Completed
Push — master ( d5349d...2edaf3 )
by Yann
9s
created

EnumValidator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 6
dl 0
loc 43
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B validate() 0 24 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 8
    public function __construct(EnumRegistryInterface $enumRegistry)
25
    {
26 8
        $this->enumRegistry = $enumRegistry;
27 8
    }
28
29
    /**
30
     * @inheritdoc
31
     */
32 8
    public function validate($value, Constraint $constraint)
33
    {
34 8
        if (!$constraint instanceof Enum) {
35 1
            throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Enum');
36
        }
37
38 7
        $constraint->choices  = null;
39 7
        $constraint->callback = null;
40
41 7
        if (!$constraint->enum) {
42 1
            throw new ConstraintDefinitionException('"enum" must be specified on constraint Enum');
43
        }
44
45 6
        if (!$this->enumRegistry->has($constraint->enum)) {
46 1
            throw new ConstraintDefinitionException(sprintf(
47 1
                '"enum" "%s" on constraint Enum does not exist',
48 1
                $constraint->enum
49 1
            ));
50
        }
51
52 5
        $constraint->choices = array_keys($this->enumRegistry->get($constraint->enum)->getChoices());
53
54 5
        parent::validate($value, $constraint);
55 5
    }
56
}
57