comparison core/modules/jsonapi/src/Entity/EntityValidationTrait.php @ 5:12f9dff5fda9 tip

Update to Drupal core 8.7.1
author Chris Cannam
date Thu, 09 May 2019 15:34:47 +0100
parents
children
comparison
equal deleted inserted replaced
4:a9cd425dd02b 5:12f9dff5fda9
1 <?php
2
3 namespace Drupal\jsonapi\Entity;
4
5 use Drupal\Core\Entity\EntityInterface;
6 use Drupal\Core\Entity\FieldableEntityInterface;
7 use Drupal\jsonapi\Exception\UnprocessableHttpEntityException;
8
9 /**
10 * Provides a method to validate an entity.
11 *
12 * @internal JSON:API maintains no PHP API. The API is the HTTP API. This class
13 * may change at any time and could break any dependencies on it.
14 *
15 * @see https://www.drupal.org/project/jsonapi/issues/3032787
16 * @see jsonapi.api.php
17 */
18 trait EntityValidationTrait {
19
20 /**
21 * Verifies that an entity does not violate any validation constraints.
22 *
23 * @param \Drupal\Core\Entity\EntityInterface $entity
24 * The entity object.
25 * @param string[] $field_names
26 * (optional) An array of field names. If specified, filters the violations
27 * list to include only this set of fields. Defaults to NULL,
28 * which means that all violations will be reported.
29 *
30 * @throws \Drupal\jsonapi\Exception\UnprocessableHttpEntityException
31 * Thrown when violations remain after filtering.
32 *
33 * @see \Drupal\rest\Plugin\rest\resource\EntityResourceValidationTrait::validate()
34 */
35 protected static function validate(EntityInterface $entity, array $field_names = NULL) {
36 if (!$entity instanceof FieldableEntityInterface) {
37 return;
38 }
39
40 $violations = $entity->validate();
41
42 // Remove violations of inaccessible fields as they cannot stem from our
43 // changes.
44 $violations->filterByFieldAccess();
45
46 // Filter violations based on the given fields.
47 if ($field_names !== NULL) {
48 $violations->filterByFields(
49 array_diff(array_keys($entity->getFieldDefinitions()), $field_names)
50 );
51 }
52
53 if (count($violations) > 0) {
54 // Instead of returning a generic 400 response we use the more specific
55 // 422 Unprocessable Entity code from RFC 4918. That way clients can
56 // distinguish between general syntax errors in bad serializations (code
57 // 400) and semantic errors in well-formed requests (code 422).
58 // @see \Drupal\jsonapi\Normalizer\UnprocessableHttpEntityExceptionNormalizer
59 $exception = new UnprocessableHttpEntityException();
60 $exception->setViolations($violations);
61 throw $exception;
62 }
63 }
64
65 }