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

EnumValidator::validate()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 4

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 24
ccs 15
cts 15
cp 1
rs 8.6845
cc 4
eloc 13
nc 4
nop 2
crap 4
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