Newer
Older

Alex Bronstein
committed
<?php
namespace Drupal\jsonapi\Controller;
use Drupal\Component\Assertion\Inspector;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\CacheableResponseInterface;

Alex Bronstein
committed
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Entity\Query\QueryInterface;
use Drupal\Core\Entity\RevisionableEntityBundleInterface;
use Drupal\Core\Entity\RevisionableInterface;
use Drupal\Core\Entity\RevisionableStorageInterface;
use Drupal\Core\Entity\RevisionLogInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Render\RenderContext;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\jsonapi\Access\EntityAccessChecker;
use Drupal\jsonapi\CacheableResourceResponse;

Alex Bronstein
committed
use Drupal\jsonapi\Context\FieldResolver;
use Drupal\jsonapi\Entity\EntityValidationTrait;
use Drupal\jsonapi\Access\TemporaryQueryGuard;
use Drupal\jsonapi\Events\CollectRelationshipMetaEvent;

Alex Bronstein
committed
use Drupal\jsonapi\Exception\EntityAccessDeniedHttpException;
use Drupal\jsonapi\IncludeResolver;
use Drupal\jsonapi\JsonApiResource\IncludedData;
use Drupal\jsonapi\JsonApiResource\LinkCollection;
use Drupal\jsonapi\JsonApiResource\NullIncludedData;
use Drupal\jsonapi\JsonApiResource\Relationship;

Alex Bronstein
committed
use Drupal\jsonapi\JsonApiResource\ResourceIdentifier;
use Drupal\jsonapi\JsonApiResource\Link;
use Drupal\jsonapi\JsonApiResource\ResourceObject;
use Drupal\jsonapi\JsonApiResource\ResourceObjectData;
use Drupal\jsonapi\JsonApiResource\TopLevelDataInterface;

Alex Bronstein
committed
use Drupal\jsonapi\Query\Filter;
use Drupal\jsonapi\Query\Sort;
use Drupal\jsonapi\Query\OffsetPage;
use Drupal\jsonapi\JsonApiResource\Data;
use Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel;
use Drupal\jsonapi\ResourceResponse;
use Drupal\jsonapi\ResourceType\ResourceType;
use Drupal\jsonapi\ResourceType\ResourceTypeField;

Alex Bronstein
committed
use Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface;
use Drupal\jsonapi\Revisions\ResourceVersionRouteEnhancer;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

Alex Bronstein
committed
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Drupal\Core\Http\Exception\CacheableBadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;

Alex Bronstein
committed
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\SerializerInterface;
/**
* Process all entity requests.
*
* @internal JSON:API maintains no PHP API. The API is the HTTP API. This class
* may change at any time and could break any dependencies on it.
*
* @see https://www.drupal.org/project/drupal/issues/3032787

Alex Bronstein
committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
* @see jsonapi.api.php
*/
class EntityResource {
use EntityValidationTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $fieldManager;
/**
* The resource type repository.
*
* @var \Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface
*/
protected $resourceTypeRepository;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* The entity repository.
*
* @var \Drupal\Core\Entity\EntityRepositoryInterface
*/
protected $entityRepository;
/**
* The include resolver.
*
* @var \Drupal\jsonapi\IncludeResolver
*/
protected $includeResolver;
/**
* The JSON:API entity access checker.
*
* @var \Drupal\jsonapi\Access\EntityAccessChecker
*/
protected $entityAccessChecker;
/**
* The JSON:API field resolver.
*
* @var \Drupal\jsonapi\Context\FieldResolver
*/
protected $fieldResolver;
/**
* The JSON:API serializer.
*
* @var \Symfony\Component\Serializer\SerializerInterface|\Symfony\Component\Serializer\Normalizer\DenormalizerInterface
*/
protected $serializer;
/**
* The time service.
*
* @var \Drupal\Component\Datetime\TimeInterface
*/
protected $time;
/**
* The current user account.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $user;
/**
* The event dispatcher.
*
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
protected EventDispatcherInterface $eventDispatcher;

Alex Bronstein
committed
/**
* Instantiates an EntityResource object.

Alex Bronstein
committed
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $field_manager
* The entity type field manager.
* @param \Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface $resource_type_repository
* The JSON:API resource type repository.
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer.
* @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
* The entity repository.
* @param \Drupal\jsonapi\IncludeResolver $include_resolver
* The include resolver.
* @param \Drupal\jsonapi\Access\EntityAccessChecker $entity_access_checker
* The JSON:API entity access checker.
* @param \Drupal\jsonapi\Context\FieldResolver $field_resolver
* The JSON:API field resolver.
* @param \Symfony\Component\Serializer\SerializerInterface|\Symfony\Component\Serializer\Normalizer\DenormalizerInterface $serializer
* The JSON:API serializer.
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
* @param \Drupal\Core\Session\AccountInterface $user
* The current user account.
* @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
* The event dispatcher.

Alex Bronstein
committed
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $field_manager, ResourceTypeRepositoryInterface $resource_type_repository, RendererInterface $renderer, EntityRepositoryInterface $entity_repository, IncludeResolver $include_resolver, EntityAccessChecker $entity_access_checker, FieldResolver $field_resolver, SerializerInterface $serializer, TimeInterface $time, AccountInterface $user, ?EventDispatcherInterface $event_dispatcher = NULL) {

Alex Bronstein
committed
$this->entityTypeManager = $entity_type_manager;
$this->fieldManager = $field_manager;
$this->resourceTypeRepository = $resource_type_repository;
$this->renderer = $renderer;
$this->entityRepository = $entity_repository;
$this->includeResolver = $include_resolver;
$this->entityAccessChecker = $entity_access_checker;
$this->fieldResolver = $field_resolver;
$this->serializer = $serializer;
$this->time = $time;
$this->user = $user;
if (!isset($event_dispatcher)) {
@trigger_error('Calling ' . __METHOD__ . '() without the $event_dispatcher argument is deprecated in drupal:11.2.0 and will be required in drupal:12.0.0. See https://www.drupal.org/node/3280569', E_USER_DEPRECATED);
$event_dispatcher = \Drupal::service('event_dispatcher');
}
$this->eventDispatcher = $event_dispatcher;

Alex Bronstein
committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
}
/**
* Gets the individual entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The loaded entity.
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
*
* @return \Drupal\jsonapi\ResourceResponse
* The response.
*
* @throws \Drupal\jsonapi\Exception\EntityAccessDeniedHttpException
* Thrown when access to the entity is not allowed.
*/
public function getIndividual(EntityInterface $entity, Request $request) {
$resource_object = $this->entityAccessChecker->getAccessCheckedResourceObject($entity);
if ($resource_object instanceof EntityAccessDeniedHttpException) {
throw $resource_object;
}
$primary_data = new ResourceObjectData([$resource_object], 1);
$response = $this->buildWrappedResponse($primary_data, $request, $this->getIncludes($request, $primary_data));
return $response;
}
/**
* Creates an individual entity.
*
* @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type
* The JSON:API resource type for the request to be served.
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
*
* @return \Drupal\jsonapi\ResourceResponse
* The response.
*
* @throws \Symfony\Component\HttpKernel\Exception\ConflictHttpException
* Thrown when the entity already exists.
* @throws \Drupal\jsonapi\Exception\UnprocessableHttpEntityException
* Thrown when the entity does not pass validation.
*/
public function createIndividual(ResourceType $resource_type, Request $request) {
$parsed_entity = $this->deserialize($resource_type, $request, JsonApiDocumentTopLevel::class);
if ($parsed_entity instanceof FieldableEntityInterface) {
// Only check 'edit' permissions for fields that were actually submitted
// by the user. Field access makes no distinction between 'create' and
// 'update', so the 'edit' operation is used here.
$document = Json::decode($request->getContent());
$field_mapping = array_map(function (ResourceTypeField $field) {
return $field->getPublicName();
}, $resource_type->getFields());
// User resource objects contain a read-only attribute that is not a
// real field on the user entity type.
// @see \Drupal\jsonapi\JsonApiResource\ResourceObject::extractContentEntityFields()
// @todo Eliminate this special casing in https://www.drupal.org/project/drupal/issues/3079254.
if ($resource_type->getEntityTypeId() === 'user') {
$field_mapping = array_diff($field_mapping, [$resource_type->getPublicName('display_name')]);
}

Alex Bronstein
committed
foreach (['attributes', 'relationships'] as $data_member_name) {
if (isset($document['data'][$data_member_name])) {
foreach (array_intersect_key(array_flip($field_mapping), $document['data'][$data_member_name]) as $internal_field_name) {
$field_access = $parsed_entity->get($internal_field_name)->access('edit', NULL, TRUE);

Alex Bronstein
committed
if (!$field_access->isAllowed()) {
$public_field_name = $field_mapping[$internal_field_name];

Alex Bronstein
committed
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
throw new EntityAccessDeniedHttpException(NULL, $field_access, "/data/$data_member_name/$public_field_name", sprintf('The current user is not allowed to POST the selected field (%s).', $public_field_name));
}
}
}
}
}
static::validate($parsed_entity);
// Return a 409 Conflict response in accordance with the JSON:API spec. See
// http://jsonapi.org/format/#crud-creating-responses-409.
if ($this->entityExists($parsed_entity)) {
throw new ConflictHttpException('Conflict: Entity already exists.');
}
$parsed_entity->save();
// Build response object.
$resource_object = ResourceObject::createFromEntity($resource_type, $parsed_entity);
$primary_data = new ResourceObjectData([$resource_object], 1);
$response = $this->buildWrappedResponse($primary_data, $request, $this->getIncludes($request, $primary_data), 201);
// According to JSON:API specification, when a new entity was created
// we should send "Location" header to the frontend.
if ($resource_type->isLocatable()) {
$url = $resource_object->toUrl()->setAbsolute()->toString(TRUE);
$response->headers->set('Location', $url->getGeneratedUrl());
}
// Return response object with updated headers info.
return $response;
}
/**
* Patches an individual entity.
*
* @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type
* The JSON:API resource type for the request to be served.
* @param \Drupal\Core\Entity\EntityInterface $entity
* The loaded entity.
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
*
* @return \Drupal\jsonapi\ResourceResponse
* The response.
*
* @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
* Thrown when the selected entity does not match the id in th payload.
* @throws \Drupal\jsonapi\Exception\UnprocessableHttpEntityException
* Thrown when the patched entity does not pass validation.
*/
public function patchIndividual(ResourceType $resource_type, EntityInterface $entity, Request $request) {
if ($entity instanceof RevisionableInterface && !($entity->isLatestRevision() && $entity->isDefaultRevision())) {
throw new BadRequestHttpException('Updating a resource object that has a working copy is not yet supported. See https://www.drupal.org/project/drupal/issues/2795279.');

Alex Bronstein
committed
}
$parsed_entity = $this->deserialize($resource_type, $request, JsonApiDocumentTopLevel::class);
$body = Json::decode($request->getContent());
$data = $body['data'];
if (!isset($data['id']) || $data['id'] != $entity->uuid()) {

Alex Bronstein
committed
throw new BadRequestHttpException(sprintf(
'The selected entity (%s) does not match the ID in the payload (%s).',
$entity->uuid(),
$data['id'] ?? '',

Alex Bronstein
committed
));
}
$data += ['attributes' => [], 'relationships' => []];
$field_names = array_map([$resource_type, 'getInternalName'], array_merge(array_keys($data['attributes']), array_keys($data['relationships'])));

Alex Bronstein
committed
// User resource objects contain a read-only attribute that is not a real
// field on the user entity type.
// @see \Drupal\jsonapi\JsonApiResource\ResourceObject::extractContentEntityFields()
// @todo Eliminate this special casing in https://www.drupal.org/project/drupal/issues/3079254.
if ($entity->getEntityTypeId() === 'user') {
$field_names = array_diff($field_names, [$resource_type->getPublicName('display_name')]);
}

Alex Bronstein
committed
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
array_reduce($field_names, function (EntityInterface $destination, $field_name) use ($resource_type, $parsed_entity) {
$this->updateEntityField($resource_type, $parsed_entity, $destination, $field_name);
return $destination;
}, $entity);
static::validate($entity, $field_names);
// Set revision data details for revisionable entities.
if ($entity->getEntityType()->isRevisionable()) {
if ($bundle_entity_type = $entity->getEntityType()->getBundleEntityType()) {
$bundle_entity = $this->entityTypeManager->getStorage($bundle_entity_type)->load($entity->bundle());
if ($bundle_entity instanceof RevisionableEntityBundleInterface) {
$entity->setNewRevision($bundle_entity->shouldCreateNewRevision());
}
}
if ($entity instanceof RevisionLogInterface && $entity->isNewRevision()) {
$entity->setRevisionUserId($this->user->id());
$entity->setRevisionCreationTime($this->time->getRequestTime());
}
}
$entity->save();
$primary_data = new ResourceObjectData([ResourceObject::createFromEntity($resource_type, $entity)], 1);
return $this->buildWrappedResponse($primary_data, $request, $this->getIncludes($request, $primary_data));
}
/**
* Deletes an individual entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The loaded entity.
*
* @return \Drupal\jsonapi\ResourceResponse
* The response.
*/
public function deleteIndividual(EntityInterface $entity) {
// @todo Replace with entity handlers in: https://www.drupal.org/project/drupal/issues/3230434
if ($entity->getEntityTypeId() === 'user') {
$cancel_method = \Drupal::service('config.factory')->get('user.settings')->get('cancel_method');
// Allow other modules to act.
user_cancel([], $entity->id(), $cancel_method);
// Since user_cancel() is not invoked via Form API, batch processing
// needs to be invoked manually.
$batch =& batch_get();
// Mark this batch as non-progressive to bypass the progress bar and
// redirect.
$batch['progressive'] = FALSE;
batch_process();
}
else {
$entity->delete();
}

Alex Bronstein
committed
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
return new ResourceResponse(NULL, 204);
}
/**
* Gets the collection of entities.
*
* @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type
* The JSON:API resource type for the request to be served.
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
*
* @return \Drupal\jsonapi\ResourceResponse
* The response.
*
* @throws \Drupal\Core\Http\Exception\CacheableBadRequestHttpException
* Thrown when filtering on a config entity which does not support it.
*/
public function getCollection(ResourceType $resource_type, Request $request) {
// Instantiate the query for the filtering.
$entity_type_id = $resource_type->getEntityTypeId();
$params = $this->getJsonApiParams($request, $resource_type);
$query_cacheability = new CacheableMetadata();
$query = $this->getCollectionQuery($resource_type, $params, $query_cacheability);
// If the request is for the latest revision, toggle it on entity query.
if ($request->get(ResourceVersionRouteEnhancer::WORKING_COPIES_REQUESTED, FALSE)) {
$query->latestRevision();
}
try {
$results = $this->executeQueryInRenderContext(
$query,
$query_cacheability
);
}
catch (\LogicException $e) {
// Ensure good DX when an entity query involves a config entity type.
// For example: getting users with a particular role, which is a config
// entity type: https://www.drupal.org/project/drupal/issues/2959445.

Alex Bronstein
committed
// @todo Remove the message parsing in https://www.drupal.org/project/drupal/issues/3028967.
if (str_starts_with($e->getMessage(), 'Getting the base fields is not supported for entity type')) {

Alex Bronstein
committed
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
preg_match('/entity type (.*)\./', $e->getMessage(), $matches);
$config_entity_type_id = $matches[1];
$cacheability = (new CacheableMetadata())->addCacheContexts(['url.path', 'url.query_args:filter']);
throw new CacheableBadRequestHttpException($cacheability, sprintf("Filtering on config entities is not supported by Drupal's entity API. You tried to filter on a %s config entity.", $config_entity_type_id));
}
else {
throw $e;
}
}
$storage = $this->entityTypeManager->getStorage($entity_type_id);
// We request N+1 items to find out if there is a next page for the pager.
// We may need to remove that extra item before loading the entities.
$pager_size = $query->getMetaData('pager_size');
if ($has_next_page = $pager_size < count($results)) {
// Drop the last result.
array_pop($results);
}
// Each item of the collection data contains an array with 'entity' and
// 'access' elements.
$collection_data = $this->loadEntitiesWithAccess($storage, $results, $request->get(ResourceVersionRouteEnhancer::WORKING_COPIES_REQUESTED, FALSE));
$primary_data = new ResourceObjectData($collection_data);
$primary_data->setHasNextPage($has_next_page);
// Calculate all the results and pass into a JSON:API Data object.
$count_query_cacheability = new CacheableMetadata();
if ($resource_type->includeCount()) {
$count_query = $this->getCollectionCountQuery($resource_type, $params, $count_query_cacheability);
$total_results = $this->executeQueryInRenderContext(
$count_query,
$count_query_cacheability
);
$primary_data->setTotalCount($total_results);
}
$response = $this->respondWithCollection($primary_data, $this->getIncludes($request, $primary_data), $request, $resource_type, $params[OffsetPage::KEY_NAME]);
$response->addCacheableDependency($query_cacheability);
$response->addCacheableDependency($count_query_cacheability);
$response->addCacheableDependency((new CacheableMetadata())
->addCacheContexts([
'url.query_args:filter',
'url.query_args:sort',
'url.query_args:page',
]));
if ($resource_type->isVersionable()) {
$response->addCacheableDependency((new CacheableMetadata())->addCacheContexts([ResourceVersionRouteEnhancer::CACHE_CONTEXT]));
}
return $response;
}
/**
* Executes the query in a render context, to catch bubbled cacheability.
*
* @param \Drupal\Core\Entity\Query\QueryInterface $query
* The query to execute to get the return results.
* @param \Drupal\Core\Cache\CacheableMetadata $query_cacheability
* The value object to carry the query cacheability.
*
* @return int|array
* Returns an integer for count queries or an array of IDs. The values of
* the array are always entity IDs. The keys will be revision IDs if the
* entity supports revision and entity IDs if not.
*
* @see node_query_node_access_alter()
* @see https://www.drupal.org/project/drupal/issues/2557815
* @see https://www.drupal.org/project/drupal/issues/2794385
* @todo Remove this after https://www.drupal.org/project/drupal/issues/3028976 is fixed.
*/
protected function executeQueryInRenderContext(QueryInterface $query, CacheableMetadata $query_cacheability) {
$context = new RenderContext();
$results = $this->renderer->executeInRenderContext($context, function () use ($query) {
return $query->execute();
});
if (!$context->isEmpty()) {
$query_cacheability->addCacheableDependency($context->pop());
}
return $results;
}
/**
* Gets the related resource.
*
* @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type
* The JSON:API resource type for the request to be served.
* @param \Drupal\Core\Entity\FieldableEntityInterface $entity
* The requested entity.
* @param string $related
* The related field name.
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
*
* @return \Drupal\jsonapi\ResourceResponse
* The response.
*/
public function getRelated(ResourceType $resource_type, FieldableEntityInterface $entity, $related, Request $request) {
/** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $field_list */
$resource_relationship = $resource_type->getFieldByPublicName($related);
$field_list = $entity->get($resource_relationship->getInternalName());

Alex Bronstein
committed
// Remove the entities pointing to a resource that may be disabled. Even
// though the normalizer skips disabled references, we can avoid unnecessary
// work by checking here too.
/** @var \Drupal\Core\Entity\EntityInterface[] $referenced_entities */

Alex Bronstein
committed
$referenced_entities = array_filter(
$field_list->referencedEntities(),
function (EntityInterface $entity) {
return (bool) $this->resourceTypeRepository->get(
$entity->getEntityTypeId(),
$entity->bundle()
);
}
);
$collection_data = [];
foreach ($referenced_entities as $referenced_entity) {
$collection_data[] = $this->entityAccessChecker->getAccessCheckedResourceObject($referenced_entity);
}
$primary_data = new ResourceObjectData($collection_data, $resource_relationship->hasOne() ? 1 : -1);

Alex Bronstein
committed
$response = $this->buildWrappedResponse($primary_data, $request, $this->getIncludes($request, $primary_data));
// $response does not contain the entity list cache tag. We add the
// cacheable metadata for the finite list of entities in the relationship.
if ($response instanceof CacheableResponseInterface) {
$response->addCacheableDependency($entity);
}

Alex Bronstein
committed
return $response;
}
/**
* Gets the relationship of an entity.
*
* @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type
* The base JSON:API resource type for the request to be served.
* @param \Drupal\Core\Entity\FieldableEntityInterface $entity
* The requested entity.
* @param string $related
* The related field name.
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
* @param int $response_code
* The response code. Defaults to 200.
*
* @return \Drupal\jsonapi\ResourceResponse
* The response.
*/
public function getRelationship(ResourceType $resource_type, FieldableEntityInterface $entity, $related, Request $request, $response_code = 200) {
/** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $field_list */

Alex Bronstein
committed
$field_list = $entity->get($resource_type->getInternalName($related));
// Access will have already been checked by the RelationshipRouteAccessCheck

Alex Bronstein
committed
// service, so we don't need to call ::getAccessCheckedResourceObject().
$resource_object = ResourceObject::createFromEntity($resource_type, $entity);
$collect_meta_event = new CollectRelationshipMetaEvent($resource_object, $related);
$this->eventDispatcher->dispatch($collect_meta_event);
$relationship = Relationship::createFromEntityReferenceField(context: $resource_object, field: $field_list, meta: $collect_meta_event->getMeta());
$response = $this->buildWrappedResponse($relationship, $request, $this->getIncludes($request, $resource_object), $response_code);

Alex Bronstein
committed
// Add the host entity as a cacheable dependency.
if ($response instanceof CacheableResponseInterface) {
$response->addCacheableDependency($entity);

Théodore Biadala
committed
// Cacheability from the classes subscribed to
// CollectRelationshipMetaEvent is added to the response.
$response->addCacheableDependency($collect_meta_event);

Alex Bronstein
committed
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
return $response;
}
/**
* Adds a relationship to a to-many relationship.
*
* @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type
* The base JSON:API resource type for the request to be served.
* @param \Drupal\Core\Entity\FieldableEntityInterface $entity
* The requested entity.
* @param string $related
* The related field name.
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
*
* @return \Drupal\jsonapi\ResourceResponse
* The response.
*
* @throws \Drupal\jsonapi\Exception\EntityAccessDeniedHttpException
* Thrown when the current user is not allowed to PATCH the selected
* field(s).
* @throws \Symfony\Component\HttpKernel\Exception\ConflictHttpException
* Thrown when POSTing to a "to-one" relationship.
* @throws \Drupal\Core\Entity\EntityStorageException
* Thrown when the underlying entity cannot be saved.
* @throws \Drupal\jsonapi\Exception\UnprocessableHttpEntityException
* Thrown when the updated entity does not pass validation.
*/
public function addToRelationshipData(ResourceType $resource_type, FieldableEntityInterface $entity, $related, Request $request) {
$resource_identifiers = $this->deserialize($resource_type, $request, ResourceIdentifier::class, $related);
$internal_relationship_field_name = $resource_type->getInternalName($related);

Alex Bronstein
committed
// According to the specification, you are only allowed to POST to a
// relationship if it is a to-many relationship.
/** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $field_list */
$field_list = $entity->{$internal_relationship_field_name};
/** @var \Drupal\field\Entity\FieldConfig $field_definition */

Alex Bronstein
committed
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
$field_definition = $field_list->getFieldDefinition();
$is_multiple = $field_definition->getFieldStorageDefinition()->isMultiple();
if (!$is_multiple) {
throw new ConflictHttpException(sprintf('You can only POST to to-many relationships. %s is a to-one relationship.', $related));
}
$original_resource_identifiers = ResourceIdentifier::toResourceIdentifiersWithArityRequired($field_list);
$new_resource_identifiers = array_udiff(
ResourceIdentifier::deduplicate(array_merge($original_resource_identifiers, $resource_identifiers)),
$original_resource_identifiers,
[ResourceIdentifier::class, 'compare']
);
// There are no relationships that need to be added so we can exit early.
if (empty($new_resource_identifiers)) {
$status = static::relationshipResponseRequiresBody($resource_identifiers, $original_resource_identifiers) ? 200 : 204;
return $this->getRelationship($resource_type, $entity, $related, $request, $status);
}
$main_property_name = $field_definition->getItemDefinition()->getMainPropertyName();
foreach ($new_resource_identifiers as $new_resource_identifier) {
$new_field_value = [$main_property_name => $this->getEntityFromResourceIdentifier($new_resource_identifier)->id()];
// Remove `arity` from the received extra properties, otherwise this
// will fail field validation.
$new_field_value += array_diff_key($new_resource_identifier->getMeta(), array_flip([ResourceIdentifier::ARITY_KEY]));
$field_list->appendItem($new_field_value);
}
$this->validate($entity);
$entity->save();
$final_resource_identifiers = ResourceIdentifier::toResourceIdentifiersWithArityRequired($field_list);
$status = static::relationshipResponseRequiresBody($resource_identifiers, $final_resource_identifiers) ? 200 : 204;
return $this->getRelationship($resource_type, $entity, $related, $request, $status);
}
/**
* Updates the relationship of an entity.
*
* @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type
* The base JSON:API resource type for the request to be served.
* @param \Drupal\Core\Entity\EntityInterface $entity
* The requested entity.
* @param string $related
* The related field name.
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
*
* @return \Drupal\jsonapi\ResourceResponse
* The response.
*
* @throws \Drupal\Core\Entity\EntityStorageException
* Thrown when the underlying entity cannot be saved.
* @throws \Drupal\jsonapi\Exception\UnprocessableHttpEntityException
* Thrown when the updated entity does not pass validation.
*/
public function replaceRelationshipData(ResourceType $resource_type, EntityInterface $entity, $related, Request $request) {
/** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $resource_identifiers */

Alex Bronstein
committed
$resource_identifiers = $this->deserialize($resource_type, $request, ResourceIdentifier::class, $related);
$internal_relationship_field_name = $resource_type->getInternalName($related);

Alex Bronstein
committed
// According to the specification, PATCH works a little bit different if the
// relationship is to-one or to-many.
/** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $field_list */
$field_list = $entity->{$internal_relationship_field_name};

Alex Bronstein
committed
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
$field_definition = $field_list->getFieldDefinition();
$is_multiple = $field_definition->getFieldStorageDefinition()->isMultiple();
$method = $is_multiple ? 'doPatchMultipleRelationship' : 'doPatchIndividualRelationship';
$this->{$method}($entity, $resource_identifiers, $field_definition);
$this->validate($entity);
$entity->save();
$requires_response = static::relationshipResponseRequiresBody($resource_identifiers, ResourceIdentifier::toResourceIdentifiersWithArityRequired($field_list));
return $this->getRelationship($resource_type, $entity, $related, $request, $requires_response ? 200 : 204);
}
/**
* Update a to-one relationship.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The requested entity.
* @param \Drupal\jsonapi\JsonApiResource\ResourceIdentifier[] $resource_identifiers
* The client-sent resource identifiers which should be set on the given
* entity. Should be an empty array or an array with a single value.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The field definition of the entity field to be updated.
*
* @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
* Thrown when a "to-one" relationship is not provided.
*/
protected function doPatchIndividualRelationship(EntityInterface $entity, array $resource_identifiers, FieldDefinitionInterface $field_definition) {
if (count($resource_identifiers) > 1) {
throw new BadRequestHttpException(sprintf('Provide a single relationship so to-one relationship fields (%s).', $field_definition->getName()));
}
$this->doPatchMultipleRelationship($entity, $resource_identifiers, $field_definition);
}
/**
* Update a to-many relationship.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The requested entity.
* @param \Drupal\jsonapi\JsonApiResource\ResourceIdentifier[] $resource_identifiers
* The client-sent resource identifiers which should be set on the given
* entity.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The field definition of the entity field to be updated.
*/
protected function doPatchMultipleRelationship(EntityInterface $entity, array $resource_identifiers, FieldDefinitionInterface $field_definition) {
$main_property_name = $field_definition->getItemDefinition()->getMainPropertyName();
$entity->{$field_definition->getName()} = array_map(function (ResourceIdentifier $resource_identifier) use ($main_property_name) {
$field_properties = [$main_property_name => $this->getEntityFromResourceIdentifier($resource_identifier)->id()];
// Remove `arity` from the received extra properties, otherwise this
// will fail field validation.
$field_properties += array_diff_key($resource_identifier->getMeta(), array_flip([ResourceIdentifier::ARITY_KEY]));
return $field_properties;
}, $resource_identifiers);
}
/**
* Deletes the relationship of an entity.
*
* @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type
* The base JSON:API resource type for the request to be served.
* @param \Drupal\Core\Entity\EntityInterface $entity
* The requested entity.
* @param string $related
* The related field name.
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
*
* @return \Drupal\jsonapi\ResourceResponse
* The response.
*
* @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
* Thrown when not body was provided for the DELETE operation.
* @throws \Symfony\Component\HttpKernel\Exception\ConflictHttpException
* Thrown when deleting a "to-one" relationship.
* @throws \Drupal\Core\Entity\EntityStorageException
* Thrown when the underlying entity cannot be saved.
*/
public function removeFromRelationshipData(ResourceType $resource_type, EntityInterface $entity, $related, Request $request) {
$resource_identifiers = $this->deserialize($resource_type, $request, ResourceIdentifier::class, $related);
$internal_relationship_field_name = $resource_type->getInternalName($related);
/** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $field_list */
$field_list = $entity->{$internal_relationship_field_name};

Alex Bronstein
committed
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
$is_multiple = $field_list->getFieldDefinition()
->getFieldStorageDefinition()
->isMultiple();
if (!$is_multiple) {
throw new ConflictHttpException(sprintf('You can only DELETE from to-many relationships. %s is a to-one relationship.', $related));
}
// Compute the list of current values and remove the ones in the payload.
$original_resource_identifiers = ResourceIdentifier::toResourceIdentifiersWithArityRequired($field_list);
$removed_resource_identifiers = array_uintersect($resource_identifiers, $original_resource_identifiers, [ResourceIdentifier::class, 'compare']);
$deltas_to_be_removed = [];
foreach ($removed_resource_identifiers as $removed_resource_identifier) {
foreach ($original_resource_identifiers as $delta => $existing_resource_identifier) {
// Identify the field item deltas which should be removed.
if (ResourceIdentifier::isDuplicate($removed_resource_identifier, $existing_resource_identifier)) {
$deltas_to_be_removed[] = $delta;
}
}
}
// Field item deltas are reset when an item is removed. This removes
// items in descending order so that the deltas yet to be removed will
// continue to exist.
rsort($deltas_to_be_removed);
foreach ($deltas_to_be_removed as $delta) {
$field_list->removeItem($delta);
}
// Save the entity and return the response object.
static::validate($entity);
$entity->save();
return $this->getRelationship($resource_type, $entity, $related, $request, 204);
}
/**
* Deserializes a request body, if any.
*
* @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type
* The JSON:API resource type for the current request.
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
* @param string $class
* The class into which the request data needs to be deserialized.
* @param string $relationship_field_name
* The public relationship field name of the data to be deserialized if the
* incoming request is for a relationship update. Not required for non-
* relationship requests.
*
* @return array
* An object normalization.
*
* @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
* Thrown if the request body cannot be decoded, or when no request body was
* provided with a POST or PATCH request.
* @throws \Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException
* Thrown if the request body cannot be denormalized.
*/
protected function deserialize(ResourceType $resource_type, Request $request, $class, $relationship_field_name = NULL) {
assert($class === JsonApiDocumentTopLevel::class || $class === ResourceIdentifier::class && !empty($relationship_field_name) && is_string($relationship_field_name));
$received = (string) $request->getContent();
if (!$received) {
assert($request->isMethod('POST') || $request->isMethod('PATCH') || $request->isMethod('DELETE'));
if ($request->isMethod('DELETE') && $relationship_field_name) {
throw new BadRequestHttpException(sprintf('You need to provide a body for DELETE operations on a relationship (%s).', $relationship_field_name));
}
else {
throw new BadRequestHttpException('Empty request body.');
}
}
// First decode the request data. We can then determine if the serialized
// data was malformed.
try {
$decoded = $this->serializer->decode($received, 'api_json');
}
catch (UnexpectedValueException $e) {
// If an exception was thrown at this stage, there was a problem decoding
// the data. Throw a 400 HTTP exception.
throw new BadRequestHttpException($e->getMessage());
}
try {
$context = ['resource_type' => $resource_type];
if ($relationship_field_name) {
$context['related'] = $resource_type->getInternalName($relationship_field_name);
}
return $this->serializer->denormalize($decoded, $class, 'api_json', $context);
}
// These two serialization exception types mean there was a problem with
// the structure of the decoded data and it's not valid.
catch (UnexpectedValueException $e) {
throw new UnprocessableEntityHttpException($e->getMessage());

Alex Bronstein
committed
}
catch (InvalidArgumentException $e) {
throw new UnprocessableEntityHttpException($e->getMessage());

Alex Bronstein
committed
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
}
}
/**
* Gets a basic query for a collection.
*
* @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type
* The base JSON:API resource type for the query.
* @param array $params
* The parameters for the query.
* @param \Drupal\Core\Cache\CacheableMetadata $query_cacheability
* Collects cacheability for the query.
*
* @return \Drupal\Core\Entity\Query\QueryInterface
* A new query.
*/
protected function getCollectionQuery(ResourceType $resource_type, array $params, CacheableMetadata $query_cacheability) {
$entity_type = $this->entityTypeManager->getDefinition($resource_type->getEntityTypeId());
$entity_storage = $this->entityTypeManager->getStorage($resource_type->getEntityTypeId());
$query = $entity_storage->getQuery();
// Ensure that access checking is performed on the query.
$query->accessCheck(TRUE);
// Compute and apply an entity query condition from the filter parameter.
if (isset($params[Filter::KEY_NAME]) && $filter = $params[Filter::KEY_NAME]) {
$query->condition($filter->queryCondition($query));
TemporaryQueryGuard::setFieldManager($this->fieldManager);
TemporaryQueryGuard::setModuleHandler(\Drupal::moduleHandler());
TemporaryQueryGuard::applyAccessControls($filter, $query, $query_cacheability);
}
// Apply any sorts to the entity query.
if (isset($params[Sort::KEY_NAME]) && $sort = $params[Sort::KEY_NAME]) {
foreach ($sort->fields() as $field) {
$path = $this->fieldResolver->resolveInternalEntityQueryPath($resource_type, $field[Sort::PATH_KEY]);
$direction = $field[Sort::DIRECTION_KEY] ?? 'ASC';
$langcode = $field[Sort::LANGUAGE_KEY] ?? NULL;

Alex Bronstein
committed
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
$query->sort($path, $direction, $langcode);
}
}
// Apply any pagination options to the query.
if (isset($params[OffsetPage::KEY_NAME])) {
$pagination = $params[OffsetPage::KEY_NAME];
}
else {
$pagination = new OffsetPage(OffsetPage::DEFAULT_OFFSET, OffsetPage::SIZE_MAX);
}
// Add one extra element to the page to see if there are more pages needed.
$query->range($pagination->getOffset(), $pagination->getSize() + 1);
$query->addMetaData('pager_size', (int) $pagination->getSize());
// Limit this query to the bundle type for this resource.
$bundle = $resource_type->getBundle();
if ($bundle && ($bundle_key = $entity_type->getKey('bundle'))) {
$query->condition(
$bundle_key, $bundle
);
}
return $query;
}
/**
* Gets a basic query for a collection count.
*
* @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type
* The base JSON:API resource type for the query.
* @param array $params
* The parameters for the query.
* @param \Drupal\Core\Cache\CacheableMetadata $query_cacheability
* Collects cacheability for the query.
*
* @return \Drupal\Core\Entity\Query\QueryInterface
* A new query.
*/
protected function getCollectionCountQuery(ResourceType $resource_type, array $params, CacheableMetadata $query_cacheability) {
// Reset the range to get all the available results.
return $this->getCollectionQuery($resource_type, $params, $query_cacheability)->range()->count();
}
/**
* Loads the entity targeted by a resource identifier.
*
* @param \Drupal\jsonapi\JsonApiResource\ResourceIdentifier $resource_identifier
* A resource identifier.
*
* @return \Drupal\Core\Entity\EntityInterface
* The entity targeted by a resource identifier.
*
* @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
* Thrown if the given resource identifier targets a resource type or
* resource which does not exist.
*/
protected function getEntityFromResourceIdentifier(ResourceIdentifier $resource_identifier) {
$resource_type_name = $resource_identifier->getTypeName();
if (!($target_resource_type = $this->resourceTypeRepository->getByTypeName($resource_type_name))) {
throw new BadRequestHttpException("The resource type `{$resource_type_name}` does not exist.");
}
$id = $resource_identifier->getId();
if (!($targeted_resource = $this->entityRepository->loadEntityByUuid($target_resource_type->getEntityTypeId(), $id))) {
throw new BadRequestHttpException("The targeted `{$resource_type_name}` resource with ID `{$id}` does not exist.");
}
return $targeted_resource;
}