1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Spatie\DataTransferObject; |
6
|
|
|
|
7
|
|
|
use ReflectionNamedType; |
8
|
|
|
use ReflectionProperty; |
9
|
|
|
use ReflectionType; |
10
|
|
|
|
11
|
|
|
class PropertyFieldValidator extends FieldValidator |
12
|
|
|
{ |
13
|
|
|
public function __construct(ReflectionProperty $property) |
14
|
|
|
{ |
15
|
|
|
$this->hasTypeDeclaration = $property->hasType(); |
16
|
|
|
$this->hasDefaultValue = $property->isDefault(); |
17
|
|
|
$this->isNullable = $this->resolveAllowsNull($property); |
18
|
|
|
$this->isMixed = $this->resolveIsMixed($property); |
19
|
|
|
$this->isMixedArray = $this->resolveIsMixedArray($property); |
20
|
|
|
$this->allowedTypes = $this->resolveAllowedTypes($property); |
21
|
|
|
$this->allowedArrayTypes = []; |
22
|
|
|
$this->allowedArrayKeyTypes = []; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
private function resolveAllowsNull(ReflectionProperty $property): bool |
26
|
|
|
{ |
27
|
|
|
if (! $property->getType()) { |
28
|
|
|
return true; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
return $property->getType()->allowsNull(); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
private function resolveIsMixed(ReflectionProperty $property): bool |
35
|
|
|
{ |
36
|
|
|
return $property->hasType() === false; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
private function resolveIsMixedArray(ReflectionProperty $property): bool |
40
|
|
|
{ |
41
|
|
|
$reflectionType = $property->getType(); |
42
|
|
|
|
43
|
|
|
if (! $reflectionType instanceof ReflectionNamedType) { |
|
|
|
|
44
|
|
|
return false; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
// We cast to array to support future union types in PHP 8 |
48
|
|
|
$types = [$reflectionType]; |
49
|
|
|
|
50
|
|
|
foreach ($types as $type) { |
51
|
|
|
if (in_array($type->getName(), ['iterable', 'array'])) { |
52
|
|
|
return true; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return false; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
private function resolveAllowedTypes(ReflectionProperty $property): array |
60
|
|
|
{ |
61
|
|
|
// We cast to array to support future union types in PHP 8 |
62
|
|
|
$types = [$property->getType()]; |
63
|
|
|
|
64
|
|
|
return $this->normaliseTypes(...$types); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
private function normaliseTypes(?ReflectionType ...$types): array |
68
|
|
|
{ |
69
|
|
|
return array_filter(array_map( |
70
|
|
|
function (?ReflectionType $type) { |
71
|
|
|
if ($type instanceof ReflectionNamedType) { |
|
|
|
|
72
|
|
|
$type = $type->getName(); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return self::$typeMapping[$type] ?? $type; |
76
|
|
|
}, |
77
|
|
|
$types |
78
|
|
|
)); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|