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