View source
<?php
namespace Drupal\Tests\jsonapi\Functional;
use Drupal\Component\Serialization\Json;
use Drupal\Component\Utility\NestedArray;
use Drupal\Component\Utility\Random;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultReasonInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\CacheableResponseInterface;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\ContentEntityNullStorage;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Entity\RevisionableInterface;
use Drupal\Core\Entity\RevisionLogInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\Plugin\Field\FieldType\BooleanItem;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\TypedData\DataReferenceTargetDefinition;
use Drupal\Core\TypedData\TypedDataInternalPropertiesHelper;
use Drupal\Core\Url;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\jsonapi\BackwardCompatibility\tests\Traits\ContentModerationTestTrait;
use Drupal\jsonapi\JsonApiResource\LinkCollection;
use Drupal\jsonapi\JsonApiResource\NullIncludedData;
use Drupal\jsonapi\JsonApiResource\Link;
use Drupal\jsonapi\JsonApiResource\ResourceObject;
use Drupal\jsonapi\JsonApiResource\ResourceObjectData;
use Drupal\jsonapi\Normalizer\HttpExceptionNormalizer;
use Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel;
use Drupal\jsonapi\ResourceResponse;
use Drupal\path\Plugin\Field\FieldType\PathItem;
use Drupal\Tests\BrowserTestBase;
use Drupal\user\Entity\Role;
use Drupal\user\EntityOwnerInterface;
use Drupal\user\RoleInterface;
use Drupal\user\UserInterface;
use GuzzleHttp\RequestOptions;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\HttpFoundation\Response;
abstract class ResourceTestBase extends BrowserTestBase {
use ResourceResponseTestTrait;
use ContentModerationTestTrait;
use JsonApiRequestTestTrait;
protected static $modules = [
'jsonapi',
'basic_auth',
'rest_test',
'jsonapi_test_field_access',
'text',
];
protected static $entityTypeId = NULL;
protected static $resourceTypeName = NULL;
protected static $resourceTypeIsVersionable = FALSE;
protected $resourceType;
protected static $patchProtectedFieldNames;
protected static $uniqueFieldNames = [];
protected static $firstCreatedEntityId = 2;
protected static $secondCreatedEntityId = 3;
protected static $labelFieldName = NULL;
protected static $newRevisionsShouldBeAutomatic = FALSE;
protected static $anonymousUsersCanViewLabels = FALSE;
protected static $jsonApiMember = [
'version' => '1.0',
'meta' => [
'links' => [
'self' => [
'href' => 'http://jsonapi.org/format/1.0/',
],
],
],
];
protected $entity;
protected $anotherEntity;
protected $account;
protected $entityStorage;
protected $uuidKey;
protected $serializer;
public function setUp() {
parent::setUp();
$this->serializer = $this->container
->get('jsonapi.serializer');
$user_role = Role::load(RoleInterface::ANONYMOUS_ID);
foreach ($user_role
->getPermissions() as $permission) {
$user_role
->revokePermission($permission);
}
$user_role
->save();
assert([] === $user_role
->getPermissions(), 'The anonymous user role has no permissions at all.');
$user_role = Role::load(RoleInterface::AUTHENTICATED_ID);
foreach ($user_role
->getPermissions() as $permission) {
$user_role
->revokePermission($permission);
}
$user_role
->save();
assert([] === $user_role
->getPermissions(), 'The authenticated user role has no permissions at all.');
$this->account = $this
->createUser();
$this->container
->get('current_user')
->setAccount($this->account);
$entity_type_manager = $this->container
->get('entity_type.manager');
$this->entityStorage = $entity_type_manager
->getStorage(static::$entityTypeId);
$this->uuidKey = $entity_type_manager
->getDefinition(static::$entityTypeId)
->getKey('uuid');
$this->entity = $this
->setUpFields($this
->createEntity(), $this->account);
$this->resourceType = $this->container
->get('jsonapi.resource_type.repository')
->getByTypeName(static::$resourceTypeName);
}
protected function setUpFields(EntityInterface $entity, UserInterface $account) {
if (!$entity instanceof FieldableEntityInterface) {
return $entity;
}
$entity_bundle = $entity
->bundle();
$account_bundle = $account
->bundle();
FieldStorageConfig::create([
'entity_type' => static::$entityTypeId,
'field_name' => 'field_rest_test',
'type' => 'text',
])
->setCardinality(1)
->save();
FieldConfig::create([
'entity_type' => static::$entityTypeId,
'field_name' => 'field_rest_test',
'bundle' => $entity_bundle,
])
->setLabel('Test field')
->setTranslatable(FALSE)
->save();
FieldStorageConfig::create([
'entity_type' => static::$entityTypeId,
'field_name' => 'field_jsonapi_test_entity_ref',
'type' => 'entity_reference',
])
->setSetting('target_type', 'user')
->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
->save();
FieldConfig::create([
'entity_type' => static::$entityTypeId,
'field_name' => 'field_jsonapi_test_entity_ref',
'bundle' => $entity_bundle,
])
->setTranslatable(FALSE)
->setSetting('handler', 'default')
->setSetting('handler_settings', [
'target_bundles' => NULL,
])
->save();
FieldStorageConfig::create([
'entity_type' => static::$entityTypeId,
'field_name' => 'field_rest_test_multivalue',
'type' => 'string',
])
->setCardinality(3)
->save();
FieldConfig::create([
'entity_type' => static::$entityTypeId,
'field_name' => 'field_rest_test_multivalue',
'bundle' => $entity_bundle,
])
->setLabel('Test field: multi-value')
->setTranslatable(FALSE)
->save();
\Drupal::service('router.builder')
->rebuildIfNeeded();
$reloaded_entity = $this
->entityLoadUnchanged($entity
->id());
if ($reloaded_entity !== NULL) {
$entity = $reloaded_entity;
$entity
->set('field_rest_test', [
'value' => 'All the faith he had had had had no effect on the outcome of his life.',
]);
$entity
->set('field_jsonapi_test_entity_ref', [
'user' => $account
->id(),
]);
$entity
->set('field_rest_test_multivalue', [
[
'value' => 'One',
],
[
'value' => 'Two',
],
]);
$entity
->save();
}
return $entity;
}
protected function getData() {
if ($this->entityStorage
->getQuery()
->count()
->execute() < 2) {
$this
->createAnotherEntity('two');
}
$query = $this->entityStorage
->getQuery()
->sort($this->entity
->getEntityType()
->getKey('id'));
return $this->entityStorage
->loadMultiple($query
->execute());
}
protected function normalize(EntityInterface $entity, Url $url) {
$self_link = new Link(new CacheableMetadata(), $url, [
'self',
]);
$resource_type = $this->container
->get('jsonapi.resource_type.repository')
->getByTypeName(static::$resourceTypeName);
$doc = new JsonApiDocumentTopLevel(new ResourceObjectData([
ResourceObject::createFromEntity($resource_type, $entity),
], 1), new NullIncludedData(), new LinkCollection([
'self' => $self_link,
]));
return $this->serializer
->normalize($doc, 'api_json', [
'resource_type' => $resource_type,
'account' => $this->account,
])
->getNormalization();
}
protected abstract function createEntity();
protected function createAnotherEntity($key) {
$duplicate = $this
->getEntityDuplicate($this->entity, $key);
if (get_class($this->entityStorage) !== ContentEntityNullStorage::class) {
$duplicate
->set('field_rest_test', 'Second collection entity');
}
$duplicate
->save();
return $duplicate;
}
protected function getEntityDuplicate(EntityInterface $original, $key) {
$duplicate = $original
->createDuplicate();
if ($label_key = $original
->getEntityType()
->getKey('label')) {
$duplicate
->set($label_key, $original
->label() . '_' . $key);
}
if ($duplicate instanceof ConfigEntityInterface && ($id_key = $duplicate
->getEntityType()
->getKey('id'))) {
$id = $original
->id();
$id_key = $duplicate
->getEntityType()
->getKey('id');
$duplicate
->set($id_key, $id . '_' . $key);
}
return $duplicate;
}
protected abstract function getExpectedDocument();
protected abstract function getPostDocument();
protected function getPatchDocument() {
return NestedArray::mergeDeep([
'data' => [
'id' => $this->entity
->uuid(),
],
], $this
->getPostDocument());
}
protected function getExpectedUnauthorizedAccessCacheability() {
return (new CacheableMetadata())
->setCacheTags([
'4xx-response',
'http_response',
])
->setCacheContexts([
'url.site',
'user.permissions',
])
->addCacheContexts($this->entity
->getEntityType()
->isRevisionable() ? [
'url.query_args:resourceVersion',
] : []);
}
protected function getExpectedCacheTags(array $sparse_fieldset = NULL) {
$expected_cache_tags = [
'http_response',
];
return Cache::mergeTags($expected_cache_tags, $this->entity
->getCacheTags());
}
protected function getExpectedCacheContexts(array $sparse_fieldset = NULL) {
$cache_contexts = [
'url.query_args:fields',
'url.query_args:include',
'url.site',
'user.permissions',
];
$entity_type = $this->entity
->getEntityType();
return Cache::mergeContexts($cache_contexts, $entity_type
->isRevisionable() ? [
'url.query_args:resourceVersion',
] : []);
}
protected static function getExpectedCollectionCacheability(AccountInterface $account, array $collection, array $sparse_fieldset = NULL, $filtered = FALSE) {
$cacheability = array_reduce($collection, function (CacheableMetadata $cacheability, EntityInterface $entity) use ($sparse_fieldset, $account) {
$access_result = static::entityAccess($entity, 'view', $account);
if (!$access_result
->isAllowed()) {
$access_result = static::entityAccess($entity, 'view label', $account)
->addCacheableDependency($access_result);
}
$cacheability
->addCacheableDependency($access_result);
if ($access_result
->isAllowed()) {
$cacheability
->addCacheableDependency($entity);
if ($entity instanceof FieldableEntityInterface) {
foreach ($entity as $field_name => $field_item_list) {
if (is_null($sparse_fieldset) || in_array($field_name, $sparse_fieldset)) {
$field_access = static::entityFieldAccess($entity, $field_name, 'view', $account);
$cacheability
->addCacheableDependency($field_access);
if ($field_access
->isAllowed()) {
foreach ($field_item_list as $field_item) {
foreach (TypedDataInternalPropertiesHelper::getNonInternalProperties($field_item) as $property) {
$cacheability
->addCacheableDependency(CacheableMetadata::createFromObject($property));
}
}
}
}
}
}
}
return $cacheability;
}, new CacheableMetadata());
$entity_type = reset($collection)
->getEntityType();
$cacheability
->addCacheTags([
'http_response',
]);
$cacheability
->addCacheTags($entity_type
->getListCacheTags());
$cache_contexts = [
'url.query_args:fields',
'url.query_args:filter',
'url.query_args:include',
'url.query_args:page',
'url.query_args:sort',
'url.site',
];
$cache_contexts = Cache::mergeContexts($cache_contexts, $entity_type
->isRevisionable() ? [
'url.query_args:resourceVersion',
] : []);
$cacheability
->addCacheContexts($cache_contexts);
return $cacheability;
}
protected abstract function setUpAuthorization($method);
protected function setUpRevisionAuthorization($method) {
assert($method === 'GET', 'Only read operations on revisions are supported.');
$this
->setUpAuthorization($method);
}
protected function getExpectedUnauthorizedAccessMessage($method) {
$permission = $this->entity
->getEntityType()
->getAdminPermission();
if ($permission !== FALSE) {
return "The '{$permission}' permission is required.";
}
return NULL;
}
protected function grantPermissionsToTestedRole(array $permissions) {
$this
->grantPermissions(Role::load(RoleInterface::AUTHENTICATED_ID), $permissions);
}
protected function revokePermissionsFromTestedRole(array $permissions) {
$role = Role::load(RoleInterface::AUTHENTICATED_ID);
foreach ($permissions as $permission) {
$role
->revokePermission($permission);
}
$role
->trustData()
->save();
}
protected function assertResourceResponse($expected_status_code, $expected_document, ResponseInterface $response, $expected_cache_tags = FALSE, $expected_cache_contexts = FALSE, $expected_page_cache_header_value = FALSE, $expected_dynamic_page_cache_header_value = FALSE) {
$this
->assertSame($expected_status_code, $response
->getStatusCode(), var_export(Json::decode((string) $response
->getBody()), TRUE));
if ($expected_status_code === 204) {
$this
->assertSame('', (string) $response
->getBody());
}
else {
$this
->assertSame([
'application/vnd.api+json',
], $response
->getHeader('Content-Type'));
if ($expected_document !== FALSE) {
$response_document = Json::decode((string) $response
->getBody());
if ($expected_document === NULL) {
$this
->assertNull($response_document);
}
else {
$this
->assertSameDocument($expected_document, $response_document);
}
}
}
$this
->assertSame($expected_cache_tags !== FALSE, $response
->hasHeader('X-Drupal-Cache-Tags'));
if (is_array($expected_cache_tags)) {
$this
->assertSame($expected_cache_tags, explode(' ', $response
->getHeader('X-Drupal-Cache-Tags')[0]));
}
$this
->assertSame($expected_cache_contexts !== FALSE, $response
->hasHeader('X-Drupal-Cache-Contexts'));
if (is_array($expected_cache_contexts)) {
$optimized_expected_cache_contexts = \Drupal::service('cache_contexts_manager')
->optimizeTokens($expected_cache_contexts);
$this
->assertSame($optimized_expected_cache_contexts, explode(' ', $response
->getHeader('X-Drupal-Cache-Contexts')[0]));
}
if ($expected_page_cache_header_value !== FALSE) {
$this
->assertTrue($response
->hasHeader('X-Drupal-Cache'));
$this
->assertSame($expected_page_cache_header_value, $response
->getHeader('X-Drupal-Cache')[0]);
}
else {
$this
->assertFalse($response
->hasHeader('X-Drupal-Cache'));
}
if ($expected_dynamic_page_cache_header_value !== FALSE) {
$this
->assertTrue($response
->hasHeader('X-Drupal-Dynamic-Cache'));
$this
->assertSame($expected_dynamic_page_cache_header_value, $response
->getHeader('X-Drupal-Dynamic-Cache')[0]);
}
else {
$this
->assertFalse($response
->hasHeader('X-Drupal-Dynamic-Cache'));
}
}
protected function assertSameDocument(array $expected_document, array $actual_document) {
static::recursiveKsort($expected_document);
static::recursiveKsort($actual_document);
if (!empty($expected_document['included'])) {
static::sortResourceCollection($expected_document['included']);
static::sortResourceCollection($actual_document['included']);
}
if (isset($actual_document['meta']['omitted']) && isset($expected_document['meta']['omitted'])) {
$actual_omitted =& $actual_document['meta']['omitted'];
$expected_omitted =& $expected_document['meta']['omitted'];
static::sortOmittedLinks($actual_omitted);
static::sortOmittedLinks($expected_omitted);
static::resetOmittedLinkKeys($actual_omitted);
static::resetOmittedLinkKeys($expected_omitted);
}
$expected_keys = array_keys($expected_document);
$actual_keys = array_keys($actual_document);
$missing_member_names = array_diff($expected_keys, $actual_keys);
$extra_member_names = array_diff($actual_keys, $expected_keys);
if (!empty($missing_member_names) || !empty($extra_member_names)) {
$message_format = "The document members did not match the expected values. Missing: [ %s ]. Unexpected: [ %s ]";
$message = sprintf($message_format, implode(', ', $missing_member_names), implode(', ', $extra_member_names));
$this
->assertSame($expected_document, $actual_document, $message);
}
foreach ($expected_document as $member_name => $expected_member) {
$actual_member = $actual_document[$member_name];
$this
->assertSame($expected_member, $actual_member, "The '{$member_name}' member was not as expected.");
}
}
protected function assertResourceErrorResponse($expected_status_code, $expected_message, $via_link, ResponseInterface $response, $pointer = FALSE, $expected_cache_tags = FALSE, $expected_cache_contexts = FALSE, $expected_page_cache_header_value = FALSE, $expected_dynamic_page_cache_header_value = FALSE) {
assert(is_null($via_link) || $via_link instanceof Url);
$expected_error = [];
if (!empty(Response::$statusTexts[$expected_status_code])) {
$expected_error['title'] = Response::$statusTexts[$expected_status_code];
}
$expected_error['status'] = (string) $expected_status_code;
$expected_error['detail'] = $expected_message;
if ($via_link) {
$expected_error['links']['via']['href'] = $via_link
->setAbsolute()
->toString();
}
if ($info_url = HttpExceptionNormalizer::getInfoUrl($expected_status_code)) {
$expected_error['links']['info']['href'] = $info_url;
}
if ($pointer !== FALSE) {
$expected_error['source']['pointer'] = $pointer;
}
$expected_document = [
'jsonapi' => static::$jsonApiMember,
'errors' => [
0 => $expected_error,
],
];
$this
->assertResourceResponse($expected_status_code, $expected_document, $response, $expected_cache_tags, $expected_cache_contexts, $expected_page_cache_header_value, $expected_dynamic_page_cache_header_value);
}
protected function removeResourceTypeFromDocument(array $document) {
unset($document['data']['type']);
return $document;
}
protected function makeNormalizationInvalid(array $document, $entity_key) {
$entity_type = $this->entity
->getEntityType();
switch ($entity_key) {
case 'label':
$label_field = $entity_type
->hasKey('label') ? $entity_type
->getKey('label') : static::$labelFieldName;
$document['data']['attributes'][$label_field] = [
0 => $document['data']['attributes'][$label_field],
1 => 'Second Title',
];
break;
case 'id':
$document['data']['attributes'][$entity_type
->getKey('id')] = $this->anotherEntity
->id();
break;
case 'uuid':
$document['data']['id'] = $this->anotherEntity
->uuid();
break;
}
return $document;
}
public function testGetIndividual() {
$url = Url::fromRoute(sprintf('jsonapi.%s.individual', static::$resourceTypeName), [
'entity' => $this->entity
->uuid(),
]);
$request_options = [];
$request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
$request_options = NestedArray::mergeDeep($request_options, $this
->getAuthenticationRequestOptions());
$response = $this
->request('GET', $url, $request_options);
if (!static::$anonymousUsersCanViewLabels) {
$expected_403_cacheability = $this
->getExpectedUnauthorizedAccessCacheability();
$reason = $this
->getExpectedUnauthorizedAccessMessage('GET');
$message = trim("The current user is not allowed to GET the selected resource. {$reason}");
$this
->assertResourceErrorResponse(403, $message, $url, $response, '/data', $expected_403_cacheability
->getCacheTags(), $expected_403_cacheability
->getCacheContexts(), FALSE, 'MISS');
$this
->assertArrayNotHasKey('Link', $response
->getHeaders());
}
else {
$expected_document = $this
->getExpectedDocument();
$label_field_name = $this->entity
->getEntityType()
->hasKey('label') ? $this->entity
->getEntityType()
->getKey('label') : static::$labelFieldName;
$expected_document['data']['attributes'] = array_intersect_key($expected_document['data']['attributes'], [
$label_field_name => TRUE,
]);
unset($expected_document['data']['relationships']);
$dynamic_cache_label_only = !empty(array_intersect([
'user',
'session',
], $this
->getExpectedCacheContexts([
$label_field_name,
]))) ? 'UNCACHEABLE' : 'MISS';
$this
->assertResourceResponse(200, $expected_document, $response, $this
->getExpectedCacheTags(), $this
->getExpectedCacheContexts([
$label_field_name,
]), FALSE, $dynamic_cache_label_only);
}
$this
->setUpAuthorization('GET');
$request_options[RequestOptions::BODY] = Json::encode($this
->getExpectedDocument());
$url_reserved_custom_query_parameter = clone $url;
$url_reserved_custom_query_parameter = $url_reserved_custom_query_parameter
->setOption('query', [
'foo' => 'bar',
]);
$response = $this
->request('GET', $url_reserved_custom_query_parameter, $request_options);
$expected_document = [
'jsonapi' => static::$jsonApiMember,
'errors' => [
[
'title' => 'Bad Request',
'status' => '400',
'detail' => "The following query parameters violate the JSON:API spec: 'foo'.",
'links' => [
'info' => [
'href' => 'http://jsonapi.org/format/#query-parameters',
],
'via' => [
'href' => $url_reserved_custom_query_parameter
->toString(),
],
],
],
],
];
$this
->assertResourceResponse(400, $expected_document, $response, [
'4xx-response',
'http_response',
], [
'url.query_args',
'url.site',
], FALSE, 'MISS');
$response = $this
->request('HEAD', $url, $request_options);
$dynamic_cache = !empty(array_intersect([
'user',
'session',
], $this
->getExpectedCacheContexts())) ? 'UNCACHEABLE' : 'MISS';
$this
->assertResourceResponse(200, NULL, $response, $this
->getExpectedCacheTags(), $this
->getExpectedCacheContexts(), FALSE, $dynamic_cache);
$head_headers = $response
->getHeaders();
$response = $this
->request('GET', $url, $request_options);
$this
->assertResourceResponse(200, $this
->getExpectedDocument(), $response, $this
->getExpectedCacheTags(), $this
->getExpectedCacheContexts(), FALSE, $dynamic_cache === 'MISS' ? 'HIT' : 'UNCACHEABLE');
$cache_items = $this->container
->get('database')
->query("SELECT cid, data FROM {cache_dynamic_page_cache} WHERE cid LIKE :pattern", [
':pattern' => '%[route]=jsonapi.%',
])
->fetchAllAssoc('cid');
$this
->assertTrue(count($cache_items) >= 2);
$found_cache_redirect = FALSE;
$found_cached_200_response = FALSE;
$other_cached_responses_are_4xx = TRUE;
foreach ($cache_items as $cid => $cache_item) {
$cached_data = unserialize($cache_item->data);
if (!isset($cached_data['#cache_redirect'])) {
$cached_response = $cached_data['#response'];
if ($cached_response
->getStatusCode() === 200) {
$found_cached_200_response = TRUE;
}
elseif (!$cached_response
->isClientError()) {
$other_cached_responses_are_4xx = FALSE;
}
$this
->assertNotInstanceOf(ResourceResponse::class, $cached_response);
$this
->assertInstanceOf(CacheableResponseInterface::class, $cached_response);
}
else {
$found_cache_redirect = TRUE;
}
}
$this
->assertTrue($found_cache_redirect);
$this
->assertSame($dynamic_cache !== 'UNCACHEABLE' || isset($dynamic_cache_label_only) && $dynamic_cache_label_only !== 'UNCACHEABLE', $found_cached_200_response);
$this
->assertTrue($other_cached_responses_are_4xx);
$unserialized = $this->serializer
->deserialize((string) $response
->getBody(), JsonApiDocumentTopLevel::class, 'api_json', [
'target_entity' => static::$entityTypeId,
'resource_type' => $this->container
->get('jsonapi.resource_type.repository')
->getByTypeName(static::$resourceTypeName),
]);
$this
->assertSame($unserialized
->uuid(), $this->entity
->uuid());
$get_headers = $response
->getHeaders();
$ignored_headers = [
'Date',
'Content-Length',
'X-Drupal-Cache',
'X-Drupal-Dynamic-Cache',
'Transfer-Encoding',
'Vary',
];
$header_cleaner = function ($headers) use ($ignored_headers) {
foreach ($headers as $header => $value) {
if (strpos($header, 'X-Drupal-Assertion-') === 0 || in_array($header, $ignored_headers)) {
unset($headers[$header]);
}
}
return $headers;
};
$get_headers = $header_cleaner($get_headers);
$head_headers = $header_cleaner($head_headers);
$this
->assertSame($get_headers, $head_headers);
$this
->doTestSparseFieldSets($url, $request_options);
$this
->doTestIncluded($url, $request_options);
$random_uuid = \Drupal::service('uuid')
->generate();
$url = Url::fromRoute(sprintf('jsonapi.%s.individual', static::$resourceTypeName), [
'entity' => $random_uuid,
]);
$response = $this
->request('GET', $url, $request_options);
$message_url = clone $url;
$path = str_replace($random_uuid, '{entity}', $message_url
->setAbsolute()
->setOptions([
'base_url' => '',
'query' => [],
])
->toString());
$message = 'The "entity" parameter was not converted for the path "' . $path . '" (route name: "jsonapi.' . static::$resourceTypeName . '.individual")';
$this
->assertResourceErrorResponse(404, $message, $url, $response, FALSE, [
'4xx-response',
'http_response',
], [
'url.site',
], FALSE, 'UNCACHEABLE');
unset($request_options[RequestOptions::HEADERS]['Accept']);
$response = $this
->request('GET', $url, $request_options);
$this
->assertResourceErrorResponse(404, $message, $url, $response, FALSE, [
'4xx-response',
'http_response',
], [
'url.site',
], FALSE, 'UNCACHEABLE');
}
public function testCollection() {
$entity_collection = $this
->getData();
assert(count($entity_collection) > 1, 'A collection must have more that one entity in it.');
$collection_url = Url::fromRoute(sprintf('jsonapi.%s.collection', static::$resourceTypeName))
->setAbsolute(TRUE);
$request_options = [];
$request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
$request_options = NestedArray::mergeDeep($request_options, $this
->getAuthenticationRequestOptions());
$expected_response = $this
->getExpectedCollectionResponse($entity_collection, $collection_url
->toString(), $request_options);
$expected_cacheability = $expected_response
->getCacheableMetadata();
$response = $this
->request('HEAD', $collection_url, $request_options);
$dynamic_cache = $expected_cacheability
->getCacheMaxAge() === 0 ? 'UNCACHEABLE' : 'MISS';
$this
->assertResourceResponse(200, NULL, $response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, $dynamic_cache);
$default_sort = [
'sort' => 'drupal_internal__' . $this->entity
->getEntityType()
->getKey('id'),
];
$collection_url
->setOption('query', $default_sort);
$expected_response = $this
->getExpectedCollectionResponse($entity_collection, $collection_url
->toString(), $request_options);
$expected_cacheability = $expected_response
->getCacheableMetadata();
$expected_document = $expected_response
->getResponseData();
$response = $this
->request('GET', $collection_url, $request_options);
$this
->assertResourceResponse(200, $expected_document, $response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, $dynamic_cache);
$this
->setUpAuthorization('GET');
$expected_response = $this
->getExpectedCollectionResponse($entity_collection, $collection_url
->toString(), $request_options);
$expected_cacheability = $expected_response
->getCacheableMetadata();
$response = $this
->request('HEAD', $collection_url, $request_options);
$this
->assertResourceResponse(200, NULL, $response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, $dynamic_cache);
$expected_response = $this
->getExpectedCollectionResponse($entity_collection, $collection_url
->toString(), $request_options);
$expected_cacheability = $expected_response
->getCacheableMetadata();
$expected_document = $expected_response
->getResponseData();
$response = $this
->request('GET', $collection_url, $request_options);
$dynamic_cache = $dynamic_cache === 'UNCACHEABLE' ? 'UNCACHEABLE' : 'HIT';
$this
->assertResourceResponse(200, $expected_document, $response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, $dynamic_cache);
if ($this->entity instanceof FieldableEntityInterface) {
$unauthorized_filter_url = clone $collection_url;
$unauthorized_filter_url
->setOption('query', [
'filter' => [
'related_author_id' => [
'operator' => '<>',
'path' => 'field_jsonapi_test_entity_ref.status',
'value' => 'doesnt@matter.com',
],
],
]);
$response = $this
->request('GET', $unauthorized_filter_url, $request_options);
$expected_error_message = "The current user is not authorized to filter by the `field_jsonapi_test_entity_ref` field, given in the path `field_jsonapi_test_entity_ref`. The 'field_jsonapi_test_entity_ref view access' permission is required.";
$expected_cache_tags = [
'4xx-response',
'http_response',
];
$expected_cache_contexts = [
'url.query_args:filter',
'url.query_args:sort',
'url.site',
'user.permissions',
];
$this
->assertResourceErrorResponse(403, $expected_error_message, $unauthorized_filter_url, $response, FALSE, $expected_cache_tags, $expected_cache_contexts, FALSE, 'MISS');
$this
->grantPermissionsToTestedRole([
'field_jsonapi_test_entity_ref view access',
]);
$response = $this
->request('GET', $unauthorized_filter_url, $request_options);
$expected_error_message = "The current user is not authorized to filter by the `status` field, given in the path `field_jsonapi_test_entity_ref.entity:user.status`.";
$this
->assertResourceErrorResponse(403, $expected_error_message, $unauthorized_filter_url, $response, FALSE, $expected_cache_tags, $expected_cache_contexts, FALSE, 'MISS');
}
$filtered_entity_collection = $entity_collection;
$removed = array_shift($filtered_entity_collection);
$filtered_collection_url = clone $collection_url;
$entity_collection_filter = [
'filter' => [
'ids' => [
'condition' => [
'operator' => '<>',
'path' => 'id',
'value' => $removed
->uuid(),
],
],
],
];
$filtered_collection_url
->setOption('query', $entity_collection_filter + $default_sort);
$expected_response = $this
->getExpectedCollectionResponse($filtered_entity_collection, $filtered_collection_url
->toString(), $request_options, NULL, TRUE);
$expected_cacheability = $expected_response
->getCacheableMetadata();
$expected_document = $expected_response
->getResponseData();
$response = $this
->request('GET', $filtered_collection_url, $request_options);
$dynamic_cache = $expected_cacheability
->getCacheMaxAge() === 0 || !empty(array_intersect([
'user',
'session',
], $expected_cacheability
->getCacheContexts())) ? 'UNCACHEABLE' : 'MISS';
$this
->assertResourceResponse(200, $expected_document, $response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, $dynamic_cache);
$relationship_field_names = array_reduce($filtered_entity_collection, function ($relationship_field_names, $entity) {
return array_unique(array_merge($relationship_field_names, $this
->getRelationshipFieldNames($entity)));
}, []);
$include = [
'include' => implode(',', $relationship_field_names),
];
$filtered_collection_include_url = clone $collection_url;
$filtered_collection_include_url
->setOption('query', $entity_collection_filter + $include + $default_sort);
$expected_response = $this
->getExpectedCollectionResponse($filtered_entity_collection, $filtered_collection_include_url
->toString(), $request_options, $relationship_field_names, TRUE);
$expected_cacheability = $expected_response
->getCacheableMetadata();
$expected_cacheability
->setCacheTags(array_values(array_diff($expected_cacheability
->getCacheTags(), [
'4xx-response',
])));
$expected_document = $expected_response
->getResponseData();
$response = $this
->request('GET', $filtered_collection_include_url, $request_options);
$dynamic_cache = $expected_cacheability
->getCacheMaxAge() === 0 || !empty(array_intersect([
'user',
'session',
], $expected_cacheability
->getCacheContexts())) ? 'UNCACHEABLE' : 'MISS';
$this
->assertResourceResponse(200, $expected_document, $response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, $dynamic_cache);
$permission_related_cache_contexts = [
'user',
'user.permissions',
'user.roles',
];
if (!empty($relationship_field_names) && !empty(array_intersect($expected_cacheability
->getCacheContexts(), $permission_related_cache_contexts))) {
$applicable_permissions = array_intersect_key(static::getIncludePermissions(), array_flip($relationship_field_names));
$flattened_permissions = array_unique(array_reduce($applicable_permissions, 'array_merge', []));
$this
->grantPermissionsToTestedRole($flattened_permissions);
$expected_response = $this
->getExpectedCollectionResponse($filtered_entity_collection, $filtered_collection_include_url
->toString(), $request_options, $relationship_field_names, TRUE);
$expected_cacheability = $expected_response
->getCacheableMetadata();
$expected_document = $expected_response
->getResponseData();
$response = $this
->request('GET', $filtered_collection_include_url, $request_options);
$requires_include_only_permissions = !empty($flattened_permissions);
$uncacheable = $expected_cacheability
->getCacheMaxAge() === 0 || !empty(array_intersect([
'user',
'session',
], $expected_cacheability
->getCacheContexts()));
$dynamic_cache = !$uncacheable ? $requires_include_only_permissions ? 'MISS' : 'HIT' : 'UNCACHEABLE';
$this
->assertResourceResponse(200, $expected_document, $response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, $dynamic_cache);
}
$sorted_entity_collection = $entity_collection;
uasort($sorted_entity_collection, function (EntityInterface $a, EntityInterface $b) {
return strcmp($b
->uuid(), $a
->uuid());
});
$sorted_collection_include_url = clone $collection_url;
$sorted_collection_include_url
->setOption('query', $include + [
'sort' => "-id",
]);
$expected_response = $this
->getExpectedCollectionResponse($sorted_entity_collection, $sorted_collection_include_url
->toString(), $request_options, $relationship_field_names);
$expected_cacheability = $expected_response
->getCacheableMetadata();
$expected_cacheability
->setCacheTags(array_values(array_diff($expected_cacheability
->getCacheTags(), [
'4xx-response',
])));
$expected_document = $expected_response
->getResponseData();
$response = $this
->request('GET', $sorted_collection_include_url, $request_options);
$dynamic_cache = $expected_cacheability
->getCacheMaxAge() === 0 ? 'UNCACHEABLE' : 'MISS';
$this
->assertResourceResponse(200, $expected_document, $response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, $dynamic_cache);
}
protected function getExpectedCollectionResponse(array $collection, $self_link, array $request_options, array $included_paths = NULL, $filtered = FALSE) {
$resource_identifiers = array_map([
static::class,
'toResourceIdentifier',
], $collection);
$individual_responses = static::toResourceResponses($this
->getResponses(static::getResourceLinks($resource_identifiers), $request_options));
$merged_response = static::toCollectionResourceResponse($individual_responses, $self_link, TRUE);
$merged_document = $merged_response
->getResponseData();
if (!isset($merged_document['data'])) {
$merged_document['data'] = [];
}
$cacheability = static::getExpectedCollectionCacheability($this->account, $collection, NULL, $filtered);
$cacheability
->setCacheMaxAge($merged_response
->getCacheableMetadata()
->getCacheMaxAge());
$collection_response = ResourceResponse::create($merged_document);
$collection_response
->addCacheableDependency($cacheability);
if (is_null($included_paths)) {
return $collection_response;
}
$related_responses = array_reduce($collection, function ($related_responses, EntityInterface $entity) use ($included_paths, $request_options, $self_link) {
if (!$entity
->access('view', $this->account) && !$entity
->access('view label', $this->account)) {
return $related_responses;
}
$expected_related_responses = $this
->getExpectedRelatedResponses($included_paths, $request_options, $entity);
if (empty($related_responses)) {
return $expected_related_responses;
}
foreach ($included_paths as $included_path) {
$both_responses = [
$related_responses[$included_path],
$expected_related_responses[$included_path],
];
$related_responses[$included_path] = static::toCollectionResourceResponse($both_responses, $self_link, TRUE);
}
return $related_responses;
}, []);
return static::decorateExpectedResponseForIncludedFields($collection_response, $related_responses);
}
public function testRelated() {
$request_options = [];
$request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
$request_options = NestedArray::mergeDeep($request_options, $this
->getAuthenticationRequestOptions());
$this
->doTestRelated($request_options);
$this
->setUpAuthorization('GET');
$this
->doTestRelated($request_options);
}
public function testRelationships() {
if ($this->entity instanceof ConfigEntityInterface) {
$this
->markTestSkipped('Configuration entities cannot have relationships.');
}
$request_options = [];
$request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
$request_options = NestedArray::mergeDeep($request_options, $this
->getAuthenticationRequestOptions());
$this
->doTestRelationshipGet($request_options);
$this
->setUpAuthorization('GET');
$this
->doTestRelationshipGet($request_options);
$this
->config('jsonapi.settings')
->set('read_only', FALSE)
->save(TRUE);
$this
->doTestRelationshipMutation($request_options);
$this
->setUpAuthorization('PATCH');
$this
->doTestRelationshipMutation($request_options);
$this
->grantPermissionsToTestedRole([
'field_jsonapi_test_entity_ref view access',
'field_jsonapi_test_entity_ref edit access',
'field_jsonapi_test_entity_ref update access',
]);
$this
->doTestRelationshipMutation($request_options);
}
protected function doTestRelated(array $request_options) {
$relationship_field_names = $this
->getRelationshipFieldNames($this->entity);
if (empty($relationship_field_names)) {
return;
}
$expected_relationship_responses = $this
->getExpectedRelatedResponses($relationship_field_names, $request_options);
$related_responses = $this
->getRelatedResponses($relationship_field_names, $request_options);
foreach ($relationship_field_names as $relationship_field_name) {
$expected_resource_response = $expected_relationship_responses[$relationship_field_name];
$actual_response = $related_responses[$relationship_field_name];
$expected_cacheability = $expected_resource_response
->getCacheableMetadata();
$this
->assertResourceResponse($expected_resource_response
->getStatusCode(), $expected_resource_response
->getResponseData(), $actual_response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, $actual_response
->getStatusCode() === 200 ? $expected_cacheability
->getCacheMaxAge() === 0 ? 'UNCACHEABLE' : 'MISS' : FALSE);
}
}
protected function doTestRelationshipGet(array $request_options) {
$relationship_field_names = $this
->getRelationshipFieldNames($this->entity);
if (empty($relationship_field_names)) {
return;
}
$related_responses = $this
->getRelationshipResponses($relationship_field_names, $request_options);
foreach ($relationship_field_names as $relationship_field_name) {
$expected_resource_response = $this
->getExpectedGetRelationshipResponse($relationship_field_name);
$expected_document = $expected_resource_response
->getResponseData();
$expected_cacheability = $expected_resource_response
->getCacheableMetadata();
$actual_response = $related_responses[$relationship_field_name];
$this
->assertResourceResponse($expected_resource_response
->getStatusCode(), $expected_document, $actual_response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, $expected_resource_response
->isSuccessful() ? 'MISS' : FALSE);
}
}
protected function doTestRelationshipMutation(array $request_options) {
$resource = $this
->createAnotherEntity('dupe');
$resource
->set('field_jsonapi_test_entity_ref', NULL);
$violations = $resource
->validate();
assert($violations
->count() === 0, (string) $violations);
$resource
->save();
$target_resource = $this
->createUser();
$violations = $target_resource
->validate();
assert($violations
->count() === 0, (string) $violations);
$target_resource
->save();
$target_identifier = static::toResourceIdentifier($target_resource);
$resource_identifier = static::toResourceIdentifier($resource);
$relationship_field_name = 'field_jsonapi_test_entity_ref';
$update_access = static::entityAccess($resource, 'update', $this->account)
->andIf(static::entityFieldAccess($resource, $relationship_field_name, 'edit', $this->account));
$url = Url::fromRoute(sprintf("jsonapi.{$resource_identifier['type']}.{$relationship_field_name}.relationship.patch"), [
'entity' => $resource
->uuid(),
]);
$response = $this
->request('POST', $url, $request_options);
$this
->assertSame(415, $response
->getStatusCode());
$request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
if ($update_access
->isAllowed()) {
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceErrorResponse(400, 'Empty request body.', $url, $response, FALSE);
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceErrorResponse(400, 'Empty request body.', $url, $response, FALSE);
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [],
]);
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceResponse(204, NULL, $response);
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [],
]);
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceResponse(204, NULL, $response);
$request_options[RequestOptions::BODY] = Json::encode([
'data' => $target_identifier,
]);
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceErrorResponse(400, 'Invalid body payload for the relationship.', $url, $response, FALSE);
$request_options[RequestOptions::BODY] = Json::encode([
'data' => $target_identifier,
]);
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceErrorResponse(400, 'Invalid body payload for the relationship.', $url, $response, FALSE);
$request_options[RequestOptions::BODY] = Json::encode([
'data' => array_intersect_key($target_identifier, [
'id' => 'id',
]),
]);
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceErrorResponse(400, 'Invalid body payload for the relationship.', $url, $response, FALSE);
$request_options[RequestOptions::BODY] = Json::encode([
'data' => array_intersect_key($target_identifier, [
'id' => 'id',
]),
]);
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceErrorResponse(400, 'Invalid body payload for the relationship.', $url, $response, FALSE);
if (static::$resourceTypeName !== $target_identifier['type']) {
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
$resource_identifier,
],
]);
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceErrorResponse(400, sprintf('The provided type (%s) does not mach the destination resource types (%s).', $resource_identifier['type'], $target_identifier['type']), $url, $response, FALSE);
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
$resource_identifier,
],
]);
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceErrorResponse(400, sprintf('The provided type (%s) does not mach the destination resource types (%s).', $resource_identifier['type'], $target_identifier['type']), $url, $response, FALSE);
}
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
$target_identifier,
$target_identifier,
],
]);
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceErrorResponse(400, 'Duplicate relationships are not permitted. Use `meta.arity` to distinguish resource identifiers with matching `type` and `id` values.', $url, $response, FALSE);
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
$target_identifier,
$target_identifier,
],
]);
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceErrorResponse(400, 'Duplicate relationships are not permitted. Use `meta.arity` to distinguish resource identifiers with matching `type` and `id` values.', $url, $response, FALSE);
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
$target_identifier,
],
]);
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceResponse(204, NULL, $response);
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceResponse(204, NULL, $response);
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
$target_identifier + [
'meta' => [
'arity' => 1,
],
],
],
]);
$response = $this
->request('POST', $url, $request_options);
$resource
->set($relationship_field_name, [
$target_resource,
$target_resource,
]);
$expected_document = $this
->getExpectedGetRelationshipDocument($relationship_field_name, $resource);
$expected_document['data'][0] += [
'meta' => [
'arity' => 0,
],
];
$expected_document['data'][1] += [
'meta' => [
'arity' => 1,
],
];
$this
->assertResourceResponse(200, $expected_document, $response);
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
$target_identifier + [
'meta' => [
'arity' => 0,
],
],
$target_identifier + [
'meta' => [
'arity' => 1,
],
],
],
]);
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceResponse(204, NULL, $response);
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
$target_identifier + [
'meta' => [
'arity' => 2,
],
],
],
]);
$response = $this
->request('POST', $url, $request_options);
$resource
->set($relationship_field_name, [
$target_resource,
$target_resource,
$target_resource,
]);
$expected_document = $this
->getExpectedGetRelationshipDocument($relationship_field_name, $resource);
$expected_document['data'][0] += [
'meta' => [
'arity' => 0,
],
];
$expected_document['data'][1] += [
'meta' => [
'arity' => 1,
],
];
$expected_document['data'][2] += [
'meta' => [
'arity' => 2,
],
];
$this
->assertResourceResponse(200, $expected_document, $response);
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
$target_identifier + [
'meta' => [
'arity' => 0,
],
],
$target_identifier + [
'meta' => [
'arity' => 1,
],
],
],
]);
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceResponse(200, $expected_document, $response);
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
$target_identifier + [
'meta' => [
'arity' => 0,
],
],
$target_identifier + [
'meta' => [
'arity' => 1,
],
],
$target_identifier + [
'meta' => [
'arity' => 2,
],
],
],
]);
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceResponse(204, NULL, $response);
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
$target_identifier + [
'meta' => [
'arity' => 0,
],
],
$target_identifier + [
'meta' => [
'arity' => 2,
],
],
],
]);
$response = $this
->request('DELETE', $url, $request_options);
$this
->assertResourceResponse(204, NULL, $response);
$resource
->set($relationship_field_name, [
$target_resource,
]);
$expected_document = $this
->getExpectedGetRelationshipDocument($relationship_field_name, $resource);
$response = $this
->request('GET', $url, $request_options);
$this
->assertSameDocument($expected_document, Json::decode((string) $response
->getBody()));
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
$target_identifier,
],
]);
$response = $this
->request('DELETE', $url, $request_options);
$resource
->set($relationship_field_name, []);
$this
->assertResourceResponse(204, NULL, $response);
$expected_document = $this
->getExpectedGetRelationshipDocument($relationship_field_name, $resource);
$response = $this
->request('GET', $url, $request_options);
$this
->assertSameDocument($expected_document, Json::decode((string) $response
->getBody()));
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
$target_identifier,
],
]);
$response = $this
->request('DELETE', $url, $request_options);
$this
->assertResourceResponse(204, NULL, $response);
$expected_document = $this
->getExpectedGetRelationshipDocument($relationship_field_name, $resource);
$response = $this
->request('GET', $url, $request_options);
$this
->assertSameDocument($expected_document, Json::decode((string) $response
->getBody()));
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
$target_identifier + [
'meta' => [
'arity' => 2,
],
],
$target_identifier + [
'meta' => [
'arity' => 3,
],
],
],
]);
$response = $this
->request('PATCH', $url, $request_options);
$resource
->set($relationship_field_name, [
$target_resource,
$target_resource,
]);
$expected_document = $this
->getExpectedGetRelationshipDocument($relationship_field_name, $resource);
$expected_document['data'][0] += [
'meta' => [
'arity' => 0,
],
];
$expected_document['data'][1] += [
'meta' => [
'arity' => 1,
],
];
$this
->assertResourceResponse(200, $expected_document, $response);
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
$target_identifier,
],
]);
$response = $this
->request('DELETE', $url, $request_options);
$resource
->set($relationship_field_name, []);
$this
->assertResourceResponse(204, NULL, $response);
$resource
->set($relationship_field_name, []);
$expected_document = $this
->getExpectedGetRelationshipDocument($relationship_field_name, $resource);
$response = $this
->request('GET', $url, $request_options);
$this
->assertSameDocument($expected_document, Json::decode((string) $response
->getBody()));
}
else {
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
$target_identifier,
],
]);
$response = $this
->request('POST', $url, $request_options);
$message = 'The current user is not allowed to edit this relationship.';
$message .= ($reason = $update_access
->getReason()) ? ' ' . $reason : '';
$this
->assertResourceErrorResponse(403, $message, $url, $response, FALSE);
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceErrorResponse(403, $message, $url, $response, FALSE);
$response = $this
->request('DELETE', $url, $request_options);
$this
->assertResourceErrorResponse(403, $message, $url, $response, FALSE);
}
$resource
->delete();
$target_resource
->delete();
}
protected function getExpectedGetRelationshipResponse($relationship_field_name, EntityInterface $entity = NULL) {
$entity = $entity ?: $this->entity;
$access = AccessResult::neutral()
->addCacheContexts($entity
->getEntityType()
->isRevisionable() ? [
'url.query_args:resourceVersion',
] : []);
$access = $access
->orIf(static::entityFieldAccess($entity, $this->resourceType
->getInternalName($relationship_field_name), 'view', $this->account));
if (!$access
->isAllowed()) {
$via_link = Url::fromRoute(sprintf('jsonapi.%s.%s.relationship.get', static::$resourceTypeName, $relationship_field_name), [
'entity' => $entity
->uuid(),
]);
return static::getAccessDeniedResponse($this->entity, $access, $via_link, $relationship_field_name, 'The current user is not allowed to view this relationship.', FALSE);
}
$expected_document = $this
->getExpectedGetRelationshipDocument($relationship_field_name, $entity);
$expected_cacheability = (new CacheableMetadata())
->addCacheTags([
'http_response',
])
->addCacheContexts([
'url.site',
'url.query_args:include',
'url.query_args:fields',
])
->addCacheableDependency($entity)
->addCacheableDependency($access);
$status_code = isset($expected_document['errors'][0]['status']) ? $expected_document['errors'][0]['status'] : 200;
$resource_response = new ResourceResponse($expected_document, $status_code);
$resource_response
->addCacheableDependency($expected_cacheability);
return $resource_response;
}
protected function getExpectedGetRelationshipDocument($relationship_field_name, EntityInterface $entity = NULL) {
$entity = $entity ?: $this->entity;
$entity_type_id = $entity
->getEntityTypeId();
$bundle = $entity
->bundle();
$id = $entity
->uuid();
$self_link = Url::fromUri("base:/jsonapi/{$entity_type_id}/{$bundle}/{$id}/relationships/{$relationship_field_name}")
->setAbsolute();
$related_link = Url::fromUri("base:/jsonapi/{$entity_type_id}/{$bundle}/{$id}/{$relationship_field_name}")
->setAbsolute();
if (static::$resourceTypeIsVersionable) {
assert($entity instanceof RevisionableInterface);
$version_query = [
'resourceVersion' => 'id:' . $entity
->getRevisionId(),
];
$self_link
->setOption('query', $version_query);
$related_link
->setOption('query', $version_query);
}
$data = $this
->getExpectedGetRelationshipDocumentData($relationship_field_name, $entity);
return [
'data' => $data,
'jsonapi' => static::$jsonApiMember,
'links' => [
'self' => [
'href' => $self_link
->toString(TRUE)
->getGeneratedUrl(),
],
'related' => [
'href' => $related_link
->toString(TRUE)
->getGeneratedUrl(),
],
],
];
}
protected function getExpectedGetRelationshipDocumentData($relationship_field_name, EntityInterface $entity = NULL) {
$entity = $entity ?: $this->entity;
$internal_field_name = $this->resourceType
->getInternalName($relationship_field_name);
$field = $entity->{$internal_field_name};
$is_multiple = $field
->getFieldDefinition()
->getFieldStorageDefinition()
->getCardinality() !== 1;
if ($field
->isEmpty()) {
return $is_multiple ? [] : NULL;
}
if (!$is_multiple) {
$target_entity = $field->entity;
return is_null($target_entity) ? NULL : static::toResourceIdentifier($target_entity);
}
else {
return array_filter(array_map(function ($item) {
$target_entity = $item->entity;
return is_null($target_entity) ? NULL : static::toResourceIdentifier($target_entity);
}, iterator_to_array($field)));
}
}
protected function getExpectedRelatedResponses(array $relationship_field_names, array $request_options, EntityInterface $entity = NULL) {
$entity = $entity ?: $this->entity;
return array_map(function ($relationship_field_name) use ($entity, $request_options) {
return $this
->getExpectedRelatedResponse($relationship_field_name, $request_options, $entity);
}, array_combine($relationship_field_names, $relationship_field_names));
}
protected function getExpectedRelatedResponse($relationship_field_name, array $request_options, EntityInterface $entity) {
$base_resource_identifier = static::toResourceIdentifier($entity);
$internal_name = $this->resourceType
->getInternalName($relationship_field_name);
$access = AccessResult::neutral()
->addCacheContexts($entity
->getEntityType()
->isRevisionable() ? [
'url.query_args:resourceVersion',
] : []);
$access = $access
->orIf(static::entityFieldAccess($entity, $internal_name, 'view', $this->account));
if (!$access
->isAllowed()) {
$detail = 'The current user is not allowed to view this relationship.';
if (!$entity
->access('view') && $entity
->access('view label') && $access instanceof AccessResultReasonInterface && empty($access
->getReason())) {
$access
->setReason("The user only has authorization for the 'view label' operation.");
if (floatval(\Drupal::VERSION) < 8.6 && $relationship_field_name === 'roles' && static::$entityTypeId === 'user' && $access
->getCacheContexts() === [
'user.permissions',
]) {
$access = $access
->setReason('');
}
}
$via_link = Url::fromRoute(sprintf('jsonapi.%s.%s.related', $base_resource_identifier['type'], $relationship_field_name), [
'entity' => $base_resource_identifier['id'],
]);
$related_response = static::getAccessDeniedResponse($entity, $access, $via_link, $relationship_field_name, $detail, FALSE);
}
else {
$self_link = static::getRelatedLink($base_resource_identifier, $relationship_field_name);
$relationship_response = $this
->getExpectedGetRelationshipResponse($relationship_field_name, $entity);
$relationship_document = $relationship_response
->getResponseData();
if (empty($relationship_document['data'])) {
$cache_contexts = Cache::mergeContexts([
'url.query_args:fields',
'url.query_args:include',
'url.site',
], $this->entity
->getEntityType()
->isRevisionable() ? [
'url.query_args:resourceVersion',
] : []);
$cacheability = (new CacheableMetadata())
->addCacheContexts($cache_contexts)
->addCacheTags([
'http_response',
]);
$related_response = isset($relationship_document['errors']) ? $relationship_response : (new ResourceResponse(static::getEmptyCollectionResponse(!is_null($relationship_document['data']), $self_link)
->getResponseData()))
->addCacheableDependency($cacheability);
}
else {
$is_to_one_relationship = static::isResourceIdentifier($relationship_document['data']);
$resource_identifiers = $is_to_one_relationship ? [
$relationship_document['data'],
] : $relationship_document['data'];
$resource_identifiers = array_filter($resource_identifiers, function ($resource_identifier) {
return $resource_identifier['id'] !== 'virtual';
});
if (!empty($resource_identifiers)) {
$individual_responses = static::toResourceResponses($this
->getResponses(static::getResourceLinks($resource_identifiers), $request_options));
$related_response = static::toCollectionResourceResponse($individual_responses, $self_link, !$is_to_one_relationship);
}
else {
$related_response = static::getEmptyCollectionResponse(!$is_to_one_relationship, $self_link);
}
}
$related_response
->addCacheableDependency($relationship_response
->getCacheableMetadata());
}
return $related_response;
}
public function testPostIndividual() {
if ($this->entity instanceof ConfigEntityInterface) {
$this
->assertTrue(TRUE, 'POSTing config entities is not yet supported.');
return;
}
$unparseable_request_body = '!{>}<';
$parseable_valid_request_body = Json::encode($this
->getPostDocument());
$parseable_invalid_request_body_missing_type = Json::encode($this
->removeResourceTypeFromDocument($this
->getPostDocument(), 'type'));
$parseable_invalid_request_body = Json::encode($this
->makeNormalizationInvalid($this
->getPostDocument(), 'label'));
$parseable_invalid_request_body_2 = Json::encode(NestedArray::mergeDeep([
'data' => [
'id' => $this
->randomMachineName(129),
],
], $this
->getPostDocument()));
$parseable_invalid_request_body_3 = Json::encode(NestedArray::mergeDeep([
'data' => [
'attributes' => [
'field_rest_test' => $this
->randomString(),
],
],
], $this
->getPostDocument()));
$parseable_invalid_request_body_4 = Json::encode(NestedArray::mergeDeep([
'data' => [
'attributes' => [
'field_nonexistent' => $this
->randomString(),
],
],
], $this
->getPostDocument()));
$url = Url::fromRoute(sprintf('jsonapi.%s.collection.post', static::$resourceTypeName));
$request_options = [];
$request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
$request_options = NestedArray::mergeDeep($request_options, $this
->getAuthenticationRequestOptions());
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceErrorResponse(405, sprintf("JSON:API is configured to accept only read operations. Site administrators can configure this at %s.", Url::fromUri('base:/admin/config/services/jsonapi')
->setAbsolute()
->toString(TRUE)
->getGeneratedUrl()), $url, $response);
if ($this->resourceType
->isLocatable()) {
$this
->assertSame([
'GET',
], $response
->getHeader('Allow'));
}
else {
$this
->assertSame([
'',
], $response
->getHeader('Allow'));
}
$this
->config('jsonapi.settings')
->set('read_only', FALSE)
->save(TRUE);
$response = $this
->request('POST', $url, $request_options);
$this
->assertSame(415, $response
->getStatusCode());
$request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
$response = $this
->request('POST', $url, $request_options);
$reason = $this
->getExpectedUnauthorizedAccessMessage('POST');
$this
->assertResourceErrorResponse(403, (string) $reason, $url, $response);
$this
->setUpAuthorization('POST');
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceErrorResponse(400, 'Empty request body.', $url, $response, FALSE);
$request_options[RequestOptions::BODY] = $unparseable_request_body;
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceErrorResponse(400, 'Syntax error', $url, $response, FALSE);
$request_options[RequestOptions::BODY] = $parseable_invalid_request_body_missing_type;
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceErrorResponse(400, 'Resource object must include a "type".', $url, $response, FALSE);
$request_options[RequestOptions::BODY] = $parseable_invalid_request_body;
$response = $this
->request('POST', $url, $request_options);
$label_field = $this->entity
->getEntityType()
->hasKey('label') ? $this->entity
->getEntityType()
->getKey('label') : static::$labelFieldName;
$label_field_capitalized = $this->entity
->getFieldDefinition($label_field)
->getLabel();
$this
->assertResourceErrorResponse(422, "{$label_field}: {$label_field_capitalized}: this field cannot hold more than 1 values.", NULL, $response, '/data/attributes/' . $label_field);
$request_options[RequestOptions::BODY] = $parseable_invalid_request_body_2;
if ($this->entity
->getEntityType()
->hasKey('uuid')) {
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceErrorResponse(422, "IDs should be properly generated and formatted UUIDs as described in RFC 4122.", $url, $response);
}
$request_options[RequestOptions::BODY] = $parseable_invalid_request_body_3;
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceErrorResponse(403, "The current user is not allowed to POST the selected field (field_rest_test).", $url, $response, '/data/attributes/field_rest_test');
$request_options[RequestOptions::BODY] = $parseable_invalid_request_body_4;
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceErrorResponse(422, sprintf("The attribute field_nonexistent does not exist on the %s resource type.", static::$resourceTypeName), $url, $response, FALSE);
$request_options[RequestOptions::BODY] = $parseable_valid_request_body;
$request_options[RequestOptions::HEADERS]['Content-Type'] = 'text/xml';
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceErrorResponse(415, 'No route found that matches "Content-Type: text/xml"', $url, $response);
$request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceResponse(201, FALSE, $response);
$this
->assertFalse($response
->hasHeader('X-Drupal-Cache'));
if (get_class($this->entityStorage) !== ContentEntityNullStorage::class) {
$created_entity = $this
->entityLoadUnchanged(static::$firstCreatedEntityId);
$uuid = $created_entity
->uuid();
$location = Url::fromRoute(sprintf('jsonapi.%s.individual', static::$resourceTypeName), [
'entity' => $uuid,
]);
if (static::$resourceTypeIsVersionable) {
assert($created_entity instanceof RevisionableInterface);
$location
->setOption('query', [
'resourceVersion' => 'id:' . $created_entity
->getRevisionId(),
]);
}
$this
->assertSame([
$location
->setAbsolute()
->toString(),
], $response
->getHeader('Location'));
$created_entity_document = $this
->normalize($created_entity, $url);
if (floatval(\Drupal::VERSION) >= 8.6) {
$decoded_response_body = Json::decode((string) $response
->getBody());
$this
->assertSame($created_entity_document, $decoded_response_body);
}
foreach ($this
->getPostDocument()['data']['attributes'] as $field_name => $field_normalization) {
if (is_array($field_normalization)) {
$this
->assertArraySubset($field_normalization, $created_entity_document['data']['attributes'][$field_name]);
}
else {
$this
->assertSame($field_normalization, $created_entity_document['data']['attributes'][$field_name]);
}
}
if (isset($this
->getPostDocument()['data']['relationships'])) {
foreach ($this
->getPostDocument()['data']['relationships'] as $field_name => $relationship_field_normalization) {
static::recursiveKsort($relationship_field_normalization);
static::recursiveKsort($created_entity_document['data']['relationships'][$field_name]);
$this
->assertSame($relationship_field_normalization, array_diff_key($created_entity_document['data']['relationships'][$field_name], [
'links' => TRUE,
]));
}
}
}
else {
$this
->assertFalse($response
->hasHeader('Location'));
}
if (get_class($this->entityStorage) !== ContentEntityNullStorage::class) {
$this->entityStorage
->load(static::$firstCreatedEntityId)
->delete();
}
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceResponse(201, FALSE, $response);
$this
->assertFalse($response
->hasHeader('X-Drupal-Cache'));
if ($this->entity
->getEntityType()
->getStorageClass() !== ContentEntityNullStorage::class && $this->entity
->getEntityType()
->hasKey('uuid')) {
$second_created_entity = $this->entityStorage
->load(static::$secondCreatedEntityId);
$uuid = $second_created_entity
->uuid();
$location = Url::fromRoute(sprintf('jsonapi.%s.individual', static::$resourceTypeName), [
'entity' => $uuid,
]);
if (static::$resourceTypeIsVersionable) {
assert($created_entity instanceof RevisionableInterface);
$location
->setOption('query', [
'resourceVersion' => 'id:' . $second_created_entity
->getRevisionId(),
]);
}
$this
->assertSame([
$location
->setAbsolute()
->toString(),
], $response
->getHeader('Location'));
$doc = $this
->getModifiedEntityForPostTesting();
$doc['data']['id'] = $uuid;
$doc['data']['attributes'][$label_field] = [
[
'value' => $this
->randomMachineName(),
],
];
$request_options[RequestOptions::BODY] = Json::encode($doc);
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceErrorResponse(409, 'Conflict: Entity already exists.', $url, $response, FALSE);
$doc = $this
->getModifiedEntityForPostTesting();
$new_uuid = \Drupal::service('uuid')
->generate();
$doc['data']['id'] = $new_uuid;
$doc['data']['attributes'][$label_field] = [
[
'value' => $this
->randomMachineName(),
],
];
$request_options[RequestOptions::BODY] = Json::encode($doc);
$response = $this
->request('POST', $url, $request_options);
$this
->assertResourceResponse(201, FALSE, $response);
$entities = $this->entityStorage
->loadByProperties([
$this->uuidKey => $new_uuid,
]);
$new_entity = reset($entities);
$this
->assertNotNull($new_entity);
$new_entity
->delete();
}
else {
$this
->assertFalse($response
->hasHeader('Location'));
}
}
public function testPatchIndividual() {
if ($this->entity instanceof ConfigEntityInterface) {
$this
->assertTrue(TRUE, 'PATCHing config entities is not yet supported.');
return;
}
$prior_revision_id = (int) $this
->entityLoadUnchanged($this->entity
->id())
->getRevisionId();
$this->anotherEntity = $this
->createAnotherEntity('dupe');
$unparseable_request_body = '!{>}<';
$parseable_valid_request_body = Json::encode($this
->getPatchDocument());
$parseable_invalid_request_body = Json::encode($this
->makeNormalizationInvalid($this
->getPatchDocument(), 'label'));
$parseable_invalid_request_body_2 = Json::encode(NestedArray::mergeDeep([
'data' => [
'attributes' => [
'field_rest_test' => $this
->randomString(),
],
],
], $this
->getPatchDocument()));
$parseable_invalid_request_body_3 = Json::encode(NestedArray::mergeDeep([
'data' => [
'attributes' => [
'field_rest_test' => $this->entity
->get('field_rest_test')
->getValue(),
],
],
], $this
->getPatchDocument()));
$parseable_invalid_request_body_4 = Json::encode(NestedArray::mergeDeep([
'data' => [
'attributes' => [
'field_nonexistent' => $this
->randomString(),
],
],
], $this
->getPatchDocument()));
if ($this->entity instanceof FieldableEntityInterface && $this->entity
->hasField('field_jsonapi_test_entity_ref')) {
$parseable_invalid_request_body_5 = Json::encode(NestedArray::mergeDeep([
'data' => [
'attributes' => [
'field_jsonapi_test_entity_ref' => [
'target_id' => $this
->randomString(),
],
],
],
], $this
->getPostDocument()));
}
$url = Url::fromRoute(sprintf('jsonapi.%s.individual', static::$resourceTypeName), [
'entity' => $this->entity
->uuid(),
]);
$request_options = [];
$request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
$request_options = NestedArray::mergeDeep($request_options, $this
->getAuthenticationRequestOptions());
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceErrorResponse(405, sprintf("JSON:API is configured to accept only read operations. Site administrators can configure this at %s.", Url::fromUri('base:/admin/config/services/jsonapi')
->setAbsolute()
->toString(TRUE)
->getGeneratedUrl()), $url, $response);
$this
->assertSame([
'GET',
], $response
->getHeader('Allow'));
$this
->config('jsonapi.settings')
->set('read_only', FALSE)
->save(TRUE);
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertsame(415, $response
->getStatusCode());
$request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
$response = $this
->request('PATCH', $url, $request_options);
$reason = $this
->getExpectedUnauthorizedAccessMessage('PATCH');
$this
->assertResourceErrorResponse(403, (string) $reason, $url, $response);
$this
->setUpAuthorization('PATCH');
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceErrorResponse(400, 'Empty request body.', $url, $response, FALSE);
$request_options[RequestOptions::BODY] = $unparseable_request_body;
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceErrorResponse(400, 'Syntax error', $url, $response, FALSE);
$request_options[RequestOptions::BODY] = $parseable_invalid_request_body;
$response = $this
->request('PATCH', $url, $request_options);
$label_field = $this->entity
->getEntityType()
->hasKey('label') ? $this->entity
->getEntityType()
->getKey('label') : static::$labelFieldName;
$label_field_capitalized = $this->entity
->getFieldDefinition($label_field)
->getLabel();
$this
->assertResourceErrorResponse(422, "{$label_field}: {$label_field_capitalized}: this field cannot hold more than 1 values.", NULL, $response, '/data/attributes/' . $label_field);
$request_options[RequestOptions::BODY] = $parseable_invalid_request_body_2;
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceErrorResponse(403, "The current user is not allowed to PATCH the selected field (field_rest_test).", $url, $response, '/data/attributes/field_rest_test');
$request_options[RequestOptions::BODY] = Json::encode($this
->makeNormalizationInvalid($this
->getPatchDocument(), 'id'));
$response = $this
->request('PATCH', $url, $request_options);
$id_field_name = $this->entity
->getEntityType()
->getKey('id');
$expected_message = floatval(\Drupal::VERSION) < 8.6 ? "The current user is not allowed to PATCH the selected field ({$id_field_name}). The entity ID cannot be changed" : "The current user is not allowed to PATCH the selected field ({$id_field_name}). The entity ID cannot be changed.";
$this
->assertResourceErrorResponse(403, $expected_message, $url, $response, "/data/attributes/{$id_field_name}");
if ($this->entity
->getEntityType()
->hasKey('uuid')) {
$request_options[RequestOptions::BODY] = Json::encode($this
->makeNormalizationInvalid($this
->getPatchDocument(), 'uuid'));
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceErrorResponse(400, sprintf("The selected entity (%s) does not match the ID in the payload (%s).", $this->entity
->uuid(), $this->anotherEntity
->uuid()), $url, $response, FALSE);
}
$request_options[RequestOptions::BODY] = $parseable_invalid_request_body_3;
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceErrorResponse(403, "The current user is not allowed to PATCH the selected field (field_rest_test).", $url, $response, '/data/attributes/field_rest_test');
list($modified_entity, $original_values) = static::getModifiedEntityForPatchTesting($this->entity);
foreach (static::$patchProtectedFieldNames as $patch_protected_field_name => $reason) {
$request_options[RequestOptions::BODY] = Json::encode($this
->normalize($modified_entity, $url));
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceErrorResponse(403, "The current user is not allowed to PATCH the selected field (" . $patch_protected_field_name . ")." . ($reason !== NULL ? ' ' . $reason : ''), $url
->setAbsolute(), $response, '/data/attributes/' . $patch_protected_field_name);
$modified_entity
->get($patch_protected_field_name)
->setValue($original_values[$patch_protected_field_name]);
}
$request_options[RequestOptions::BODY] = $parseable_invalid_request_body_4;
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceErrorResponse(422, sprintf("The attribute field_nonexistent does not exist on the %s resource type.", static::$resourceTypeName), $url, $response, FALSE);
if (isset($parseable_invalid_request_body_5)) {
$request_options[RequestOptions::BODY] = $parseable_invalid_request_body_5;
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceErrorResponse(422, "The following relationship fields were provided as attributes: [ field_jsonapi_test_entity_ref ]", $url, $response, FALSE);
}
$valid_request_body = NestedArray::mergeDeep($this
->normalize($this->entity, $url), $this
->getPatchDocument());
$request_options[RequestOptions::BODY] = Json::encode($valid_request_body);
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceResponse(200, FALSE, $response);
$updated_entity = $this
->entityLoadUnchanged($this->entity
->id());
$this
->assertSame(static::$newRevisionsShouldBeAutomatic, $prior_revision_id < (int) $updated_entity
->getRevisionId());
$prior_revision_id = (int) $updated_entity
->getRevisionId();
$request_options[RequestOptions::BODY] = $parseable_valid_request_body;
$request_options[RequestOptions::HEADERS]['Content-Type'] = 'text/xml';
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertSame(415, $response
->getStatusCode());
$request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceResponse(200, FALSE, $response);
$this
->assertFalse($response
->hasHeader('X-Drupal-Cache'));
$updated_entity = $this
->entityLoadUnchanged($this->entity
->id());
$this
->assertSame(static::$newRevisionsShouldBeAutomatic, $prior_revision_id < (int) $updated_entity
->getRevisionId());
if ($this->entity instanceof RevisionLogInterface) {
if (static::$newRevisionsShouldBeAutomatic) {
$this
->assertNotSame((int) $this->entity
->getRevisionCreationTime(), (int) $updated_entity
->getRevisionCreationTime());
}
else {
$this
->assertSame((int) $this->entity
->getRevisionCreationTime(), (int) $updated_entity
->getRevisionCreationTime());
}
}
$updated_entity_document = $this
->normalize($updated_entity, $url);
$this
->assertSame($updated_entity_document, Json::decode((string) $response
->getBody()));
$prior_revision_id = (int) $updated_entity
->getRevisionId();
foreach ($this
->getPatchDocument()['data']['attributes'] as $field_name => $field_normalization) {
if (is_array($field_normalization)) {
$this
->assertArraySubset($field_normalization, $updated_entity_document['data']['attributes'][$field_name]);
}
else {
$this
->assertSame($field_normalization, $updated_entity_document['data']['attributes'][$field_name]);
}
}
if (isset($this
->getPatchDocument()['data']['relationships'])) {
foreach ($this
->getPatchDocument()['data']['relationships'] as $field_name => $relationship_field_normalization) {
static::recursiveKsort($relationship_field_normalization);
static::recursiveKsort($updated_entity_document['data']['relationships'][$field_name]);
$this
->assertSame($relationship_field_normalization, array_diff_key($updated_entity_document['data']['relationships'][$field_name], [
'links' => TRUE,
]));
}
}
$this
->assertSame('All the faith he had had had had no effect on the outcome of his life.', $updated_entity
->get('field_rest_test')->value);
$doc_multi_value_tests = $this
->getPatchDocument();
$doc_multi_value_tests['data']['attributes']['field_rest_test_multivalue'] = $this->entity
->get('field_rest_test_multivalue')
->getValue();
$doc_remove_item = $doc_multi_value_tests;
unset($doc_remove_item['data']['attributes']['field_rest_test_multivalue'][0]);
$request_options[RequestOptions::BODY] = Json::encode($doc_remove_item, 'api_json');
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceResponse(200, FALSE, $response);
$updated_entity = $this
->entityLoadUnchanged($this->entity
->id());
$this
->assertSame([
0 => [
'value' => 'Two',
],
], $updated_entity
->get('field_rest_test_multivalue')
->getValue());
$this
->assertSame(static::$newRevisionsShouldBeAutomatic, $prior_revision_id < (int) $updated_entity
->getRevisionId());
$prior_revision_id = (int) $updated_entity
->getRevisionId();
$doc_add_items = $doc_multi_value_tests;
$doc_add_items['data']['attributes']['field_rest_test_multivalue'][2] = [
'value' => 'Three',
];
$request_options[RequestOptions::BODY] = Json::encode($doc_add_items);
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceResponse(200, FALSE, $response);
$expected_document = [
0 => [
'value' => 'One',
],
1 => [
'value' => 'Two',
],
2 => [
'value' => 'Three',
],
];
$updated_entity = $this
->entityLoadUnchanged($this->entity
->id());
$this
->assertSame($expected_document, $updated_entity
->get('field_rest_test_multivalue')
->getValue());
$this
->assertSame(static::$newRevisionsShouldBeAutomatic, $prior_revision_id < (int) $updated_entity
->getRevisionId());
$prior_revision_id = (int) $updated_entity
->getRevisionId();
if ($updated_entity instanceof EntityPublishedInterface) {
$updated_entity
->setPublished()
->save();
}
$this
->assertTrue($this->container
->get('module_installer')
->install([
'content_moderation',
], TRUE), 'Installed modules.');
if (!\Drupal::service('content_moderation.moderation_information')
->canModerateEntitiesOfEntityType($this->entity
->getEntityType())) {
return;
}
$workflow = floatval(\Drupal::VERSION) > 8.5 ? $this
->createEditorialWorkflow() : entity_load('workflow', 'editorial');
$workflow
->getTypePlugin()
->addEntityTypeAndBundle(static::$entityTypeId, $this->entity
->bundle());
$workflow
->save();
$this
->grantPermissionsToTestedRole([
'use editorial transition publish',
]);
$doc_add_items['data']['attributes']['field_rest_test_multivalue'][2] = [
'value' => '3',
];
$request_options[RequestOptions::BODY] = Json::encode($doc_add_items);
$response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceResponse(200, FALSE, $response);
$expected_document = [
0 => [
'value' => 'One',
],
1 => [
'value' => 'Two',
],
2 => [
'value' => '3',
],
];
$updated_entity = $this
->entityLoadUnchanged($this->entity
->id());
$this
->assertSame($expected_document, $updated_entity
->get('field_rest_test_multivalue')
->getValue());
if ($this->entity
->getEntityType()
->hasHandlerClass('moderation')) {
$this
->assertLessThan((int) $updated_entity
->getRevisionId(), $prior_revision_id);
}
else {
$this
->assertSame(static::$newRevisionsShouldBeAutomatic, $prior_revision_id < (int) $updated_entity
->getRevisionId());
}
if (!$this->entity
->getEntityType()
->isRevisionable() || !$this->entity instanceof FieldableEntityInterface) {
return;
}
assert($this->entity instanceof RevisionableInterface);
$request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
$request_options[RequestOptions::BODY] = Json::encode([
'data' => [
'type' => static::$resourceTypeName,
'id' => $this->entity
->uuid(),
],
]);
$this
->setUpAuthorization('PATCH');
$this
->grantPermissionsToTestedRole([
'use editorial transition create_new_draft',
'use editorial transition archived_published',
'use editorial transition published',
]);
$updated_entity
->set('moderation_state', 'draft');
$updated_entity
->setNewRevision();
$updated_entity
->save();
$actual_response = $this
->request('PATCH', $url, $request_options);
$this
->assertResourceErrorResponse(400, 'Updating a resource object that has a working copy is not yet supported. See https://www.drupal.org/project/jsonapi/issues/2795279.', $url, $actual_response);
$updated_entity
->set('moderation_state', 'archived');
$updated_entity
->setNewRevision();
$updated_entity
->save();
$actual_response = $this
->request('PATCH', $url, $request_options);
$this
->assertSame(200, $actual_response
->getStatusCode());
$updated_entity
->set('moderation_state', 'draft');
$updated_entity
->setNewRevision();
$updated_entity
->save();
$actual_response = $this
->request('PATCH', $url, $request_options);
$this
->assertSame(200, $actual_response
->getStatusCode());
$updated_entity
->set('moderation_state', 'published');
$updated_entity
->setNewRevision();
$updated_entity
->save();
$actual_response = $this
->request('PATCH', $url, $request_options);
$this
->assertSame(200, $actual_response
->getStatusCode());
}
public function testDeleteIndividual() {
if ($this->entity instanceof ConfigEntityInterface) {
$this
->assertTrue(TRUE, 'DELETEing config entities is not yet supported.');
return;
}
$url = Url::fromRoute(sprintf('jsonapi.%s.individual', static::$resourceTypeName), [
'entity' => $this->entity
->uuid(),
]);
$request_options = [];
$request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
$request_options = NestedArray::mergeDeep($request_options, $this
->getAuthenticationRequestOptions());
$response = $this
->request('DELETE', $url, $request_options);
$this
->assertResourceErrorResponse(405, sprintf("JSON:API is configured to accept only read operations. Site administrators can configure this at %s.", Url::fromUri('base:/admin/config/services/jsonapi')
->setAbsolute()
->toString(TRUE)
->getGeneratedUrl()), $url, $response);
$this
->assertSame([
'GET',
], $response
->getHeader('Allow'));
$this
->config('jsonapi.settings')
->set('read_only', FALSE)
->save(TRUE);
$response = $this
->request('DELETE', $url, $request_options);
$reason = $this
->getExpectedUnauthorizedAccessMessage('DELETE');
$this
->assertResourceErrorResponse(403, (string) $reason, $url, $response, FALSE);
$this
->setUpAuthorization('DELETE');
$response = $this
->request('DELETE', $url, $request_options);
$this
->assertResourceResponse(204, NULL, $response);
$response = $this
->request('DELETE', $url, $request_options);
$this
->assertSame(404, $response
->getStatusCode());
}
protected static function recursiveKsort(array &$array) {
ksort($array);
foreach ($array as $key => &$value) {
if (is_array($value)) {
static::recursiveKsort($value);
}
}
}
protected function getAuthenticationRequestOptions() {
return [
'headers' => [
'Authorization' => 'Basic ' . base64_encode($this->account->name->value . ':' . $this->account->passRaw),
],
];
}
protected static function getModifiedEntityForPatchTesting(EntityInterface $entity) {
$modified_entity = clone $entity;
$original_values = [];
foreach (array_keys(static::$patchProtectedFieldNames) as $field_name) {
$field = $modified_entity
->get($field_name);
$original_values[$field_name] = $field
->getValue();
switch ($field
->getItemDefinition()
->getClass()) {
case BooleanItem::class:
$field->value = (int) $field->value === 1 ? '0' : '1';
break;
case PathItem::class:
$field->alias = str_replace(' ', '-', strtolower((new Random())
->sentences(3)));
break;
default:
$original_field = clone $field;
while ($field
->equals($original_field)) {
$field
->generateSampleItems();
}
break;
}
}
return [
$modified_entity,
$original_values,
];
}
protected function getModifiedEntityForPostTesting() {
$document = $this
->getPostDocument();
foreach (static::$uniqueFieldNames as $field_name) {
$field_definition = $this->entity
->getFieldDefinition($field_name);
$field_type_class = $field_definition
->getItemDefinition()
->getClass();
$document['data']['attributes'][$field_name] = $field_type_class::generateSampleValue($field_definition);
}
return $document;
}
protected function doTestSparseFieldSets(Url $url, array $request_options) {
$field_sets = $this
->getSparseFieldSets();
$expected_cacheability = new CacheableMetadata();
foreach ($field_sets as $type => $field_set) {
if ($type === 'all') {
assert($this
->getExpectedCacheTags($field_set) === $this
->getExpectedCacheTags());
assert($this
->getExpectedCacheContexts($field_set) === $this
->getExpectedCacheContexts());
}
$query = [
'fields[' . static::$resourceTypeName . ']' => implode(',', $field_set),
];
$expected_document = $this
->getExpectedDocument();
$expected_cacheability
->setCacheTags($this
->getExpectedCacheTags($field_set));
$expected_cacheability
->setCacheContexts($this
->getExpectedCacheContexts($field_set));
if (strpos($type, 'nested') === 0) {
$this
->grantPermissionsToTestedRole([
'access user profiles',
]);
$query['fields[user--user]'] = implode(',', $field_set);
$query['include'] = 'uid';
$owner = $this->entity
->getOwner();
$owner_resource = static::toResourceIdentifier($owner);
foreach ($field_set as $field_name) {
$owner_resource['attributes'][$field_name] = $this->serializer
->normalize($owner
->get($field_name)[0]
->get('value'), 'api_json');
}
$owner_resource['links']['self']['href'] = static::getResourceLink($owner_resource);
$expected_document['included'] = [
$owner_resource,
];
$expected_cacheability
->addCacheableDependency($owner);
$expected_cacheability
->addCacheableDependency(static::entityAccess($owner, 'view', $this->account));
}
foreach ([
'attributes',
'relationships',
] as $member) {
if (!empty($expected_document['data'][$member])) {
$remaining = array_intersect_key($expected_document['data'][$member], array_flip($field_set));
if (empty($remaining)) {
unset($expected_document['data'][$member]);
}
else {
$expected_document['data'][$member] = $remaining;
}
}
}
$url
->setOption('query', $query);
$expected_document['links']['self']['href'] = $url
->setAbsolute()
->toString();
$response = $this
->request('GET', $url, $request_options);
$dynamic_cache = !empty(array_intersect([
'user',
'session',
], $expected_cacheability
->getCacheContexts())) ? 'UNCACHEABLE' : 'MISS';
$this
->assertResourceResponse(200, $expected_document, $response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, $dynamic_cache);
}
$response = $this
->request('GET', $url, $request_options);
$this
->assertResourceResponse(200, FALSE, $response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, $dynamic_cache === 'MISS' ? 'HIT' : 'UNCACHEABLE');
}
protected function doTestIncluded(Url $url, array $request_options) {
$relationship_field_names = $this
->getRelationshipFieldNames($this->entity);
if (empty($relationship_field_names)) {
return;
}
$field_sets = [
'empty' => [],
'all' => $relationship_field_names,
];
if (count($relationship_field_names) > 1) {
$about_half_the_fields = floor(count($relationship_field_names) / 2);
$field_sets['some'] = array_slice($relationship_field_names, $about_half_the_fields);
$nested_includes = $this
->getNestedIncludePaths();
if (!empty($nested_includes) && !in_array($nested_includes, $field_sets)) {
$field_sets['nested'] = $nested_includes;
}
}
foreach ($field_sets as $type => $included_paths) {
$this
->grantIncludedPermissions($included_paths);
$query = [
'include' => implode(',', $included_paths),
];
$url
->setOption('query', $query);
$actual_response = $this
->request('GET', $url, $request_options);
$expected_response = $this
->getExpectedIncludedResourceResponse($included_paths, $request_options);
$expected_document = $expected_response
->getResponseData();
$expected_cacheability = $expected_response
->getCacheableMetadata();
$dynamic_cache = $expected_cacheability
->getCacheMaxAge() === 0 || !empty(array_intersect([
'user',
'session',
], $this
->getExpectedCacheContexts())) ? 'UNCACHEABLE' : 'MISS';
$this
->assertResourceResponse(200, $expected_document, $actual_response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, $dynamic_cache);
}
}
public function testRevisions() {
if (!$this->entity
->getEntityType()
->isRevisionable() || !$this->entity instanceof FieldableEntityInterface) {
return;
}
assert($this->entity instanceof RevisionableInterface);
if (!static::$resourceTypeIsVersionable) {
$this
->setUpRevisionAuthorization('GET');
$url = Url::fromRoute(sprintf('jsonapi.%s.individual', static::$resourceTypeName), [
'entity' => $this->entity
->uuid(),
])
->setAbsolute();
$url
->setOption('query', [
'resourceVersion' => 'id:' . $this->entity
->getRevisionId(),
]);
$request_options = [];
$request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
$request_options = NestedArray::mergeDeep($request_options, $this
->getAuthenticationRequestOptions());
$response = $this
->request('GET', $url, $request_options);
$detail = 'JSON:API does not yet support resource versioning for this resource type.';
$detail .= ' For context, see https://www.drupal.org/project/jsonapi/issues/2992833#comment-12818258.';
$detail .= ' To contribute, see https://www.drupal.org/project/drupal/issues/2350939 and https://www.drupal.org/project/drupal/issues/2809177.';
$expected_cache_contexts = [
'url.path',
'url.query_args:resourceVersion',
'url.site',
];
$this
->assertResourceErrorResponse(501, $detail, $url, $response, FALSE, [
'http_response',
], $expected_cache_contexts);
return;
}
FieldStorageConfig::create([
'entity_type' => static::$entityTypeId,
'field_name' => 'field_revisionable_number',
'type' => 'integer',
])
->setCardinality(1)
->save();
FieldConfig::create([
'entity_type' => static::$entityTypeId,
'field_name' => 'field_revisionable_number',
'bundle' => $this->entity
->bundle(),
])
->setLabel('Revisionable text field')
->setTranslatable(FALSE)
->save();
$entity = $this
->entityLoadUnchanged($this->entity
->id());
$entity
->set('field_revisionable_number', 42);
$entity
->save();
$original_revision_id = (int) $entity
->getRevisionId();
$entity
->set('field_revisionable_number', 99);
$entity
->setNewRevision();
$entity
->save();
$latest_revision_id = (int) $entity
->getRevisionId();
$url = Url::fromRoute(sprintf('jsonapi.%s.individual', static::$resourceTypeName), [
'entity' => $this->entity
->uuid(),
])
->setAbsolute();
$collection_url = Url::fromRoute(sprintf('jsonapi.%s.collection', static::$resourceTypeName))
->setAbsolute();
$relationship_url = Url::fromRoute(sprintf('jsonapi.%s.%s.relationship.get', static::$resourceTypeName, 'field_jsonapi_test_entity_ref'), [
'entity' => $this->entity
->uuid(),
])
->setAbsolute();
$related_url = Url::fromRoute(sprintf('jsonapi.%s.%s.related', static::$resourceTypeName, 'field_jsonapi_test_entity_ref'), [
'entity' => $this->entity
->uuid(),
])
->setAbsolute();
$original_revision_id_url = clone $url;
$original_revision_id_url
->setOption('query', [
'resourceVersion' => "id:{$original_revision_id}",
]);
$original_revision_id_relationship_url = clone $relationship_url;
$original_revision_id_relationship_url
->setOption('query', [
'resourceVersion' => "id:{$original_revision_id}",
]);
$original_revision_id_related_url = clone $related_url;
$original_revision_id_related_url
->setOption('query', [
'resourceVersion' => "id:{$original_revision_id}",
]);
$latest_revision_id_url = clone $url;
$latest_revision_id_url
->setOption('query', [
'resourceVersion' => "id:{$latest_revision_id}",
]);
$latest_revision_id_relationship_url = clone $relationship_url;
$latest_revision_id_relationship_url
->setOption('query', [
'resourceVersion' => "id:{$latest_revision_id}",
]);
$latest_revision_id_related_url = clone $related_url;
$latest_revision_id_related_url
->setOption('query', [
'resourceVersion' => "id:{$latest_revision_id}",
]);
$rel_latest_version_url = clone $url;
$rel_latest_version_url
->setOption('query', [
'resourceVersion' => 'rel:latest-version',
]);
$rel_latest_version_relationship_url = clone $relationship_url;
$rel_latest_version_relationship_url
->setOption('query', [
'resourceVersion' => 'rel:latest-version',
]);
$rel_latest_version_related_url = clone $related_url;
$rel_latest_version_related_url
->setOption('query', [
'resourceVersion' => 'rel:latest-version',
]);
$rel_latest_version_collection_url = clone $collection_url;
$rel_latest_version_collection_url
->setOption('query', [
'resourceVersion' => 'rel:latest-version',
]);
$rel_working_copy_url = clone $url;
$rel_working_copy_url
->setOption('query', [
'resourceVersion' => 'rel:working-copy',
]);
$rel_working_copy_relationship_url = clone $relationship_url;
$rel_working_copy_relationship_url
->setOption('query', [
'resourceVersion' => 'rel:working-copy',
]);
$rel_working_copy_related_url = clone $related_url;
$rel_working_copy_related_url
->setOption('query', [
'resourceVersion' => 'rel:working-copy',
]);
$rel_working_copy_collection_url = clone $collection_url;
$rel_working_copy_collection_url
->setOption('query', [
'resourceVersion' => 'rel:working-copy',
]);
$rel_invalid_collection_url = clone $collection_url;
$rel_invalid_collection_url
->setOption('query', [
'resourceVersion' => 'rel:invalid',
]);
$revision_id_key = 'drupal_internal__' . $this->entity
->getEntityType()
->getKey('revision');
$published_key = $this->entity
->getEntityType()
->getKey('published');
$revision_translation_affected_key = $this->entity
->getEntityType()
->getKey('revision_translation_affected');
$amend_relationship_urls = function (array &$document, $revision_id) {
if (!empty($document['data']['relationships'])) {
foreach ($document['data']['relationships'] as &$relationship) {
$pattern = '/resourceVersion=id%3A\\d/';
$replacement = 'resourceVersion=' . urlencode("id:{$revision_id}");
$relationship['links']['self']['href'] = preg_replace($pattern, $replacement, $relationship['links']['self']['href']);
$relationship['links']['related']['href'] = preg_replace($pattern, $replacement, $relationship['links']['related']['href']);
}
}
};
$request_options = [];
$request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
$request_options = NestedArray::mergeDeep($request_options, $this
->getAuthenticationRequestOptions());
$actual_response = $this
->request('GET', $url, $request_options);
$expected_cacheability = $this
->getExpectedUnauthorizedAccessCacheability();
$result = $entity
->access('view', $this->account, TRUE);
$detail = 'The current user is not allowed to GET the selected resource.';
if ($result instanceof AccessResultReasonInterface && ($reason = $result
->getReason()) && !empty($reason)) {
$detail .= ' ' . $reason;
}
$this
->assertResourceErrorResponse(403, $detail, $url, $actual_response, '/data', $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, 'MISS');
$actual_response = $this
->request('GET', $original_revision_id_url, $request_options);
$expected_cacheability = $this
->getExpectedUnauthorizedAccessCacheability();
$detail = 'The current user is not allowed to GET the selected resource. The user does not have access to the requested version.';
if ($result instanceof AccessResultReasonInterface && ($reason = $result
->getReason()) && !empty($reason)) {
$detail .= ' ' . $reason;
}
$this
->assertResourceErrorResponse(403, $detail, $url, $actual_response, '/data', $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, 'MISS');
$this
->setUpRevisionAuthorization('GET');
$actual_response = $this
->request('GET', $url, $request_options);
$expected_document = $this
->getExpectedDocument();
$expected_document['data']['links']['self']['href'] = $latest_revision_id_url
->setAbsolute()
->toString();
$amend_relationship_urls($expected_document, $latest_revision_id);
$expected_document['data']['attributes'][$revision_id_key] = $latest_revision_id;
$expected_document['data']['attributes']['field_revisionable_number'] = 99;
$expected_cache_tags = $this
->getExpectedCacheTags();
$expected_cache_contexts = $this
->getExpectedCacheContexts();
$this
->assertResourceResponse(200, $expected_document, $actual_response, $expected_cache_tags, $expected_cache_contexts, FALSE, 'MISS');
$actual_response = $this
->request('GET', $latest_revision_id_url, $request_options);
$expected_document['links']['self']['href'] = $latest_revision_id_url
->setAbsolute()
->toString();
$this
->assertResourceResponse(200, $expected_document, $actual_response, $expected_cache_tags, $expected_cache_contexts, FALSE, 'MISS');
$actual_response = $this
->request('GET', $latest_revision_id_url, $request_options);
$this
->assertResourceResponse(200, $expected_document, $actual_response, $expected_cache_tags, $expected_cache_contexts, FALSE, 'HIT');
$actual_response = $this
->request('GET', $rel_latest_version_url, $request_options);
$expected_document['links']['self']['href'] = $rel_latest_version_url
->setAbsolute()
->toString();
$this
->assertResourceResponse(200, $expected_document, $actual_response, $expected_cache_tags, $expected_cache_contexts, FALSE, 'MISS');
$actual_response = $this
->request('GET', $rel_working_copy_url, $request_options);
$expected_document['links']['self']['href'] = $rel_working_copy_url
->setAbsolute()
->toString();
$this
->assertResourceResponse(200, $expected_document, $actual_response, $expected_cache_tags, $expected_cache_contexts, FALSE, 'MISS');
$actual_response = $this
->request('GET', $original_revision_id_url, $request_options);
$expected_document['data']['attributes'][$revision_id_key] = $original_revision_id;
$expected_document['data']['attributes']['field_revisionable_number'] = 42;
$expected_document['links']['self']['href'] = $original_revision_id_url
->setAbsolute()
->toString();
$expected_document['data']['links']['self']['href'] = $original_revision_id_url
->setAbsolute()
->toString();
$amend_relationship_urls($expected_document, $original_revision_id);
$expected_document['data']['links']['latest-version']['href'] = $rel_latest_version_url
->setAbsolute()
->toString();
$expected_document['data']['links']['working-copy']['href'] = $rel_working_copy_url
->setAbsolute()
->toString();
$this
->assertResourceResponse(200, $expected_document, $actual_response, $expected_cache_tags, $expected_cache_contexts, FALSE, 'MISS');
$this
->assertTrue($this->container
->get('module_installer')
->install([
'content_moderation',
], TRUE), 'Installed modules.');
$workflow = floatval(\Drupal::VERSION) > 8.5 ? $this
->createEditorialWorkflow() : entity_load('workflow', 'editorial');
$workflow
->getTypePlugin()
->addEntityTypeAndBundle(static::$entityTypeId, $this->entity
->bundle());
$workflow
->save();
$entity = $this->entityStorage
->load($entity
->id());
$entity
->set('moderation_state', 'published');
$entity
->setNewRevision();
$entity
->save();
$default_revision_id = (int) $entity
->getRevisionId();
$actual_response = $this
->request('GET', $rel_latest_version_url, $request_options);
$expected_document['data']['attributes'][$revision_id_key] = $default_revision_id;
$expected_document['data']['attributes']['moderation_state'] = 'published';
$expected_document['data']['attributes'][$published_key] = TRUE;
$expected_document['data']['attributes']['field_revisionable_number'] = 99;
$expected_document['links']['self']['href'] = $rel_latest_version_url
->toString();
$expected_document['data']['attributes'][$revision_translation_affected_key] = $entity
->isRevisionTranslationAffected();
$default_revision_id_url = clone $url;
$default_revision_id_url = $default_revision_id_url
->setOption('query', [
'resourceVersion' => "id:{$default_revision_id}",
]);
$expected_document['data']['links']['self']['href'] = $default_revision_id_url
->setAbsolute()
->toString();
$amend_relationship_urls($expected_document, $default_revision_id);
unset($expected_document['data']['links']['latest-version']);
unset($expected_document['data']['links']['working-copy']);
$this
->assertResourceResponse(200, $expected_document, $actual_response, $expected_cache_tags, $expected_cache_contexts, FALSE, 'MISS');
$actual_response = $this
->request('GET', $rel_latest_version_collection_url, $request_options);
$expected_response = $this
->getExpectedCollectionResponse([
$entity,
], $rel_latest_version_collection_url
->toString(), $request_options);
$expected_collection_document = $expected_response
->getResponseData();
$expected_cacheability = $expected_response
->getCacheableMetadata();
$this
->assertResourceResponse(200, $expected_collection_document, $actual_response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, 'MISS');
$actual_response = $this
->request('GET', $rel_working_copy_url, $request_options);
$expected_document['links']['self']['href'] = $rel_working_copy_url
->toString();
$this
->assertResourceResponse(200, $expected_document, $actual_response, $expected_cache_tags, $expected_cache_contexts, FALSE, 'MISS');
$actual_response = $this
->request('GET', $rel_working_copy_collection_url, $request_options);
$expected_collection_document['links']['self']['href'] = $rel_working_copy_collection_url
->toString();
$this
->assertResourceResponse(200, $expected_collection_document, $actual_response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, 'MISS');
$rel_working_copy_collection_url_filtered = clone $rel_working_copy_collection_url;
$rel_working_copy_collection_url_filtered
->setOption('query', [
'filter[foo]' => 'bar',
] + $rel_working_copy_collection_url
->getOption('query'));
$actual_response = $this
->request('GET', $rel_working_copy_collection_url_filtered, $request_options);
$filtered_collection_expected_cache_contexts = [
'url.path',
'url.query_args:filter',
'url.query_args:resourceVersion',
'url.site',
];
$this
->assertResourceErrorResponse(501, 'JSON:API does not support filtering on revisions other than the latest version because a secure Drupal core API does not yet exist to do so.', $rel_working_copy_collection_url_filtered, $actual_response, FALSE, [
'http_response',
], $filtered_collection_expected_cache_contexts);
$actual_response = $this
->request('GET', $rel_invalid_collection_url, $request_options);
$invalid_version_expected_cache_contexts = [
'url.path',
'url.query_args:resourceVersion',
'url.site',
];
$this
->assertResourceErrorResponse(400, 'Collection resources only support the following resource version identifiers: rel:latest-version, rel:working-copy', $rel_invalid_collection_url, $actual_response, FALSE, [
'4xx-response',
'http_response',
], $invalid_version_expected_cache_contexts);
$entity
->set('field_revisionable_number', 42);
$new_user = $this
->createUser();
$new_user
->save();
$entity
->set('field_jsonapi_test_entity_ref', [
'target_id' => $new_user
->id(),
]);
$entity
->set('moderation_state', 'draft');
$entity
->setNewRevision();
$entity
->save();
$forward_revision_id = (int) $entity
->getRevisionId();
$actual_response = $this
->request('GET', $rel_latest_version_url, $request_options);
$expected_document['links']['self']['href'] = $rel_latest_version_url
->toString();
$expected_document['data']['links']['working-copy']['href'] = $rel_working_copy_url
->setAbsolute()
->toString();
$this
->assertResourceResponse(200, $expected_document, $actual_response, $expected_cache_tags, $expected_cache_contexts, FALSE, 'MISS');
$actual_response = $this
->request('GET', $rel_latest_version_collection_url, $request_options);
$expected_collection_document['data'][0] = $expected_document['data'];
$expected_collection_document['links']['self']['href'] = $rel_latest_version_collection_url
->toString();
$this
->assertResourceResponse(200, $expected_collection_document, $actual_response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, 'MISS');
$actual_response = $this
->request('GET', $url, $request_options);
$expected_document['links']['self']['href'] = $url
->toString();
$this
->assertResourceResponse(200, $expected_document, $actual_response, $expected_cache_tags, $expected_cache_contexts, FALSE, 'MISS');
$actual_response = $this
->request('GET', $collection_url, $request_options);
$expected_collection_document['links']['self']['href'] = $collection_url
->toString();
$this
->assertResourceResponse(200, $expected_collection_document, $actual_response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, 'MISS');
$result = $entity
->access('view', $this->account, TRUE);
if (!$result
->isAllowed()) {
$actual_response = $this
->request('GET', $rel_working_copy_url, $request_options);
$expected_cacheability = $this
->getExpectedUnauthorizedAccessCacheability();
$expected_cache_tags = Cache::mergeTags($expected_cacheability
->getCacheTags(), $entity
->getCacheTags());
$expected_cache_contexts = $expected_cacheability
->getCacheContexts();
$detail = 'The current user is not allowed to GET the selected resource. The user does not have access to the requested version.';
$message = $result instanceof AccessResultReasonInterface ? trim($detail . ' ' . $result
->getReason()) : $detail;
$this
->assertResourceErrorResponse(403, $message, $url, $actual_response, '/data', $expected_cache_tags, $expected_cache_contexts, FALSE, 'MISS');
$actual_response = $this
->request('GET', $rel_working_copy_collection_url, $request_options);
$expected_response = static::getExpectedCollectionResponse([
$entity,
], $rel_working_copy_collection_url
->toString(), $request_options);
$expected_collection_document = $expected_response
->getResponseData();
$expected_collection_document['data'] = [];
$expected_cacheability = $expected_response
->getCacheableMetadata();
$access_denied_response = static::getAccessDeniedResponse($entity, $result, $url, NULL, $detail)
->getResponseData();
static::addOmittedObject($expected_collection_document, static::errorsToOmittedObject($access_denied_response['errors']));
$this
->assertResourceResponse(200, $expected_collection_document, $actual_response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, 'MISS');
}
$this
->grantPermissionsToTestedRole($this
->getEditorialPermissions());
$actual_response = $this
->request('GET', $rel_working_copy_url, $request_options);
$expected_document['data']['attributes'][$revision_id_key] = $forward_revision_id;
$expected_document['data']['attributes']['moderation_state'] = 'draft';
$expected_document['data']['attributes'][$published_key] = FALSE;
$expected_document['data']['attributes']['field_revisionable_number'] = 42;
$expected_document['links']['self']['href'] = $rel_working_copy_url
->setAbsolute()
->toString();
$expected_document['data']['attributes'][$revision_translation_affected_key] = $entity
->isRevisionTranslationAffected();
$forward_revision_id_url = clone $url;
$forward_revision_id_url = $forward_revision_id_url
->setOption('query', [
'resourceVersion' => "id:{$forward_revision_id}",
]);
$expected_document['data']['links']['self']['href'] = $forward_revision_id_url
->setAbsolute()
->toString();
$amend_relationship_urls($expected_document, $forward_revision_id);
unset($expected_document['data']['links']['working-copy']);
$expected_document['data']['links']['latest-version']['href'] = $rel_latest_version_url
->setAbsolute()
->toString();
$expected_cache_tags = $this
->getExpectedCacheTags();
$expected_cache_contexts = $this
->getExpectedCacheContexts();
$this
->assertResourceResponse(200, $expected_document, $actual_response, $expected_cache_tags, $expected_cache_contexts, FALSE, 'MISS');
$actual_response = $this
->request('GET', $rel_working_copy_collection_url, $request_options);
$expected_response = static::getExpectedCollectionResponse([
$entity,
], $rel_working_copy_collection_url
->toString(), $request_options);
$expected_collection_document = $expected_response
->getResponseData();
$expected_collection_document['data'] = [
$expected_document['data'],
];
$expected_cacheability = $expected_response
->getCacheableMetadata();
$this
->assertResourceResponse(200, $expected_collection_document, $actual_response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, 'MISS');
$test_relationship_urls = [
[
NULL,
$relationship_url,
$related_url,
],
[
$original_revision_id,
$original_revision_id_relationship_url,
$original_revision_id_related_url,
],
[
$latest_revision_id,
$latest_revision_id_relationship_url,
$latest_revision_id_related_url,
],
[
$default_revision_id,
$rel_latest_version_relationship_url,
$rel_latest_version_related_url,
],
[
$forward_revision_id,
$rel_working_copy_relationship_url,
$rel_working_copy_related_url,
],
];
foreach ($test_relationship_urls as $revision_case) {
list($revision_id, $relationship_url, $related_url) = $revision_case;
$this->entityStorage
->resetCache([
$entity
->id(),
]);
$revision = is_null($revision_id) ? $this->entityStorage
->load($entity
->id()) : $this->entityStorage
->loadRevision($revision_id);
$actual_response = $this
->request('GET', $relationship_url, $request_options);
$expected_response = $this
->getExpectedGetRelationshipResponse('field_jsonapi_test_entity_ref', $revision);
$expected_document = $expected_response
->getResponseData();
$expected_cacheability = $expected_response
->getCacheableMetadata();
$expected_document['errors'][0]['links']['via']['href'] = $relationship_url
->toString();
$this
->assertResourceResponse(403, $expected_document, $actual_response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts());
$actual_response = $this
->request('GET', $related_url, $request_options);
$expected_response = $this
->getExpectedRelatedResponses([
'field_jsonapi_test_entity_ref',
], $request_options, $revision)['field_jsonapi_test_entity_ref'];
$expected_document = $expected_response
->getResponseData();
$expected_cacheability = $expected_response
->getCacheableMetadata();
$expected_document['errors'][0]['links']['via']['href'] = $related_url
->toString();
$this
->assertResourceResponse(403, $expected_document, $actual_response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts());
}
$this
->grantPermissionsToTestedRole([
'field_jsonapi_test_entity_ref view access',
]);
foreach ($test_relationship_urls as $revision_case) {
list($revision_id, $relationship_url, $related_url) = $revision_case;
$this->entityStorage
->resetCache([
$entity
->id(),
]);
$revision = is_null($revision_id) ? $this->entityStorage
->load($entity
->id()) : $this->entityStorage
->loadRevision($revision_id);
$actual_response = $this
->request('GET', $relationship_url, $request_options);
$expected_response = $this
->getExpectedGetRelationshipResponse('field_jsonapi_test_entity_ref', $revision);
$expected_document = $expected_response
->getResponseData();
$expected_cacheability = $expected_response
->getCacheableMetadata();
$this
->assertResourceResponse(200, $expected_document, $actual_response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, 'MISS');
$actual_response = $this
->request('GET', $related_url, $request_options);
$expected_response = $this
->getExpectedRelatedResponse('field_jsonapi_test_entity_ref', $request_options, $revision);
$expected_document = $expected_response
->getResponseData();
$expected_cacheability = $expected_response
->getCacheableMetadata();
$expected_document['links']['self']['href'] = $related_url
->toString();
$dynamic_cache = !empty(array_intersect([
'user',
'session',
], $expected_cacheability
->getCacheContexts())) ? 'UNCACHEABLE' : 'MISS';
$this
->assertResourceResponse(200, $expected_document, $actual_response, $expected_cacheability
->getCacheTags(), $expected_cacheability
->getCacheContexts(), FALSE, $dynamic_cache);
}
$this
->config('jsonapi.settings')
->set('read_only', FALSE)
->save(TRUE);
$individual_urls = [
$original_revision_id_url,
$latest_revision_id_url,
$rel_latest_version_url,
$rel_working_copy_url,
];
$request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
foreach ($individual_urls as $url) {
foreach ([
'PATCH',
'DELETE',
] as $method) {
$actual_response = $this
->request($method, $url, $request_options);
$this
->assertResourceErrorResponse(400, sprintf('%s requests with a `%s` query parameter are not supported.', $method, 'resourceVersion'), $url, $actual_response);
}
}
$relationship_urls = [
$original_revision_id_relationship_url,
$latest_revision_id_relationship_url,
$rel_latest_version_relationship_url,
$rel_working_copy_relationship_url,
];
foreach ($relationship_urls as $url) {
foreach ([
'PATCH',
'POST',
'DELETE',
] as $method) {
$actual_response = $this
->request($method, $url, $request_options);
$this
->assertResourceErrorResponse(400, sprintf('%s requests with a `%s` query parameter are not supported.', $method, 'resourceVersion'), $url, $actual_response);
}
}
$collection_urls = [
$rel_latest_version_collection_url,
$rel_working_copy_collection_url,
];
foreach ($collection_urls as $url) {
foreach ([
'POST',
] as $method) {
$actual_response = $this
->request($method, $url, $request_options);
$this
->assertResourceErrorResponse(400, sprintf('%s requests with a `%s` query parameter are not supported.', $method, 'resourceVersion'), $url, $actual_response);
}
}
}
protected static function decorateExpectedResponseForIncludedFields(ResourceResponse $expected_response, array $related_responses) {
$expected_document = $expected_response
->getResponseData();
$expected_cacheability = $expected_response
->getCacheableMetadata();
foreach ($related_responses as $related_response) {
$related_document = $related_response
->getResponseData();
$expected_cacheability
->addCacheableDependency($related_response
->getCacheableMetadata());
$expected_cacheability
->setCacheTags(array_values(array_diff($expected_cacheability
->getCacheTags(), [
'4xx-response',
])));
if (!empty($related_document['errors'])) {
static::addOmittedObject($expected_document, static::errorsToOmittedObject($related_document['errors']));
}
if (!empty($related_document['meta']['omitted'])) {
static::addOmittedObject($expected_document, $related_document['meta']['omitted']);
}
if (isset($related_document['data'])) {
$related_data = $related_document['data'];
$related_resources = static::isResourceIdentifier($related_data) ? [
$related_data,
] : $related_data;
foreach ($related_resources as $related_resource) {
if (empty($expected_document['included']) || !static::collectionHasResourceIdentifier($related_resource, $expected_document['included'])) {
$expected_document['included'][] = $related_resource;
}
}
}
}
return (new ResourceResponse($expected_document))
->addCacheableDependency($expected_cacheability);
}
protected function getExpectedGetIndividualResourceResponse($status_code = 200) {
$resource_response = new ResourceResponse($this
->getExpectedDocument(), $status_code);
$cacheability = new CacheableMetadata();
$cacheability
->setCacheContexts($this
->getExpectedCacheContexts());
$cacheability
->setCacheTags($this
->getExpectedCacheTags());
return $resource_response
->addCacheableDependency($cacheability);
}
protected function getSparseFieldSets() {
$field_names = array_keys($this->entity
->toArray());
$field_sets = [
'empty' => [],
'some' => array_slice($field_names, floor(count($field_names) / 2)),
'all' => $field_names,
];
if ($this->entity instanceof EntityOwnerInterface) {
$field_sets['nested_empty_fieldset'] = $field_sets['empty'];
$field_sets['nested_fieldset_with_owner_fieldset'] = [
'name',
'created',
];
}
return $field_sets;
}
protected function getRelationshipFieldNames(EntityInterface $entity = NULL) {
$entity = $entity ?: $this->entity;
$fields = $entity instanceof ContentEntityInterface ? iterator_to_array($entity) : [];
return array_reduce($fields, function ($field_names, $field) {
if (static::isReferenceFieldDefinition($field
->getFieldDefinition())) {
$field_names[] = $this->resourceType
->getPublicName($field
->getName());
}
return $field_names;
}, []);
}
protected static function getIncludePermissions() {
return [];
}
protected function getEditorialPermissions() {
return [
'view latest version',
"view any unpublished content",
];
}
protected static function entityAccess(EntityInterface $entity, $operation, AccountInterface $account) {
\Drupal::entityTypeManager()
->getAccessControlHandler($entity
->getEntityTypeId())
->resetCache();
return $entity
->access($operation, $account, TRUE);
}
protected static function entityFieldAccess(EntityInterface $entity, $field_name, $operation, AccountInterface $account) {
$entity_access = static::entityAccess($entity, $operation === 'edit' ? 'update' : 'view', $account);
$field_access = $entity->{$field_name}
->access($operation, $account, TRUE);
return $entity_access
->andIf($field_access);
}
protected function getNestedIncludePaths($depth = 3) {
$get_nested_relationship_field_names = function (EntityInterface $entity, $depth, $path = "") use (&$get_nested_relationship_field_names) {
$relationship_field_names = $this
->getRelationshipFieldNames($entity);
if ($depth > 0) {
$paths = [];
foreach ($relationship_field_names as $field_name) {
$next = $path ? "{$path}.{$field_name}" : $field_name;
$internal_field_name = $this->resourceType
->getInternalName($field_name);
if ($target_entity = $entity->{$internal_field_name}->entity) {
$deep = $get_nested_relationship_field_names($target_entity, $depth - 1, $next);
$paths = array_merge($paths, $deep);
}
else {
$paths[] = $next;
}
}
return $paths;
}
return array_map(function ($target_name) use ($path) {
return "{$path}.{$target_name}";
}, $relationship_field_names);
};
return $get_nested_relationship_field_names($this->entity, $depth);
}
protected static function isReferenceFieldDefinition(FieldDefinitionInterface $field_definition) {
$item_definition = $field_definition
->getItemDefinition();
$main_property = $item_definition
->getMainPropertyName();
$property_definition = $item_definition
->getPropertyDefinition($main_property);
return $property_definition instanceof DataReferenceTargetDefinition;
}
protected function grantIncludedPermissions(array $include_paths = []) {
$applicable_permissions = array_intersect_key(static::getIncludePermissions(), array_flip($include_paths));
$flattened_permissions = array_unique(array_reduce($applicable_permissions, 'array_merge', []));
$flattened_permissions[] = 'field_jsonapi_test_entity_ref view access';
$this
->grantPermissionsToTestedRole($flattened_permissions);
}
protected function entityLoadUnchanged($id) {
$this->entityStorage
->resetCache();
return $this->entityStorage
->loadUnchanged($id);
}
}