You are here

public function EntityResource::patch in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 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\ResourceResponse The HTTP response object.

Throws

\Symfony\Component\HttpKernel\Exception\HttpException

File

core/modules/rest/src/Plugin/rest/resource/EntityResource.php, line 134
Contains \Drupal\rest\Plugin\rest\resource\EntityResource.

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');
  }
  if (!$original_entity
    ->access('update')) {
    throw new AccessDeniedHttpException();
  }

  // Overwrite the received properties.
  $langcode_key = $entity
    ->getEntityType()
    ->getKey('langcode');
  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.
    if ($field_name == $langcode_key && $field
      ->isEmpty()) {
      continue;
    }
    if (!$original_entity
      ->get($field_name)
      ->access('edit')) {
      throw new AccessDeniedHttpException("Access denied on updating field '{$field_name}'.");
    }
    $original_entity
      ->set($field_name, $field
      ->getValue());
  }

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

    // Update responses have an empty body.
    return new ResourceResponse(NULL, 204);
  } catch (EntityStorageException $e) {
    throw new HttpException(500, 'Internal Server Error', $e);
  }
}