trait GetDocumentFromResponseTrait

Same name in other branches
  1. 10 core/modules/jsonapi/tests/src/Traits/GetDocumentFromResponseTrait.php \Drupal\Tests\jsonapi\Traits\GetDocumentFromResponseTrait

Test trait for retrieving the JSON:API document from a response.

Hierarchy

4 files declare their use of GetDocumentFromResponseTrait
EntryPointTest.php in core/modules/jsonapi/tests/src/Functional/EntryPointTest.php
ExternalNormalizersTest.php in core/modules/jsonapi/tests/src/Functional/ExternalNormalizersTest.php
JsonApiFunctionalTestBase.php in core/modules/jsonapi/tests/src/Functional/JsonApiFunctionalTestBase.php
ResourceTestBase.php in core/modules/jsonapi/tests/src/Functional/ResourceTestBase.php

File

core/modules/jsonapi/tests/src/Traits/GetDocumentFromResponseTrait.php, line 14

Namespace

Drupal\Tests\jsonapi\Traits
View source
trait GetDocumentFromResponseTrait {
    
    /**
     * Retrieve document from response, with basic validation.
     *
     * @param \Psr\Http\Message\ResponseInterface $response
     *   Response to extract JSON:API document from.
     * @param bool $validate
     *   Determines whether the data is validated or not. Defaults to TRUE.
     *
     * @return ?array
     *   JSON:API document extracted from the response, or NULL.
     *
     * @throws \PHPUnit\Framework\AssertionFailedError
     *   Thrown when the document does not pass basic validation against the spec.
     */
    protected function getDocumentFromResponse(ResponseInterface $response, bool $validate = TRUE) : ?array {
        assert($this instanceof TestCase);
        $document = Json::decode((string) $response->getBody());
        if (isset($document['data']) && isset($document['errors'])) {
            $this->fail('Document contains both data and errors members; only one is allowed.');
        }
        if ($validate === TRUE && !isset($document['data'])) {
            if (isset($document['errors'])) {
                $errors = [];
                foreach ($document['errors'] as $error) {
                    $errors[] = $error['title'] . ' (' . $error['status'] . '): ' . $error['detail'];
                }
                $this->fail('Missing expected data member in document. Error(s): ' . PHP_EOL . '  ' . implode('  ' . PHP_EOL, $errors));
            }
            $this->fail('Missing both data and errors members in document; either is required. Response body: ' . PHP_EOL . '  ' . $response->getBody());
        }
        return $document;
    }

}

Members

Title Sort descending Modifiers Object type Summary
GetDocumentFromResponseTrait::getDocumentFromResponse protected function Retrieve document from response, with basic validation.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.