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
|
|
|
|