PHP: Могу ли я разбить JSONstring на первую глубину без перекодирования? - PullRequest
0 голосов
/ 08 июня 2018

Поскольку я не знаю, может ли behat внедрить параметры моей функции Behat FeatureContext с чем-либо, кроме строк, я хотел бы знать, могу ли я разделить строки таким образом, чтобы у меня остался массив json_objects.

Мне удалось сделать это с json_decode и json_encode, но это кажется немного повторяющимся, когда я сначала декодирую строку объектов, только чтобы закодировать ее обратно в один объект.

В каждом примере есть следующая функция Behat:

Feature: Provide a consistent standard JSON API endpoint

  In order to build interchangeable front ends
  As a JSON API developer
  I need to allow Create, Read, Update, and Delete functionality

  Background:
    Given there are Albums with the following details:
      """
      [{
        "artist":"Pink Floyd",
        "title":"The Dark Side of the Moon",
        "songs":[
          {"title":"Speak to Me", "length":254}
          {"title":"Breathe", "length":192}
          {"title":"On the Run", "length":188}
        ] 
      },
      {
        "artist":"AC/DC",
        "title":"Back to Black",
        "songs":[
          {"title":"Hells Bells", "length":205}
          {"title":"Shoot to Thrill", "length":302}
          {"title":"What Do You Do for Money Honey", "length":244}
        ] 
      }]    
      """
      And the "Content-Type" request header is "application/json"

и следующая функция в FeatureContext.php:

...

public function thereAreAlbumsWithTheFollowingDetails(string $jsonString) {
    $albums = json_decode($jsonString, true);

    foreach ($albums as $album) {
        $albumJson = json_encode($album);
        $this->apiContext->setRequestBody($albumJson);
        $this->apiContext->requestPath("/api/album", "POST");
    }
}

...

Ответы [ 2 ]

0 голосов
/ 25 июня 2018

Я следовал руководству, которое добавляло первые тестовые объекты через REST, но этого не должно происходить.

Я также узнал, что вложенные таблицы для Behat - плохая идея.

https://joebuschmann.com/specflow-nested-tables-a-bad-idea/

behat.yml

default:
    suites:
        default:
            contexts:
                - App\Features\Bootstrap\FeatureContext:
                    container: '@service_container'
                    entityManager: "@doctrine.orm.default_entity_manager"
                - Imbo\BehatApiExtension\Context\ApiContext
    extensions:
        Imbo\BehatApiExtension:
            apiClient:
                base_uri: http://127.0.0.1:8000
        Behat\Symfony2Extension:
            kernel:
                bootstrap: config\behat\bootstrap.php
                class: App\Kernel

Код ниже не совсем правильный, но он достаточно близок.

FeatureContext.php

...

/**
     * @Given there are Albums with the following details:
     */
    public function thereAreAlbumsWithTheFollowingDetails(TableNode $table) {
        foreach ($table->getColumnsHash() as $row) {
            $album = new Album();
            $album->setTitle($row['title']);
            $album->setReleaseDate(new \DateTime($row['release_date']));
            array_push($this->entities, $album);
        }
        $this->em->flush();
    }

    /**
     * @Given albums with the following Songs:
     */
    public function albumsWithTheFollowingSongs(TableNode $table) {
        $i = 0;
        foreach ($table->getColumnsHash() as $row) {
            $song = new Song($row['title']);
            $this->entities[$i]->setSong($song);
            $i = $i + 1;
        }
    }

    /**
     * @When they are saved into the database
     */
    public function theyAreSavedIntoTheDatabase() {
        foreach ($this->entities as $entity) {
            $this->em->persist($entity);
        }
        $this->em->flush();
    }
...
0 голосов
/ 09 июня 2018

Насколько я понимаю, вы хотите добавить некоторые данные для настройки сценария, в этом случае я бы отошел от json, поскольку это деталь реализации:

Given there are Albums with the following details:
  | artist     | title                     | songs                            |
  | Pink Floyd | The Dark Side of the Moon | Speak to Me, Breathe, On the Run |
  | AC/DC      | Back to Black             | Hells Bells, Shoot to Thrill, What Do You Do for Money Honey |
...

Затем на FeatureContext преобразовать данные в json, если вам это нужно, но лично, если вы сделали это правильно, я бы просто внедрил тот же сервис, который должен использоваться в контроллере / api / album для создания альбомов.

...