-
Notifications
You must be signed in to change notification settings - Fork 1
/
UniqueConstraint.php
95 lines (77 loc) · 2.61 KB
/
UniqueConstraint.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
declare(strict_types=1);
namespace Chubbyphp\Validation\Constraint\Doctrine;
use Chubbyphp\Validation\Accessor\PropertyAccessor;
use Chubbyphp\Validation\Constraint\ConstraintInterface;
use Chubbyphp\Validation\Error\Error;
use Chubbyphp\Validation\Error\ErrorInterface;
use Chubbyphp\Validation\ValidatorContextInterface;
use Chubbyphp\Validation\ValidatorInterface;
use Doctrine\Persistence\ObjectManager;
final class UniqueConstraint implements ConstraintInterface
{
/**
* @param array<int, string> $uniqueProperties
*/
public function __construct(private ObjectManager $objectManager, private array $uniqueProperties)
{
}
/**
* @param mixed $model
*
* @return array<ErrorInterface>
*/
public function validate(
string $path,
$model,
ValidatorContextInterface $context,
?ValidatorInterface $validator = null
) {
if (null === $model) {
return [];
}
$criteria = $this->getCriteria($model);
/** @var class-string $modelClass */
$modelClass = $model::class;
if (null === $persistedModel = $this->objectManager->getRepository($modelClass)->findOneBy($criteria)) {
return [];
}
$metadata = $this->objectManager->getClassMetadata($modelClass);
if ($this->isValueSameAsPersistedValue($metadata->getIdentifier(), $model, $persistedModel)) {
return [];
}
$errors = [];
foreach ($this->uniqueProperties as $uniqueProperty) {
$errors[] = new Error(
'' !== $path ? $path.'.'.$uniqueProperty : $uniqueProperty,
'constraint.unique.notunique',
['uniqueProperties' => implode(', ', $this->uniqueProperties)]
);
}
return $errors;
}
/**
* @return array<string, mixed>
*/
private function getCriteria(object $model): array
{
$criteria = [];
foreach ($this->uniqueProperties as $uniqueProperty) {
$criteria[$uniqueProperty] = (new PropertyAccessor($uniqueProperty))->getValue($model);
}
return $criteria;
}
/**
* @param array<int, string> $identifierParts
*/
private function isValueSameAsPersistedValue(array $identifierParts, object $model, object $persistedModel): bool
{
foreach ($identifierParts as $identifierPart) {
$accessor = new PropertyAccessor($identifierPart);
if ($accessor->getValue($model) !== $accessor->getValue($persistedModel)) {
return false;
}
}
return true;
}
}