Responds to entity PATCH requests.
mixed $id: The entity ID.
\Drupal\Core\Entity\EntityInterface $entity: The entity.
\Drupal\rest\ResourceResponse The HTTP response object.
\Symfony\Component\HttpKernel\Exception\HttpException
public function patch($id, EntityInterface $entity) {
if (empty($id)) {
throw new NotFoundHttpException();
}
$definition = $this
->getPluginDefinition();
if ($entity
->entityType() != $definition['entity_type']) {
throw new BadRequestHttpException(t('Invalid entity type'));
}
$original_entity = entity_load($definition['entity_type'], $id);
// We don't support creating entities with PATCH, so we throw an error if
// there is no existing entity.
if ($original_entity == FALSE) {
throw new NotFoundHttpException();
}
if (!$original_entity
->access('update')) {
throw new AccessDeniedHttpException();
}
$info = $original_entity
->entityInfo();
// Make sure that the entity ID is the one provided in the URL.
$entity->{$info['entity_keys']['id']} = $id;
// Overwrite the received properties.
foreach ($entity as $field_name => $field) {
if (isset($entity->{$field_name})) {
if (empty($entity->{$field_name})) {
if (!$original_entity->{$field_name}
->access('delete')) {
throw new AccessDeniedHttpException(t('Access denied on deleting field @field.', array(
'@field' => $field_name,
)));
}
}
else {
if (!$original_entity->{$field_name}
->access('update')) {
throw new AccessDeniedHttpException(t('Access denied on updating field @field.', array(
'@field' => $field_name,
)));
}
}
$original_entity->{$field_name} = $field;
}
}
try {
$original_entity
->save();
watchdog('rest', 'Updated entity %type with ID %id.', array(
'%type' => $entity
->entityType(),
'%id' => $entity
->id(),
));
// Update responses have an empty body.
return new ResourceResponse(NULL, 204);
} catch (EntityStorageException $e) {
throw new HttpException(500, t('Internal Server Error'), $e);
}
}