EntityResource.php 7.98 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Definition of Drupal\rest\Plugin\rest\resource\EntityResource.
 */

namespace Drupal\rest\Plugin\rest\resource;

10
use Drupal\Core\Entity\EntityInterface;
11 12
use Drupal\Core\Entity\EntityStorageException;
use Drupal\rest\Plugin\ResourceBase;
13
use Drupal\rest\ResourceResponse;
14
use Drupal\Component\Utility\String;
15
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
16
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
17 18 19 20 21
use Symfony\Component\HttpKernel\Exception\HttpException;

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

37 38 39
  /**
   * Responds to entity GET requests.
   *
40 41
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
42 43
   *
   * @return \Drupal\rest\ResourceResponse
44
   *   The response containing the entity with its accessible fields.
45 46 47
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   */
48 49 50 51 52 53 54
  public function get(EntityInterface $entity) {
    if (!$entity->access('view')) {
      throw new AccessDeniedHttpException();
    }
    foreach ($entity as $field_name => $field) {
      if (!$field->access('view')) {
        unset($entity->{$field_name});
55
      }
56
    }
57
    return new ResourceResponse($entity);
58 59
  }

60 61 62 63 64 65 66 67 68 69 70
  /**
   * Responds to entity POST requests and saves the new entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity.
   *
   * @return \Drupal\rest\ResourceResponse
   *   The HTTP response object.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   */
71
  public function post(EntityInterface $entity = NULL) {
72
    if ($entity == NULL) {
73
      throw new BadRequestHttpException('No entity content received.');
74 75
    }

76 77 78
    if (!$entity->access('create')) {
      throw new AccessDeniedHttpException();
    }
79
    $definition = $this->getPluginDefinition();
80 81
    // Verify that the deserialized entity is of the type that we expect to
    // prevent security issues.
82
    if ($entity->getEntityTypeId() != $definition['entity_type']) {
83
      throw new BadRequestHttpException('Invalid entity type');
84 85 86 87
    }
    // POSTed entities must not have an ID set, because we always want to create
    // new entities here.
    if (!$entity->isNew()) {
88
      throw new BadRequestHttpException('Only new entities can be created');
89
    }
90 91
    foreach ($entity as $field_name => $field) {
      if (!$field->access('create')) {
92
        throw new AccessDeniedHttpException(String::format('Access denied on creating field ', array('@field' => $field_name)));
93 94
      }
    }
95 96 97

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

102
      $url = _url(strtr($this->pluginId, ':', '/') . '/' . $entity->id(), array('absolute' => TRUE));
103 104 105 106
      // 201 Created responses have an empty body.
      return new ResourceResponse(NULL, 201, array('Location' => $url));
    }
    catch (EntityStorageException $e) {
107
      throw new HttpException(500, 'Internal Server Error', $e);
108 109 110
    }
  }

111 112 113
  /**
   * Responds to entity PATCH requests.
   *
114 115
   * @param \Drupal\Core\Entity\EntityInterface $original_entity
   *   The original entity object.
116 117 118 119 120 121 122 123
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity.
   *
   * @return \Drupal\rest\ResourceResponse
   *   The HTTP response object.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   */
124
  public function patch(EntityInterface $original_entity, EntityInterface $entity = NULL) {
125
    if ($entity == NULL) {
126
      throw new BadRequestHttpException('No entity content received.');
127
    }
128
    $definition = $this->getPluginDefinition();
129
    if ($entity->getEntityTypeId() != $definition['entity_type']) {
130
      throw new BadRequestHttpException('Invalid entity type');
131
    }
132 133 134 135
    if (!$original_entity->access('update')) {
      throw new AccessDeniedHttpException();
    }

136
    // Overwrite the received properties.
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    foreach ($entity->_restPatchFields 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: Use the langcode entity key when available. See
      //   https://drupal.org/node/2143729.
      if ($field_name == 'langcode' && $field->isEmpty()) {
        continue;
      }
      if ($field->isEmpty() && !$original_entity->get($field_name)->access('delete')) {
        throw new AccessDeniedHttpException(String::format('Access denied on deleting field @field.', array('@field' => $field_name)));
      }
      $original_entity->set($field_name, $field->getValue());
      if (!$original_entity->get($field_name)->access('update')) {
        throw new AccessDeniedHttpException(String::format('Access denied on updating field @field.', array('@field' => $field_name)));
152 153
      }
    }
154 155 156

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

161 162 163 164
      // Update responses have an empty body.
      return new ResourceResponse(NULL, 204);
    }
    catch (EntityStorageException $e) {
165
      throw new HttpException(500, 'Internal Server Error', $e);
166 167 168
    }
  }

169 170 171
  /**
   * Responds to entity DELETE requests.
   *
172 173
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
174
   *
175 176
   * @return \Drupal\rest\ResourceResponse
   *   The HTTP response object.
177 178 179
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   */
180 181 182 183 184 185
  public function delete(EntityInterface $entity) {
    if (!$entity->access('delete')) {
      throw new AccessDeniedHttpException();
    }
    try {
      $entity->delete();
186
      $this->logger->notice('Deleted entity %type with ID %id.', array('%type' => $entity->getEntityTypeId(), '%id' => $entity->id()));
187

188 189 190 191
      // Delete responses have an empty body.
      return new ResourceResponse(NULL, 204);
    }
    catch (EntityStorageException $e) {
192
      throw new HttpException(500, 'Internal Server Error', $e);
193 194
    }
  }
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218

  /**
   * Verifies that the whole entity does not violate any validation constraints.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   *   If validation errors are found.
   */
  protected function validate(EntityInterface $entity) {
    $violations = $entity->validate();
    if (count($violations) > 0) {
      $message = "Unprocessable Entity: validation failed.\n";
      foreach ($violations as $violation) {
        $message .= $violation->getPropertyPath() . ': ' . $violation->getMessage() . "\n";
      }
      // Instead of returning a generic 400 response we use the more specific
      // 422 Unprocessable Entity code from RFC 4918. That way clients can
      // distinguish between general syntax errors in bad serializations (code
      // 400) and semantic errors in well-formed requests (code 422).
      throw new HttpException(422, $message);
    }
  }
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234

  /**
   * {@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;
  }


235
}