Failed Conditions
Pull Request — new-parser-ast-metadata (#3)
by
unknown
06:33 queued 04:54
created

ValueValidator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 83.33%

Importance

Changes 0
Metric Value
wmc 6
eloc 16
dl 0
loc 42
ccs 15
cts 18
cp 0.8333
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 12 2
A determinePropertyConstraint() 0 17 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Annotations\Assembler\Validator;
6
7
use Doctrine\Annotations\Assembler\Validator\Constraint\CompositeConstraint;
8
use Doctrine\Annotations\Assembler\Validator\Constraint\Constraint;
9
use Doctrine\Annotations\Assembler\Validator\Constraint\EnumConstraint;
10
use Doctrine\Annotations\Assembler\Validator\Constraint\Exception\ConstraintNotFulfilled;
11
use Doctrine\Annotations\Assembler\Validator\Constraint\RequiredConstraint;
12
use Doctrine\Annotations\Assembler\Validator\Constraint\TypeConstraint;
13
use Doctrine\Annotations\Assembler\Validator\Exception\InvalidPropertyValue;
14
use Doctrine\Annotations\Metadata\PropertyMetadata;
15
use Doctrine\Annotations\Metadata\Type\Type;
16
use function count;
17
18
final class ValueValidator
19
{
20
    /**
21
     * @param mixed $value
22
     *
23
     * @throws InvalidPropertyValue
24
     */
25 6
    public function validate(PropertyMetadata $metadata, $value) : void
26
    {
27 6
        $constraint = $this->determinePropertyConstraint(
28 6
            $metadata->type(),
29 6
            $metadata->isRequired(),
30 6
            $metadata->enumValues()
31
        );
32
33
        try {
34 6
            $constraint->validate($value);
35 1
        } catch (ConstraintNotFulfilled $exception) {
36 1
            throw InvalidPropertyValue::new($metadata, $exception);
37
        }
38 5
    }
39
40
    /**
41
     * @param mixed[] $enumValues
42
     */
43 6
    private function determinePropertyConstraint(Type $type, bool $required, array $enumValues) : Constraint
44
    {
45 6
        $constraints = [new TypeConstraint($type)];
46
47 6
        if ($required) {
48
            $constraints[] = new RequiredConstraint();
49
        }
50
51 6
        if (count($enumValues) > 0) {
52
            $constraints[] = new EnumConstraint($enumValues);
53
        }
54
55 6
        if (count($constraints) === 1) {
56 6
            return $constraints[0];
57
        }
58
59
        return new CompositeConstraint(...$constraints);
60
    }
61
}
62