You are here

public function EntityResource::post 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::post()

Responds to entity POST requests and saves the new entity.

Parameters

\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 75
Contains \Drupal\rest\Plugin\rest\resource\EntityResource.

Class

EntityResource
Represents entities as resources.

Namespace

Drupal\rest\Plugin\rest\resource

Code

public function post(EntityInterface $entity = NULL) {
  if ($entity == NULL) {
    throw new BadRequestHttpException('No entity content received.');
  }
  if (!$entity
    ->access('create')) {
    throw new AccessDeniedHttpException();
  }
  $definition = $this
    ->getPluginDefinition();

  // Verify that the deserialized entity is of the type that we expect to
  // prevent security issues.
  if ($entity
    ->getEntityTypeId() != $definition['entity_type']) {
    throw new BadRequestHttpException('Invalid entity type');
  }

  // POSTed entities must not have an ID set, because we always want to create
  // new entities here.
  if (!$entity
    ->isNew()) {
    throw new BadRequestHttpException('Only new entities can be created');
  }

  // Only check 'edit' permissions for fields that were actually
  // submitted by the user. Field access makes no difference between 'create'
  // and 'update', so the 'edit' operation is used here.
  foreach ($entity->_restSubmittedFields as $key => $field_name) {
    if (!$entity
      ->get($field_name)
      ->access('edit')) {
      throw new AccessDeniedHttpException("Access denied on creating field '{$field_name}'");
    }
  }

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

    // 201 Created responses have an empty body.
    $url = $entity
      ->urlInfo('canonical', [
      'absolute' => TRUE,
    ])
      ->toString(TRUE);
    $response = new ResourceResponse(NULL, 201, [
      'Location' => $url
        ->getGeneratedUrl(),
    ]);
    $response
      ->addCacheableDependency($url);
    return $response;
  } catch (EntityStorageException $e) {
    throw new HttpException(500, 'Internal Server Error', $e);
  }
}