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

ValueValidator::determinePropertyConstraint()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4.5923

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 17
ccs 6
cts 9
cp 0.6667
rs 10
c 0
b 0
f 0
cc 4
nc 8
nop 3
crap 4.5923
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