MyCLabsEnumValidator   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 39
ccs 20
cts 20
cp 1
rs 10
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 19 2
A __construct() 0 3 1
A support() 0 11 5
1
<?php
2
/**
3
 * Schema Validator
4
 *
5
 * @author    Vlad Shashkov <[email protected]>
6
 * @copyright Copyright (c) 2021, The Myaza Software
7
 */
8
9
declare(strict_types=1);
10
11
namespace SchemaValidator\Validator;
12
13
use MyCLabs\Enum\Enum;
14
use SchemaValidator\Argument;
15
use SchemaValidator\Context;
16
use Symfony\Component\Validator\Constraints\Choice;
17
use Symfony\Component\Validator\Util\PropertyPath;
18
use Symfony\Component\Validator\Validator\ValidatorInterface as SymfonyValidator;
19
20
final class MyCLabsEnumValidator implements ValidatorInterface
21
{
22 9
    public function __construct(
23
        private SymfonyValidator $validator,
24
    ) {
25 9
    }
26
27 3
    public function support(\ReflectionType $type): bool
28
    {
29 3
        if (!$type instanceof \ReflectionNamedType || $type->isBuiltin()) {
30 1
            return false;
31
        }
32
33 2
        if (!class_exists(Enum::class) || !is_subclass_of($type->getName(), Enum::class)) {
34 1
            return false;
35
        }
36
37 1
        return true;
38
    }
39
40 6
    public function validate(Argument $argument, Context $context): void
41
    {
42 6
        $type = $argument->getType();
43
44 6
        if (!$type instanceof \ReflectionNamedType) {
45 1
            throw new \InvalidArgumentException('Type expected:' . \ReflectionNamedType::class);
46
        }
47
48
        /** @var string $value */
49 5
        $value = $argument->getValueByArgumentName();
50
        /** @var class-string<Enum> $enum */
51 5
        $enum      = $type->getName();
52 5
        $execution = $context->getExecution();
53
54 5
        $this->validator->inContext($execution)
55 5
            ->atPath(PropertyPath::append($context->getRootPath(), $argument->getName()))
56 5
            ->validate($value, [
57 5
                new Choice([
58 5
                    'choices' => forward_static_call_array([$enum, 'toArray'], []),
59
                ]),
60
            ])
61
        ;
62 5
    }
63
}
64