You are here

public function EntityResource::replaceRelationshipData in JSON:API 8.2

Updates the relationship of an entity.

Parameters

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

\Drupal\Core\Entity\EntityInterface $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.

Throws

\Drupal\Core\Entity\EntityStorageException Thrown when the underlying entity cannot be saved.

\Drupal\jsonapi\Exception\UnprocessableHttpEntityException Thrown when the updated entity does not pass validation.

File

src/Controller/EntityResource.php, line 649

Class

EntityResource
Process all entity requests.

Namespace

Drupal\jsonapi\Controller

Code

public function replaceRelationshipData(ResourceType $resource_type, EntityInterface $entity, $related, Request $request) {
  $resource_identifiers = $this
    ->deserialize($resource_type, $request, ResourceIdentifier::class, $related);
  $related = $resource_type
    ->getInternalName($related);

  /* @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $resource_identifiers */

  // 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->{$related};
  $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);
}