-
Notifications
You must be signed in to change notification settings - Fork 0
/
UniqueValidator.php
68 lines (56 loc) · 2.11 KB
/
UniqueValidator.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
<?php
namespace Vanio\DomainBundle\Validator;
use Doctrine\Common\Persistence\ManagerRegistry;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class UniqueValidator extends ConstraintValidator
{
/** @var ManagerRegistry */
private $registry;
public function __construct(ManagerRegistry $registry)
{
$this->registry = $registry;
}
/**
* @param mixed $object
* @param Constraint $constraint
*/
public function validate($object, Constraint $constraint)
{
if (!$constraint instanceof Unique) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\Unique');
}
$fields = $constraint->fields;
if (!is_array($fields)) {
$fields = [ $fields ];
}
$accessor = PropertyAccess::createPropertyAccessor();
$criteria = [];
foreach ($fields as $objectField => $entityField) {
$criteria[$entityField] = $accessor->getValue(
$object,
is_numeric($objectField) ? $entityField : $objectField
);
}
$em = $this->registry->getManagerForClass($constraint->class);
if (!$em) {
throw new ConstraintDefinitionException(sprintf('Unable to find the object manager associated with an entity of class "%s".', $constraint->class));
}
$repository = $em->getRepository($constraint->class);
$result = $repository->findBy($criteria);
if (count($result) === 0) {
return;
}
$id = $constraint->id;
if (!is_null($id) && count($result) === 1 &&
$em->getReference($constraint->class, $accessor->getValue($object, $id)) === current($result)) {
return;
}
$this->context->buildViolation($constraint->message)
->setCode(Unique::NOT_UNIQUE_ERROR)
->addViolation();
}
}