You are here

public function EntityResource::post in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/rest/src/Plugin/rest/resource/EntityResource.php \Drupal\rest\Plugin\rest\resource\EntityResource::post()
  2. 9 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\ModifiedResourceResponse The HTTP response object.

Throws

\Symfony\Component\HttpKernel\Exception\HttpException

File

core/modules/rest/src/Plugin/rest/resource/EntityResource.php, line 160

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.');
  }
  $entity_access = $entity
    ->access('create', NULL, TRUE);
  if (!$entity_access
    ->isAllowed()) {
    throw new AccessDeniedHttpException($entity_access
      ->getReason() ?: $this
      ->generateFallbackAccessDeniedMessage($entity, 'create'));
  }
  $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');
  }
  $this
    ->checkEditFieldAccess($entity);

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

    // 201 Created responses return the newly created entity in the response
    // body. These responses are not cacheable, so we add no cacheability
    // metadata here.
    $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);
  }
}