class EntityResource (View source)

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.
 

Process all entity requests.

Traits

Provides a method to validate an entity.

Properties

protected EntityTypeManagerInterface $entityTypeManager

The entity type manager.

protected EntityFieldManagerInterface $fieldManager

The field manager.

protected ResourceTypeRepositoryInterface $resourceTypeRepository

The resource type repository.

protected RendererInterface $renderer

The renderer.

protected EntityRepositoryInterface $entityRepository

The entity repository.

protected IncludeResolver $includeResolver

The include resolver.

protected EntityAccessChecker $entityAccessChecker

The JSON:API entity access checker.

protected FieldResolver $fieldResolver

The JSON:API field resolver.

protected SerializerInterface|DenormalizerInterface $serializer

The JSON:API serializer.

protected TimeInterface $time

The time service.

protected AccountInterface $user

The current user account.

Methods

static 
validate(EntityInterface $entity, array $field_names = NULL)

Verifies that an entity does not violate any validation constraints.

__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)

Instantiates an EntityResource object.

getIndividual(EntityInterface $entity, Request $request)

Gets the individual entity.

createIndividual(ResourceType $resource_type, Request $request)

Creates an individual entity.

patchIndividual(ResourceType $resource_type, EntityInterface $entity, Request $request)

Patches an individual entity.

deleteIndividual(EntityInterface $entity)

Deletes an individual entity.

getCollection(ResourceType $resource_type, Request $request)

Gets the collection of entities.

int|array
executeQueryInRenderContext(QueryInterface $query, CacheableMetadata $query_cacheability)

Executes the query in a render context, to catch bubbled cacheability.

getRelated(ResourceType $resource_type, FieldableEntityInterface $entity, string $related, Request $request)

Gets the related resource.

getRelationship(ResourceType $resource_type, FieldableEntityInterface $entity, string $related, Request $request, int $response_code = 200)

Gets the relationship of an entity.

addToRelationshipData(ResourceType $resource_type, FieldableEntityInterface $entity, string $related, Request $request)

Adds a relationship to a to-many relationship.

replaceRelationshipData(ResourceType $resource_type, EntityInterface $entity, string $related, Request $request)

Updates the relationship of an entity.

doPatchIndividualRelationship(EntityInterface $entity, array $resource_identifiers, FieldDefinitionInterface $field_definition)

Update a to-one relationship.

doPatchMultipleRelationship(EntityInterface $entity, array $resource_identifiers, FieldDefinitionInterface $field_definition)

Update a to-many relationship.

removeFromRelationshipData(ResourceType $resource_type, EntityInterface $entity, string $related, Request $request)

Deletes the relationship of an entity.

array
deserialize(ResourceType $resource_type, Request $request, string $class, string $relationship_field_name = NULL)

Deserializes a request body, if any.

getCollectionQuery(ResourceType $resource_type, array $params, CacheableMetadata $query_cacheability)

Gets a basic query for a collection.

getCollectionCountQuery(ResourceType $resource_type, array $params, CacheableMetadata $query_cacheability)

Gets a basic query for a collection count.

getEntityFromResourceIdentifier(ResourceIdentifier $resource_identifier)

Loads the entity targeted by a resource identifier.

static bool
relationshipResponseRequiresBody(array $received_resource_identifiers, array $final_resource_identifiers)

Determines if the client needs to be updated with new relationship data.

buildWrappedResponse(TopLevelDataInterface $data, Request $request, IncludedData $includes, int $response_code = 200, array $headers = [], LinkCollection $links = NULL, array $meta = [])

Builds a response with the appropriate wrapped document.

respondWithCollection(ResourceObjectData $primary_data, Data $includes, Request $request, ResourceType $resource_type, OffsetPage $page_param)

Respond with an entity collection.

updateEntityField(ResourceType $resource_type, EntityInterface $origin, EntityInterface $destination, string $field_name)

Takes a field from the origin entity and puts it to the destination entity.

getIncludes(Request $request, ResourceObject|ResourceObjectData $data)

Gets includes for the given response data.

bool
checkPatchFieldAccess(FieldItemListInterface $original_field, FieldItemListInterface $received_field)

Checks whether the given field should be PATCHed.

array
loadEntitiesWithAccess(EntityStorageInterface $storage, array $ids, bool $load_latest_revisions)

Build a collection of the entities to respond with and access objects.

bool
entityExists(EntityInterface $entity)

Checks if the given entity exists.

array
getJsonApiParams(Request $request, ResourceType $resource_type)

Extracts JSON:API query parameters from the request.

static Url
getRequestLink(Request $request, array|null $query = NULL)

Get the full URL for a given request object.

static LinkCollection
getPagerLinks(Request $request, OffsetPage $page_param, array $link_context = [])

Get the pager links for a given request object.

static array
getPagerQueries(string $link_id, int $offset, int $size, array $query = [], int $total = 0)

Get the query param array.

Details

static protected validate(EntityInterface $entity, array $field_names = NULL)

Verifies that an entity does not violate any validation constraints.

Parameters

EntityInterface $entity

The entity object.

array $field_names

(optional) An array of field names. If specified, filters the violations list to include only this set of fields. Defaults to NULL, which means that all violations will be reported.

Exceptions

UnprocessableHttpEntityException

See also

EntityResourceValidationTrait::validate

__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)

Instantiates an EntityResource object.

Parameters

EntityTypeManagerInterface $entity_type_manager

The entity type manager.

EntityFieldManagerInterface $field_manager

The entity type field manager.

ResourceTypeRepositoryInterface $resource_type_repository

The JSON:API resource type repository.

RendererInterface $renderer

The renderer.

EntityRepositoryInterface $entity_repository

The entity repository.

IncludeResolver $include_resolver

The include resolver.

EntityAccessChecker $entity_access_checker

The JSON:API entity access checker.

FieldResolver $field_resolver

The JSON:API field resolver.

SerializerInterface $serializer

The JSON:API serializer.

TimeInterface $time

The time service.

AccountInterface $user

The current user account.

ResourceResponse getIndividual(EntityInterface $entity, Request $request)

Gets the individual entity.

Parameters

EntityInterface $entity

The loaded entity.

Request $request

The request object.

Return Value

ResourceResponse

The response.

Exceptions

EntityAccessDeniedHttpException

ResourceResponse createIndividual(ResourceType $resource_type, Request $request)

Creates an individual entity.

Parameters

ResourceType $resource_type

The JSON:API resource type for the request to be served.

Request $request

The request object.

Return Value

ResourceResponse

The response.

Exceptions

ConflictHttpException
UnprocessableHttpEntityException

ResourceResponse patchIndividual(ResourceType $resource_type, EntityInterface $entity, Request $request)

Patches an individual entity.

Parameters

ResourceType $resource_type

The JSON:API resource type for the request to be served.

EntityInterface $entity

The loaded entity.

Request $request

The request object.

Return Value

ResourceResponse

The response.

Exceptions

BadRequestHttpException
UnprocessableHttpEntityException

ResourceResponse deleteIndividual(EntityInterface $entity)

Deletes an individual entity.

Parameters

EntityInterface $entity

The loaded entity.

Return Value

ResourceResponse

The response.

ResourceResponse getCollection(ResourceType $resource_type, Request $request)

Gets the collection of entities.

Parameters

ResourceType $resource_type

The JSON:API resource type for the request to be served.

Request $request

The request object.

Return Value

ResourceResponse

The response.

Exceptions

CacheableBadRequestHttpException

protected int|array executeQueryInRenderContext(QueryInterface $query, CacheableMetadata $query_cacheability)

Executes the query in a render context, to catch bubbled cacheability.

Remove this after https://www.drupal.org/project/drupal/issues/3028976 is fixed.

Parameters

QueryInterface $query

The query to execute to get the return results.

CacheableMetadata $query_cacheability

The value object to carry the query cacheability.

Return Value

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 also

node_query_node_access_alter()
https://www.drupal.org/project/drupal/issues/2557815
https://www.drupal.org/project/drupal/issues/2794385

ResourceResponse getRelated(ResourceType $resource_type, FieldableEntityInterface $entity, string $related, Request $request)

Gets the related resource.

Parameters

ResourceType $resource_type

The JSON:API resource type for the request to be served.

FieldableEntityInterface $entity

The requested entity.

string $related

The related field name.

Request $request

The request object.

Return Value

ResourceResponse

The response.

ResourceResponse getRelationship(ResourceType $resource_type, FieldableEntityInterface $entity, string $related, Request $request, int $response_code = 200)

Gets the relationship of an entity.

Parameters

ResourceType $resource_type

The base JSON:API resource type for the request to be served.

FieldableEntityInterface $entity

The requested entity.

string $related

The related field name.

Request $request

The request object.

int $response_code

The response code. Defaults to 200.

Return Value

ResourceResponse

The response.

ResourceResponse addToRelationshipData(ResourceType $resource_type, FieldableEntityInterface $entity, string $related, Request $request)

Adds a relationship to a to-many relationship.

Parameters

ResourceType $resource_type

The base JSON:API resource type for the request to be served.

FieldableEntityInterface $entity

The requested entity.

string $related

The related field name.

Request $request

The request object.

Return Value

ResourceResponse

The response.

Exceptions

EntityAccessDeniedHttpException
ConflictHttpException
EntityStorageException
UnprocessableHttpEntityException

ResourceResponse replaceRelationshipData(ResourceType $resource_type, EntityInterface $entity, string $related, Request $request)

Updates the relationship of an entity.

Parameters

ResourceType $resource_type

The base JSON:API resource type for the request to be served.

EntityInterface $entity

The requested entity.

string $related

The related field name.

Request $request

The request object.

Return Value

ResourceResponse

The response.

Exceptions

EntityStorageException
UnprocessableHttpEntityException

protected doPatchIndividualRelationship(EntityInterface $entity, array $resource_identifiers, FieldDefinitionInterface $field_definition)

Update a to-one relationship.

Parameters

EntityInterface $entity

The requested entity.

array $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.

FieldDefinitionInterface $field_definition

The field definition of the entity field to be updated.

Exceptions

BadRequestHttpException

protected doPatchMultipleRelationship(EntityInterface $entity, array $resource_identifiers, FieldDefinitionInterface $field_definition)

Update a to-many relationship.

Parameters

EntityInterface $entity

The requested entity.

array $resource_identifiers

The client-sent resource identifiers which should be set on the given entity.

FieldDefinitionInterface $field_definition

The field definition of the entity field to be updated.

ResourceResponse removeFromRelationshipData(ResourceType $resource_type, EntityInterface $entity, string $related, Request $request)

Deletes the relationship of an entity.

Parameters

ResourceType $resource_type

The base JSON:API resource type for the request to be served.

EntityInterface $entity

The requested entity.

string $related

The related field name.

Request $request

The request object.

Return Value

ResourceResponse

The response.

Exceptions

BadRequestHttpException
ConflictHttpException
EntityStorageException

protected array deserialize(ResourceType $resource_type, Request $request, string $class, string $relationship_field_name = NULL)

Deserializes a request body, if any.

Parameters

ResourceType $resource_type

The JSON:API resource type for the current request.

Request $request

The request object.

string $class

The class into which the request data needs to be deserialized.

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 Value

array

An object normalization.

Exceptions

BadRequestHttpException
UnprocessableEntityHttpException

protected QueryInterface getCollectionQuery(ResourceType $resource_type, array $params, CacheableMetadata $query_cacheability)

Gets a basic query for a collection.

Parameters

ResourceType $resource_type

The base JSON:API resource type for the query.

array $params

The parameters for the query.

CacheableMetadata $query_cacheability

Collects cacheability for the query.

Return Value

QueryInterface

A new query.

protected QueryInterface getCollectionCountQuery(ResourceType $resource_type, array $params, CacheableMetadata $query_cacheability)

Gets a basic query for a collection count.

Parameters

ResourceType $resource_type

The base JSON:API resource type for the query.

array $params

The parameters for the query.

CacheableMetadata $query_cacheability

Collects cacheability for the query.

Return Value

QueryInterface

A new query.

protected EntityInterface getEntityFromResourceIdentifier(ResourceIdentifier $resource_identifier)

Loads the entity targeted by a resource identifier.

Parameters

ResourceIdentifier $resource_identifier

A resource identifier.

Return Value

EntityInterface

The entity targeted by a resource identifier.

Exceptions

BadRequestHttpException

static protected bool relationshipResponseRequiresBody(array $received_resource_identifiers, array $final_resource_identifiers)

Determines if the client needs to be updated with new relationship data.

Parameters

array $received_resource_identifiers

The array of resource identifiers given by the client.

array $final_resource_identifiers

The final array of resource identifiers after applying the requested changes.

Return Value

bool

Whether the final array of resource identifiers is different than the client-sent data.

protected ResourceResponse buildWrappedResponse(TopLevelDataInterface $data, Request $request, IncludedData $includes, int $response_code = 200, array $headers = [], LinkCollection $links = NULL, array $meta = [])

Builds a response with the appropriate wrapped document.

Parameters

TopLevelDataInterface $data

The data to wrap.

Request $request

The request object.

IncludedData $includes

The resources to be included in the document. Use NullData if there should be no included resources in the document.

int $response_code

The response code.

array $headers

An array of response headers.

LinkCollection $links

The URLs to which to link. A 'self' link is added automatically.

array $meta

(optional) The top-level metadata.

Return Value

ResourceResponse

The response.

protected ResourceResponse respondWithCollection(ResourceObjectData $primary_data, Data $includes, Request $request, ResourceType $resource_type, OffsetPage $page_param)

Respond with an entity collection.

Parameters

ResourceObjectData $primary_data

The collection of entities.

Data $includes

The resources to be included in the document.

Request $request

The request object.

ResourceType $resource_type

The base JSON:API resource type for the request to be served.

OffsetPage $page_param

The pagination parameter for the requested collection.

Return Value

ResourceResponse

The response.

protected updateEntityField(ResourceType $resource_type, EntityInterface $origin, EntityInterface $destination, string $field_name)

Takes a field from the origin entity and puts it to the destination entity.

Parameters

ResourceType $resource_type

The JSON:API resource type of the entity to be updated.

EntityInterface $origin

The entity that contains the field values.

EntityInterface $destination

The entity that needs to be updated.

string $field_name

The name of the field to extract and update.

Exceptions

BadRequestHttpException

Data getIncludes(Request $request, ResourceObject|ResourceObjectData $data)

Gets includes for the given response data.

Parameters

Request $request

The request object.

ResourceObject|ResourceObjectData $data

The response data from which to resolve includes.

Return Value

Data

A Data object to be included or a NullData object if the request does not specify any include paths.

Exceptions

InvalidPluginDefinitionException
PluginNotFoundException

protected bool checkPatchFieldAccess(FieldItemListInterface $original_field, FieldItemListInterface $received_field)

internal  
 

Checks whether the given field should be PATCHed.

Parameters

FieldItemListInterface $original_field

The original (stored) value for the field.

FieldItemListInterface $received_field

The received value for the field.

Return Value

bool

Whether the field should be PATCHed or not.

Exceptions

EntityAccessDeniedHttpException

See also

EntityResource::checkPatchFieldAccess

protected array loadEntitiesWithAccess(EntityStorageInterface $storage, array $ids, bool $load_latest_revisions)

Build a collection of the entities to respond with and access objects.

Parameters

EntityStorageInterface $storage

The entity storage to load the entities from.

array $ids

An array of entity IDs, keyed by revision ID if the entity type is revisionable.

bool $load_latest_revisions

Whether to load the latest revisions instead of the defaults.

Return Value

array

An array of loaded entities and/or an access exceptions.

protected bool entityExists(EntityInterface $entity)

Checks if the given entity exists.

Parameters

EntityInterface $entity

The entity for which to test existence.

Return Value

bool

Whether the entity already has been created.

protected array getJsonApiParams(Request $request, ResourceType $resource_type)

Extracts JSON:API query parameters from the request.

Parameters

Request $request

The request object.

ResourceType $resource_type

The JSON:API resource type.

Return Value

array

An array of JSON:API parameters like sort and filter.

Get the full URL for a given request object.

Parameters

Request $request

The request object.

array|null $query

The query parameters to use. Leave it empty to get the query from the request object.

Return Value

Url

The full URL.

Get the pager links for a given request object.

Parameters

Request $request

The request object.

OffsetPage $page_param

The current pagination parameter for the requested collection.

array $link_context

An associative array with extra data to build the links.

Return Value

LinkCollection

A LinkCollection, with:

  • a 'next' key if it is not the last page;
  • 'prev' and 'first' keys if it's not the first page.

static protected array getPagerQueries(string $link_id, int $offset, int $size, array $query = [], int $total = 0)

Get the query param array.

Parameters

string $link_id

The name of the pagination link requested.

int $offset

The starting index.

int $size

The pagination page size.

array $query

The query parameters.

int $total

The total size of the collection.

Return Value

array

The pagination query param array.