EnumValidator::validate()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 2
1
<?php
2
/*
3
 * This file is part of the FreshDoctrineEnumBundle.
4
 *
5
 * (c) Artem Henvald <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
declare(strict_types=1);
12
13
namespace Fresh\DoctrineEnumBundle\Validator\Constraints;
14
15
use Fresh\DoctrineEnumBundle\Exception\RuntimeException;
16
use Symfony\Component\Validator\Constraint;
17
use Symfony\Component\Validator\Constraints\ChoiceValidator;
18
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
19
20
/**
21
 * EnumValidator validates that the value is one of the expected ENUM values.
22
 *
23
 * @author Artem Henvald <[email protected]>
24
 */
25
class EnumValidator extends ChoiceValidator
26
{
27
    /**
28
     * @param mixed           $value
29
     * @param Constraint|Enum $constraint
30
     *
31
     * @throws RuntimeException
32
     * @throws ConstraintDefinitionException
33
     */
34
    public function validate($value, Constraint $constraint): void
35
    {
36
        if (!$constraint instanceof Enum) {
37
            throw new RuntimeException(\sprintf('Object of class %s is not instance of %s', \get_class($constraint), Enum::class));
38
        }
39
40
        if (!$constraint->entity) {
41
            throw new ConstraintDefinitionException('Entity not specified.');
42
        }
43
44
        $constraint->choices = $constraint->entity::getValues();
45
46
        parent::validate($value, $constraint);
47
    }
48
}
49