Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
0.00% |
0 / 27 |
|
0.00% |
0 / 3 |
CRAP | |
0.00% |
0 / 1 |
UniqueReferenceConstraintValidator | |
0.00% |
0 / 27 |
|
0.00% |
0 / 3 |
30 | |
0.00% |
0 / 1 |
__construct | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
create | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
2 | |||
validate | |
0.00% |
0 / 23 |
|
0.00% |
0 / 1 |
12 |
1 | <?php |
2 | |
3 | namespace Drupal\crm\Plugin\Validation\Constraint; |
4 | |
5 | use Drupal\Core\DependencyInjection\ContainerInjectionInterface; |
6 | use Drupal\Core\Entity\EntityTypeManagerInterface; |
7 | use Symfony\Component\DependencyInjection\ContainerInterface; |
8 | use Symfony\Component\Validator\Constraint; |
9 | use Symfony\Component\Validator\ConstraintValidator; |
10 | |
11 | /** |
12 | * Validates that a field is unique for the given entity type. |
13 | */ |
14 | class UniqueReferenceConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface { |
15 | |
16 | /** |
17 | * The entity type manager. |
18 | * |
19 | * @var \Drupal\Core\Entity\EntityTypeManagerInterface |
20 | */ |
21 | protected $entityTypeManager; |
22 | |
23 | /** |
24 | * Creates a new TaxonomyTermHierarchyConstraintValidator instance. |
25 | * |
26 | * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager |
27 | * The entity type manager. |
28 | */ |
29 | public function __construct(EntityTypeManagerInterface $entity_type_manager) { |
30 | $this->entityTypeManager = $entity_type_manager; |
31 | } |
32 | |
33 | /** |
34 | * {@inheritdoc} |
35 | */ |
36 | public static function create(ContainerInterface $container) { |
37 | return new static( |
38 | $container->get('entity_type.manager') |
39 | ); |
40 | } |
41 | |
42 | /** |
43 | * {@inheritdoc} |
44 | */ |
45 | public function validate($items, Constraint $constraint) { |
46 | if (!$item = $items->first()) { |
47 | return; |
48 | } |
49 | $field_name = $items->getFieldDefinition()->getName(); |
50 | /** @var \Drupal\Core\Entity\EntityInterface $entity */ |
51 | $entity = $items->getEntity(); |
52 | $entity_type_id = $entity->getEntityTypeId(); |
53 | $id_key = $entity->getEntityType()->getKey('id'); |
54 | $id = (int) $items->getEntity()->id(); |
55 | $target_id = $item->target_id; |
56 | |
57 | $value_taken = (bool) $this->entityTypeManager->getStorage($entity_type_id) |
58 | ->getQuery() |
59 | // The id could be NULL, so we cast it to 0 in that case. |
60 | ->condition($id_key, $id, '<>') |
61 | ->condition($field_name, $target_id) |
62 | ->accessCheck(FALSE) |
63 | ->range(0, 1) |
64 | ->count() |
65 | ->execute(); |
66 | |
67 | if ($value_taken) { |
68 | $this->context->addViolation($constraint->message, [ |
69 | '@id' => $target_id, |
70 | '@entity_type' => $entity->getEntityType()->getSingularLabel(), |
71 | '@field_name' => mb_strtolower($items->getFieldDefinition()->getLabel()), |
72 | ]); |
73 | } |
74 | } |
75 | |
76 | } |