You are here

protected static function EntityValidationTrait::validate in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/jsonapi/src/Entity/EntityValidationTrait.php \Drupal\jsonapi\Entity\EntityValidationTrait::validate()
  2. 9 core/modules/jsonapi/src/Entity/EntityValidationTrait.php \Drupal\jsonapi\Entity\EntityValidationTrait::validate()

Verifies that an 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\UnprocessableHttpEntityException Thrown when violations remain after filtering.

See also

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

File

core/modules/jsonapi/src/Entity/EntityValidationTrait.php, line 35

Class

EntityValidationTrait
Provides a method to validate an entity.

Namespace

Drupal\jsonapi\Entity

Code

protected static 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;
  }
}