EntityResource.php 11.3 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\rest\Plugin\rest\resource;

5
use Drupal\Component\Plugin\DependentPluginInterface;
6 7 8
use Drupal\Core\Config\Entity\ConfigEntityType;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
9
use Drupal\Core\Config\ConfigFactoryInterface;
10
use Drupal\Core\Entity\EntityInterface;
11 12
use Drupal\Core\Entity\EntityStorageException;
use Drupal\rest\Plugin\ResourceBase;
13
use Drupal\rest\ResourceResponse;
14 15
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
16
use Drupal\rest\ModifiedResourceResponse;
17
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
18
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
19 20 21 22 23
use Symfony\Component\HttpKernel\Exception\HttpException;

/**
 * Represents entities as resources.
 *
24 25
 * @see \Drupal\rest\Plugin\Deriver\EntityDeriver
 *
26
 * @RestResource(
27 28
 *   id = "entity",
 *   label = @Translation("Entity"),
29
 *   serialization_class = "Drupal\Core\Entity\Entity",
30
 *   deriver = "Drupal\rest\Plugin\Deriver\EntityDeriver",
31 32
 *   uri_paths = {
 *     "canonical" = "/entity/{entity_type}/{entity}",
33
 *     "https://www.drupal.org/link-relations/create" = "/entity/{entity_type}"
34
 *   }
35 36
 * )
 */
37
class EntityResource extends ResourceBase implements DependentPluginInterface {
38

39 40 41
  use EntityResourceValidationTrait;
  use EntityResourceAccessTrait;

42
  /**
43
   * The entity type targeted by this resource.
44
   *
45
   * @var \Drupal\Core\Entity\EntityTypeInterface
46
   */
47
  protected $entityType;
48

49 50 51 52 53 54 55
  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

56 57 58 59 60 61 62 63 64
  /**
   * Constructs a Drupal\rest\Plugin\rest\resource\EntityResource object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
65 66
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager
67 68 69 70
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
71
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
72
   *   The config factory.
73
   */
74
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, $serializer_formats, LoggerInterface $logger, ConfigFactoryInterface $config_factory) {
75
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
76
    $this->entityType = $entity_type_manager->getDefinition($plugin_definition['entity_type']);
77
    $this->configFactory = $config_factory;
78 79 80 81 82 83 84 85 86 87
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
88
      $container->get('entity_type.manager'),
89
      $container->getParameter('serializer.formats'),
90 91
      $container->get('logger.factory')->get('rest'),
      $container->get('config.factory')
92 93 94
    );
  }

95 96 97
  /**
   * Responds to entity GET requests.
   *
98 99
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
100
   *
101
   * @return \Drupal\rest\ResourceResponse
102
   *   The response containing the entity with its accessible fields.
103 104 105
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   */
106
  public function get(EntityInterface $entity) {
107 108
    $entity_access = $entity->access('view', NULL, TRUE);
    if (!$entity_access->isAllowed()) {
109 110
      throw new AccessDeniedHttpException();
    }
111 112 113 114 115

    $response = new ResourceResponse($entity, 200);
    $response->addCacheableDependency($entity);
    $response->addCacheableDependency($entity_access);

116 117 118 119 120 121 122 123 124
    if ($entity instanceof FieldableEntityInterface) {
      foreach ($entity as $field_name => $field) {
        /** @var \Drupal\Core\Field\FieldItemListInterface $field */
        $field_access = $field->access('view', NULL, TRUE);
        $response->addCacheableDependency($field_access);

        if (!$field_access->isAllowed()) {
          $entity->set($field_name, NULL);
        }
125
      }
126
    }
127

128
    return $response;
129 130
  }

131 132 133 134 135 136
  /**
   * Responds to entity POST requests and saves the new entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity.
   *
137
   * @return \Drupal\rest\ModifiedResourceResponse
138 139 140 141
   *   The HTTP response object.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   */
142
  public function post(EntityInterface $entity = NULL) {
143
    if ($entity == NULL) {
144
      throw new BadRequestHttpException('No entity content received.');
145 146
    }

147 148 149
    if (!$entity->access('create')) {
      throw new AccessDeniedHttpException();
    }
150
    $definition = $this->getPluginDefinition();
151 152
    // Verify that the deserialized entity is of the type that we expect to
    // prevent security issues.
153
    if ($entity->getEntityTypeId() != $definition['entity_type']) {
154
      throw new BadRequestHttpException('Invalid entity type');
155 156 157 158
    }
    // POSTed entities must not have an ID set, because we always want to create
    // new entities here.
    if (!$entity->isNew()) {
159
      throw new BadRequestHttpException('Only new entities can be created');
160
    }
161

162
    $this->checkEditFieldAccess($entity);
163 164 165

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

170
      // 201 Created responses return the newly created entity in the response
171 172
      // body. These responses are not cacheable, so we add no cacheability
      // metadata here.
173
      $url = $entity->urlInfo('canonical', ['absolute' => TRUE])->toString(TRUE);
174
      return new ModifiedResourceResponse($entity, 201, ['Location' => $url->getGeneratedUrl()]);
175 176
    }
    catch (EntityStorageException $e) {
177
      throw new HttpException(500, 'Internal Server Error', $e);
178 179 180
    }
  }

181 182 183
  /**
   * Responds to entity PATCH requests.
   *
184 185
   * @param \Drupal\Core\Entity\EntityInterface $original_entity
   *   The original entity object.
186 187 188
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity.
   *
189
   * @return \Drupal\rest\ModifiedResourceResponse
190 191 192 193
   *   The HTTP response object.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   */
194
  public function patch(EntityInterface $original_entity, EntityInterface $entity = NULL) {
195
    if ($entity == NULL) {
196
      throw new BadRequestHttpException('No entity content received.');
197
    }
198
    $definition = $this->getPluginDefinition();
199
    if ($entity->getEntityTypeId() != $definition['entity_type']) {
200
      throw new BadRequestHttpException('Invalid entity type');
201
    }
202 203 204 205
    if (!$original_entity->access('update')) {
      throw new AccessDeniedHttpException();
    }

206
    // Overwrite the received properties.
207
    $entity_keys = $entity->getEntityType()->getKeys();
208
    foreach ($entity->_restSubmittedFields as $field_name) {
209
      $field = $entity->get($field_name);
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

      // Entity key fields need special treatment: together they uniquely
      // identify the entity. Therefore it does not make sense to modify any of
      // them. However, rather than throwing an error, we just ignore them as
      // long as their specified values match their current values.
      if (in_array($field_name, $entity_keys, TRUE)) {
        // Unchanged values for entity keys don't need access checking.
        if ($original_entity->get($field_name)->getValue() === $entity->get($field_name)->getValue()) {
          continue;
        }
        // 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.
        elseif (isset($entity_keys['langcode']) && $field_name === $entity_keys['langcode'] && $field->isEmpty()) {
          continue;
        }
225
      }
226 227

      if (!$original_entity->get($field_name)->access('edit')) {
228
        throw new AccessDeniedHttpException("Access denied on updating field '$field_name'.");
229
      }
230
      $original_entity->set($field_name, $field->getValue());
231
    }
232 233 234

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

239 240
      // Return the updated entity in the response body.
      return new ModifiedResourceResponse($original_entity, 200);
241 242
    }
    catch (EntityStorageException $e) {
243
      throw new HttpException(500, 'Internal Server Error', $e);
244 245 246
    }
  }

247 248 249
  /**
   * Responds to entity DELETE requests.
   *
250 251
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
252
   *
253
   * @return \Drupal\rest\ModifiedResourceResponse
254
   *   The HTTP response object.
255 256 257
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   */
258 259 260 261 262 263
  public function delete(EntityInterface $entity) {
    if (!$entity->access('delete')) {
      throw new AccessDeniedHttpException();
    }
    try {
      $entity->delete();
264
      $this->logger->notice('Deleted entity %type with ID %id.', array('%type' => $entity->getEntityTypeId(), '%id' => $entity->id()));
265

266
      // Delete responses have an empty body.
267
      return new ModifiedResourceResponse(NULL, 204);
268 269
    }
    catch (EntityStorageException $e) {
270
      throw new HttpException(500, 'Internal Server Error', $e);
271 272
    }
  }
273

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
  /**
   * {@inheritdoc}
   */
  public function permissions() {
    // @see https://www.drupal.org/node/2664780
    if ($this->configFactory->get('rest.settings')->get('bc_entity_resource_permissions')) {
      // The default Drupal 8.0.x and 8.1.x behavior.
      return parent::permissions();
    }
    else {
      // The default Drupal 8.2.x behavior.
      return [];
    }
  }

289 290 291 292 293 294 295 296 297 298 299 300 301 302
  /**
   * {@inheritdoc}
   */
  protected function getBaseRoute($canonical_path, $method) {
    $route = parent::getBaseRoute($canonical_path, $method);
    $definition = $this->getPluginDefinition();

    $parameters = $route->getOption('parameters') ?: array();
    $parameters[$definition['entity_type']]['type'] = 'entity:' . $definition['entity_type'];
    $route->setOption('parameters', $parameters);

    return $route;
  }

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
  /**
   * {@inheritdoc}
   */
  public function availableMethods() {
    $methods = parent::availableMethods();
    if ($this->isConfigEntityResource()) {
      // Currently only GET is supported for Config Entities.
      // @todo Remove when supported https://www.drupal.org/node/2300677
      $unsupported_methods = ['POST', 'PUT', 'DELETE', 'PATCH'];
      $methods = array_diff($methods, $unsupported_methods);
    }
    return $methods;
  }

  /**
   * Checks if this resource is for a Config Entity.
   *
   * @return bool
   *   TRUE if the entity is a Config Entity, FALSE otherwise.
   */
  protected function isConfigEntityResource() {
324 325 326 327 328 329 330 331 332 333
    return $this->entityType instanceof ConfigEntityType;
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    if (isset($this->entityType)) {
      return ['module' => [$this->entityType->getProvider()]];
    }
334 335
  }

336
}