You are here

public function EntityResource::patchIndividual in JSON:API 8

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

Patches an individual entity.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The loaded entity.

\Drupal\Core\Entity\EntityInterface $parsed_entity: The entity with the new data.

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

Return value

\Drupal\jsonapi\ResourceResponse The response.

Throws

\Drupal\Core\Entity\EntityStorageException

\Drupal\jsonapi\Exception\EntityAccessDeniedHttpException

File

src/Controller/EntityResource.php, line 295

Class

EntityResource
Process all entity requests.

Namespace

Drupal\jsonapi\Controller

Code

public function patchIndividual(EntityInterface $entity, EntityInterface $parsed_entity, Request $request) {
  $entity_access = $entity
    ->access('update', NULL, TRUE);
  if (!$entity_access
    ->isAllowed()) {
    throw new EntityAccessDeniedHttpException($entity, $entity_access, '/data', 'The current user is not allowed to PATCH the selected resource.');
  }
  $body = Json::decode($request
    ->getContent());
  $data = $body['data'];
  if ($data['id'] != $entity
    ->uuid()) {
    throw new BadRequestHttpException(sprintf('The selected entity (%s) does not match the ID in the payload (%s).', $entity
      ->uuid(), $data['id']));
  }
  $data += [
    'attributes' => [],
    'relationships' => [],
  ];
  $field_names = array_merge(array_keys($data['attributes']), array_keys($data['relationships']));
  array_reduce($field_names, function (EntityInterface $destination, $field_name) use ($parsed_entity) {
    $this
      ->updateEntityField($parsed_entity, $destination, $field_name);
    return $destination;
  }, $entity);
  $this
    ->validate($entity, $field_names);
  $entity
    ->save();
  return $this
    ->buildWrappedResponse($entity);
}