PrimitiveValidator   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 42
ccs 18
cts 18
cp 1
rs 10
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A validate() 0 24 4
A support() 0 3 2
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 SchemaValidator\Argument;
14
use SchemaValidator\Context;
15
use Symfony\Component\Validator\Constraints\Type as ConstraintType;
16
use Symfony\Component\Validator\Util\PropertyPath;
17
use Symfony\Component\Validator\Validator\ValidatorInterface as SymfonyValidator;
18
19
final class PrimitiveValidator implements ValidatorInterface
20
{
21
    private const SUPPORT_CAST_TYPE = [
22
        'int'    => ['int', 'string', 'float'],
23
        'string' => ['string', 'int', 'float'],
24
        'float'  => ['float', 'int', 'string'],
25
    ];
26
27 15
    public function __construct(
28
        private SymfonyValidator $validator,
29
    ) {
30 15
    }
31
32 3
    public function support(\ReflectionType $type): bool
33
    {
34 3
        return $type instanceof \ReflectionNamedType && $type->isBuiltin();
35
    }
36
37 12
    public function validate(Argument $argument, Context $context): void
38
    {
39 12
        $type = $argument->getType();
40
41 12
        if (!$type instanceof \ReflectionNamedType) {
42 1
            throw new \InvalidArgumentException('Type expected:' . \ReflectionNamedType::class);
43
        }
44
45
        /** @var string|int|float|array $value */
46 11
        $value    = $argument->getValueByArgumentName();
47 11
        $typeName = $type->getName();
48 11
        $types    = [$typeName];
49
50 11
        if (!$context->isStrictTypes() && array_key_exists($typeName, self::SUPPORT_CAST_TYPE)) {
51 1
            $types = self::SUPPORT_CAST_TYPE[$typeName];
52
        }
53
54 11
        $constraint = new ConstraintType([
55 11
            'type' => $types,
56
        ]);
57
58 11
        $this->validator->inContext($context->getExecution())
59 11
            ->atPath(PropertyPath::append($context->getRootPath(), $argument->getName()))
60 11
            ->validate($value, [$constraint])
61
        ;
62 11
    }
63
}
64