Pull merge.
[yaffs-website] / web / core / lib / Drupal / Core / Validation / Plugin / Validation / Constraint / UniqueFieldValueValidator.php
1 <?php
2
3 namespace Drupal\Core\Validation\Plugin\Validation\Constraint;
4
5 use Symfony\Component\Validator\Constraint;
6 use Symfony\Component\Validator\ConstraintValidator;
7
8 /**
9  * Validates that a field is unique for the given entity type.
10  */
11 class UniqueFieldValueValidator extends ConstraintValidator {
12
13   /**
14    * {@inheritdoc}
15    */
16   public function validate($items, Constraint $constraint) {
17     if (!$item = $items->first()) {
18       return;
19     }
20     $field_name = $items->getFieldDefinition()->getName();
21     /** @var \Drupal\Core\Entity\EntityInterface $entity */
22     $entity = $items->getEntity();
23     $entity_type_id = $entity->getEntityTypeId();
24     $id_key = $entity->getEntityType()->getKey('id');
25
26     $value_taken = (bool) \Drupal::entityQuery($entity_type_id)
27       // The id could be NULL, so we cast it to 0 in that case.
28       ->condition($id_key, (int) $items->getEntity()->id(), '<>')
29       ->condition($field_name, $item->value)
30       ->range(0, 1)
31       ->count()
32       ->execute();
33
34     if ($value_taken) {
35       $this->context->addViolation($constraint->message, [
36         '%value' => $item->value,
37         '@entity_type' => $entity->getEntityType()->getLowercaseLabel(),
38         '@field_name' => mb_strtolower($items->getFieldDefinition()->getLabel()),
39       ]);
40     }
41   }
42
43 }