View source
<?php
namespace Drupal\rest\Plugin\rest\resource;
use Drupal\Component\Plugin\DependentPluginInterface;
use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Core\Access\AccessResultReasonInterface;
use Drupal\Core\Cache\CacheableResponseInterface;
use Drupal\Core\Config\Entity\ConfigEntityType;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Routing\AccessAwareRouterInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\rest\ModifiedResourceResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
class EntityResource extends ResourceBase implements DependentPluginInterface {
use EntityResourceValidationTrait;
use EntityResourceAccessTrait;
protected $entityType;
protected $configFactory;
protected $linkRelationTypeManager;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, $serializer_formats, LoggerInterface $logger, ConfigFactoryInterface $config_factory, PluginManagerInterface $link_relation_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
$this->entityType = $entity_type_manager
->getDefinition($plugin_definition['entity_type']);
$this->configFactory = $config_factory;
$this->linkRelationTypeManager = $link_relation_type_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_type.manager'), $container
->getParameter('serializer.formats'), $container
->get('logger.factory')
->get('rest'), $container
->get('config.factory'), $container
->get('plugin.manager.link_relation_type'));
}
public function get(EntityInterface $entity, Request $request) {
$response = new ResourceResponse($entity, 200);
$response
->addCacheableDependency($request->attributes
->get(AccessAwareRouterInterface::ACCESS_RESULT));
$response
->addCacheableDependency($entity);
if ($entity instanceof FieldableEntityInterface) {
foreach ($entity as $field_name => $field) {
$field_access = $field
->access('view', NULL, TRUE);
$response
->addCacheableDependency($field_access);
if (!$field_access
->isAllowed()) {
$entity
->set($field_name, NULL);
}
}
}
$this
->addLinkHeaders($entity, $response);
return $response;
}
public function post(EntityInterface $entity = NULL) {
if ($entity == NULL) {
throw new BadRequestHttpException('No entity content received.');
}
$entity_access = $entity
->access('create', NULL, TRUE);
if (!$entity_access
->isAllowed()) {
throw new AccessDeniedHttpException($entity_access
->getReason() ?: $this
->generateFallbackAccessDeniedMessage($entity, 'create'));
}
$definition = $this
->getPluginDefinition();
if ($entity
->getEntityTypeId() != $definition['entity_type']) {
throw new BadRequestHttpException('Invalid entity type');
}
if (!$entity
->isNew()) {
throw new BadRequestHttpException('Only new entities can be created');
}
$this
->checkEditFieldAccess($entity);
$this
->validate($entity);
try {
$entity
->save();
$this->logger
->notice('Created entity %type with ID %id.', [
'%type' => $entity
->getEntityTypeId(),
'%id' => $entity
->id(),
]);
$headers = [];
if (in_array('canonical', $entity
->uriRelationships(), TRUE)) {
$url = $entity
->toUrl('canonical', [
'absolute' => TRUE,
])
->toString(TRUE);
$headers['Location'] = $url
->getGeneratedUrl();
}
return new ModifiedResourceResponse($entity, 201, $headers);
} catch (EntityStorageException $e) {
throw new HttpException(500, 'Internal Server Error', $e);
}
}
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');
}
$changed_fields = [];
foreach ($entity->_restSubmittedFields as $field_name) {
$field = $entity
->get($field_name);
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 (empty($changed_fields)) {
return new ModifiedResourceResponse($original_entity, 200);
}
$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 new ModifiedResourceResponse($original_entity, 200);
} catch (EntityStorageException $e) {
throw new HttpException(500, 'Internal Server Error', $e);
}
}
protected function checkPatchFieldAccess(FieldItemListInterface $original_field, FieldItemListInterface $received_field) {
if ($original_field
->access('view') && $original_field
->equals($received_field)) {
return FALSE;
}
$field_edit_access = $original_field
->access('edit', NULL, TRUE);
if ($field_edit_access
->isAllowed()) {
return TRUE;
}
$field_name = $received_field
->getName();
$error_message = "Access denied on updating field '{$field_name}'.";
if ($field_edit_access instanceof AccessResultReasonInterface) {
$reason = $field_edit_access
->getReason();
if ($reason) {
$error_message .= ' ' . $reason;
}
}
throw new AccessDeniedHttpException($error_message);
}
public function delete(EntityInterface $entity) {
try {
$entity
->delete();
$this->logger
->notice('Deleted entity %type with ID %id.', [
'%type' => $entity
->getEntityTypeId(),
'%id' => $entity
->id(),
]);
return new ModifiedResourceResponse(NULL, 204);
} catch (EntityStorageException $e) {
throw new HttpException(500, 'Internal Server Error', $e);
}
}
protected function generateFallbackAccessDeniedMessage(EntityInterface $entity, $operation) {
$message = "You are not authorized to {$operation} this {$entity->getEntityTypeId()} entity";
if ($entity
->bundle() !== $entity
->getEntityTypeId()) {
$message .= " of bundle {$entity->bundle()}";
}
return "{$message}.";
}
public function permissions() {
return [];
}
protected function getBaseRoute($canonical_path, $method) {
$route = parent::getBaseRoute($canonical_path, $method);
switch ($method) {
case 'GET':
$route
->setRequirement('_entity_access', $this->entityType
->id() . '.view');
break;
case 'POST':
$route
->setRequirement('_entity_create_any_access', $this->entityType
->id());
$route
->setOption('_ignore_create_bundle_access', TRUE);
break;
case 'PATCH':
$route
->setRequirement('_entity_access', $this->entityType
->id() . '.update');
break;
case 'DELETE':
$route
->setRequirement('_entity_access', $this->entityType
->id() . '.delete');
break;
}
$definition = $this
->getPluginDefinition();
$parameters = $route
->getOption('parameters') ?: [];
$parameters[$definition['entity_type']]['type'] = 'entity:' . $definition['entity_type'];
$route
->setOption('parameters', $parameters);
return $route;
}
public function availableMethods() {
$methods = parent::availableMethods();
if ($this
->isConfigEntityResource()) {
$unsupported_methods = [
'POST',
'PUT',
'DELETE',
'PATCH',
];
$methods = array_diff($methods, $unsupported_methods);
}
return $methods;
}
protected function isConfigEntityResource() {
return $this->entityType instanceof ConfigEntityType;
}
public function calculateDependencies() {
if (isset($this->entityType)) {
return [
'module' => [
$this->entityType
->getProvider(),
],
];
}
}
protected function addLinkHeaders(EntityInterface $entity, Response $response) {
foreach ($entity
->uriRelationships() as $relation_name) {
if ($this->linkRelationTypeManager
->hasDefinition($relation_name)) {
$link_relation_type = $this->linkRelationTypeManager
->createInstance($relation_name);
$generator_url = $entity
->toUrl($relation_name)
->setAbsolute(TRUE)
->toString(TRUE);
if ($response instanceof CacheableResponseInterface) {
$response
->addCacheableDependency($generator_url);
}
$uri = $generator_url
->getGeneratedUrl();
$relationship = $link_relation_type
->isRegistered() ? $link_relation_type
->getRegisteredName() : $link_relation_type
->getExtensionUri();
$link_header = '<' . $uri . '>; rel="' . $relationship . '"';
$response->headers
->set('Link', $link_header, FALSE);
}
}
}
}