You are here

public function EntityResource::patch in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/rest/src/Plugin/rest/resource/EntityResource.php \Drupal\rest\Plugin\rest\resource\EntityResource::patch()

Responds to entity PATCH requests.

Parameters

\Drupal\Core\Entity\EntityInterface $original_entity: The original entity object.

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

Return value

\Drupal\rest\ModifiedResourceResponse The HTTP response object.

Throws

\Symfony\Component\HttpKernel\Exception\HttpException

File

core/modules/rest/src/Plugin/rest/resource/EntityResource.php, line 217

Class

EntityResource
Represents entities as resources.

Namespace

Drupal\rest\Plugin\rest\resource

Code

public function patch(EntityInterface $original_entity, EntityInterface $entity = NULL) {
  if ($entity == NULL) {
    throw new BadRequestHttpException('No entity content received.');
  }
  $definition = $this
    ->getPluginDefinition();
  if ($entity
    ->getEntityTypeId() != $definition['entity_type']) {
    throw new BadRequestHttpException('Invalid entity type');
  }

  // Overwrite the received fields.
  // @todo Remove $changed_fields in https://www.drupal.org/project/drupal/issues/2862574.
  $changed_fields = [];
  foreach ($entity->_restSubmittedFields as $field_name) {
    $field = $entity
      ->get($field_name);

    // It is not possible to set the language to NULL as it is automatically
    // re-initialized. As it must not be empty, skip it if it is.
    // @todo Remove in https://www.drupal.org/project/drupal/issues/2933408.
    if ($entity
      ->getEntityType()
      ->hasKey('langcode') && $field_name === $entity
      ->getEntityType()
      ->getKey('langcode') && $field
      ->isEmpty()) {
      continue;
    }
    if ($this
      ->checkPatchFieldAccess($original_entity
      ->get($field_name), $field)) {
      $changed_fields[] = $field_name;
      $original_entity
        ->set($field_name, $field
        ->getValue());
    }
  }

  // If no fields are changed, we can send a response immediately!
  if (empty($changed_fields)) {
    return new ModifiedResourceResponse($original_entity, 200);
  }

  // Validate the received data before saving.
  $this
    ->validate($original_entity, $changed_fields);
  try {
    $original_entity
      ->save();
    $this->logger
      ->notice('Updated entity %type with ID %id.', [
      '%type' => $original_entity
        ->getEntityTypeId(),
      '%id' => $original_entity
        ->id(),
    ]);

    // Return the updated entity in the response body.
    return new ModifiedResourceResponse($original_entity, 200);
  } catch (EntityStorageException $e) {
    throw new HttpException(500, 'Internal Server Error', $e);
  }
}