EnumValidator::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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