Completed
Push — sensio-insight-fixes ( 787c3e )
by Yann
07:09
created

EnumValidator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Yokai\EnumBundle\Validator\Constraints;
4
5
use Symfony\Component\Validator\Constraint;
6
use Symfony\Component\Validator\Constraints\ChoiceValidator;
7
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
8
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
9
use Yokai\EnumBundle\Registry\EnumRegistryInterface;
10
11
/**
12
 * @author Yann Eugoné <[email protected]>
13
 */
14
class EnumValidator extends ChoiceValidator
15
{
16
    /**
17
     * @var EnumRegistryInterface
18
     */
19
    private $enumRegistry;
20
21
    /**
22
     * @param EnumRegistryInterface $enumRegistry
23
     */
24
    public function __construct(EnumRegistryInterface $enumRegistry)
25
    {
26
        $this->enumRegistry = $enumRegistry;
27
    }
28
29
    /**
30
     * @inheritdoc
31
     */
32
    public function validate($value, Constraint $constraint)
33
    {
34
        if (!$constraint instanceof Enum) {
35
            throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Enum');
36
        }
37
38
        $constraint->choices  = null;
39
        $constraint->callback = null;
40
41
        if (!$constraint->enum) {
42
            throw new ConstraintDefinitionException('"enum" must be specified on constraint Enum');
43
        }
44
45
        if (!$this->enumRegistry->has($constraint->enum)) {
46
            throw new ConstraintDefinitionException(sprintf(
47
                '"enum" "%s" on constraint Enum does not exist',
48
                $constraint->enum
49
            ));
50
        }
51
52
        $constraint->choices = array_keys($this->enumRegistry->get($constraint->enum)->getChoices());
53
54
        parent::validate($value, $constraint);
55
    }
56
}
57