You are here

protected function EntityResource::validate in JSON:API 8

Verifies that the whole entity does not violate any validation constraints.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity object.

string[] $field_names: (optional) An array of field names. If specified, filters the violations list to include only this set of fields. Defaults to NULL, which means that all violations will be reported.

Throws

\Drupal\jsonapi\Exception\EntityAccessDeniedHttpException If validation errors are found.

See also

\Drupal\rest\Plugin\rest\resource\EntityResourceValidationTrait::validate()

5 calls to EntityResource::validate()
EntityResource::createIndividual in src/Controller/EntityResource.php
Creates an individual entity.
EntityResource::createRelationship in src/Controller/EntityResource.php
Adds a relationship to a to-many relationship.
EntityResource::deleteRelationship in src/Controller/EntityResource.php
Deletes the relationship of an entity.
EntityResource::patchIndividual in src/Controller/EntityResource.php
Patches an individual entity.
EntityResource::patchRelationship in src/Controller/EntityResource.php
Updates the relationship of an entity.

File

src/Controller/EntityResource.php, line 164

Class

EntityResource
Process all entity requests.

Namespace

Drupal\jsonapi\Controller

Code

protected function validate(EntityInterface $entity, array $field_names = NULL) {
  if (!$entity instanceof FieldableEntityInterface) {
    return;
  }
  $violations = $entity
    ->validate();

  // Remove violations of inaccessible fields as they cannot stem from our
  // changes.
  $violations
    ->filterByFieldAccess();

  // Filter violations based on the given fields.
  if ($field_names !== NULL) {
    $violations
      ->filterByFields(array_diff(array_keys($entity
      ->getFieldDefinitions()), $field_names));
  }
  if (count($violations) > 0) {

    // 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).
    // @see \Drupal\jsonapi\Normalizer\UnprocessableHttpEntityExceptionNormalizer
    $exception = new UnprocessableHttpEntityException();
    $exception
      ->setViolations($violations);
    throw $exception;
  }
}