You are here

public function EntityResource::getRelated in JSON:API 8.2

Same name and namespace in other branches
  1. 8 src/Controller/EntityResource.php \Drupal\jsonapi\Controller\EntityResource::getRelated()

Gets the related resource.

Parameters

\Drupal\jsonapi\ResourceType\ResourceType $resource_type: The JSON:API resource type for the request to be served.

\Drupal\Core\Entity\FieldableEntityInterface $entity: The requested entity.

string $related: The related field name.

\Symfony\Component\HttpFoundation\Request $request: The request object.

Return value

\Drupal\jsonapi\ResourceResponse The response.

File

src/Controller/EntityResource.php, line 497

Class

EntityResource
Process all entity requests.

Namespace

Drupal\jsonapi\Controller

Code

public function getRelated(ResourceType $resource_type, FieldableEntityInterface $entity, $related, Request $request) {

  /* @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $field_list */
  $field_list = $entity
    ->get($resource_type
    ->getInternalName($related));

  // 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 */
  $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, $field_list
    ->getFieldDefinition()
    ->getFieldStorageDefinition()
    ->getCardinality());
  $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.
  $response
    ->addCacheableDependency($entity);
  return $response;
}