Security update for Core, with self-updated composer
[yaffs-website] / web / core / lib / Drupal / Core / Entity / Plugin / Validation / Constraint / ValidReferenceConstraintValidator.php
1 <?php
2
3 namespace Drupal\Core\Entity\Plugin\Validation\Constraint;
4
5 use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
6 use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface;
7 use Drupal\Core\Entity\EntityReferenceSelection\SelectionWithAutocreateInterface;
8 use Drupal\Core\Entity\EntityTypeManagerInterface;
9 use Symfony\Component\DependencyInjection\ContainerInterface;
10 use Symfony\Component\Validator\Constraint;
11 use Symfony\Component\Validator\ConstraintValidator;
12
13 /**
14  * Checks if referenced entities are valid.
15  */
16 class ValidReferenceConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
17
18   /**
19    * The selection plugin manager.
20    *
21    * @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface
22    */
23   protected $selectionManager;
24
25   /**
26    * The entity type manager.
27    *
28    * @var \Drupal\Core\Entity\EntityTypeManagerInterface
29    */
30   protected $entityTypeManager;
31
32   /**
33    * Constructs a ValidReferenceConstraintValidator object.
34    *
35    * @param \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface $selection_manager
36    *   The selection plugin manager.
37    * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
38    *   The entity type manager.
39    */
40   public function __construct(SelectionPluginManagerInterface $selection_manager, EntityTypeManagerInterface $entity_type_manager) {
41     $this->selectionManager = $selection_manager;
42     $this->entityTypeManager = $entity_type_manager;
43   }
44
45   /**
46    * {@inheritdoc}
47    */
48   public static function create(ContainerInterface $container) {
49     return new static(
50       $container->get('plugin.manager.entity_reference_selection'),
51       $container->get('entity_type.manager')
52     );
53   }
54
55   /**
56    * {@inheritdoc}
57    */
58   public function validate($value, Constraint $constraint) {
59     /** @var \Drupal\Core\Field\FieldItemListInterface $value */
60     /** @var ValidReferenceConstraint $constraint */
61     if (!isset($value)) {
62       return;
63     }
64
65     // Collect new entities and IDs of existing entities across the field items.
66     $new_entities = [];
67     $target_ids = [];
68     foreach ($value as $delta => $item) {
69       $target_id = $item->target_id;
70       // We don't use a regular NotNull constraint for the target_id property as
71       // NULL is allowed if the entity property contains an unsaved entity.
72       // @see \Drupal\Core\TypedData\DataReferenceTargetDefinition::getConstraints()
73       if (!$item->isEmpty() && $target_id === NULL) {
74         if (!$item->entity->isNew()) {
75           $this->context->buildViolation($constraint->nullMessage)
76             ->atPath((string) $delta)
77             ->addViolation();
78           return;
79         }
80         $new_entities[$delta] = $item->entity;
81       }
82
83       // '0' or NULL are considered valid empty references.
84       if (!empty($target_id)) {
85         $target_ids[$delta] = $target_id;
86       }
87     }
88
89     // Early opt-out if nothing to validate.
90     if (!$new_entities && !$target_ids) {
91       return;
92     }
93
94     $entity = !empty($value->getParent()) ? $value->getEntity() : NULL;
95
96     /** @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface $handler * */
97     $handler = $this->selectionManager->getSelectionHandler($value->getFieldDefinition(), $entity);
98     $target_type_id = $value->getFieldDefinition()->getSetting('target_type');
99
100     // Add violations on deltas with a new entity that is not valid.
101     if ($new_entities) {
102       if ($handler instanceof SelectionWithAutocreateInterface) {
103         $valid_new_entities = $handler->validateReferenceableNewEntities($new_entities);
104         $invalid_new_entities = array_diff_key($new_entities, $valid_new_entities);
105       }
106       else {
107         // If the selection handler does not support referencing newly created
108         // entities, all of them should be invalidated.
109         $invalid_new_entities = $new_entities;
110       }
111
112       foreach ($invalid_new_entities as $delta => $entity) {
113         $this->context->buildViolation($constraint->invalidAutocreateMessage)
114           ->setParameter('%type', $target_type_id)
115           ->setParameter('%label', $entity->label())
116           ->atPath((string) $delta . '.entity')
117           ->setInvalidValue($entity)
118           ->addViolation();
119       }
120     }
121
122     // Add violations on deltas with a target_id that is not valid.
123     if ($target_ids) {
124       // Get a list of pre-existing references.
125       $previously_referenced_ids = [];
126       if ($value->getParent() && ($entity = $value->getEntity()) && !$entity->isNew()) {
127         $existing_entity = $this->entityTypeManager->getStorage($entity->getEntityTypeId())->loadUnchanged($entity->id());
128         foreach ($existing_entity->{$value->getFieldDefinition()->getName()}->getValue() as $item) {
129           $previously_referenced_ids[$item['target_id']] = $item['target_id'];
130         }
131       }
132
133       $valid_target_ids = $handler->validateReferenceableEntities($target_ids);
134       if ($invalid_target_ids = array_diff($target_ids, $valid_target_ids)) {
135         // For accuracy of the error message, differentiate non-referenceable
136         // and non-existent entities.
137         $existing_entities = $this->entityTypeManager->getStorage($target_type_id)->loadMultiple($invalid_target_ids);
138         foreach ($invalid_target_ids as $delta => $target_id) {
139           // Check if any of the invalid existing references are simply not
140           // accessible by the user, in which case they need to be excluded from
141           // validation
142           if (isset($previously_referenced_ids[$target_id]) && isset($existing_entities[$target_id]) && !$existing_entities[$target_id]->access('view')) {
143             continue;
144           }
145
146           $message = isset($existing_entities[$target_id]) ? $constraint->message : $constraint->nonExistingMessage;
147           $this->context->buildViolation($message)
148             ->setParameter('%type', $target_type_id)
149             ->setParameter('%id', $target_id)
150             ->atPath((string) $delta . '.target_id')
151             ->setInvalidValue($target_id)
152             ->addViolation();
153         }
154       }
155     }
156   }
157
158 }