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
|
|
|
} |
23
|
|
|
|
24
|
|
|
private function resolveAllowsNull(ReflectionProperty $property): bool |
25
|
|
|
{ |
26
|
|
|
if (! $property->getType()) { |
27
|
|
|
return true; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
return $property->getType()->allowsNull(); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
private function resolveIsMixed(ReflectionProperty $property): bool |
34
|
|
|
{ |
35
|
|
|
return $property->hasType() === false; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
private function resolveIsMixedArray(ReflectionProperty $property): bool |
39
|
|
|
{ |
40
|
|
|
$reflectionType = $property->getType(); |
41
|
|
|
|
42
|
|
|
if (! $reflectionType instanceof ReflectionNamedType) { |
|
|
|
|
43
|
|
|
return false; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
// We cast to array to support future union types in PHP 8 |
47
|
|
|
$types = [$reflectionType]; |
48
|
|
|
|
49
|
|
|
foreach ($types as $type) { |
50
|
|
|
if (in_array($type->getName(), ['iterable', 'array'])) { |
51
|
|
|
return true; |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return false; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
private function resolveAllowedTypes(ReflectionProperty $property): array |
59
|
|
|
{ |
60
|
|
|
// We cast to array to support future union types in PHP 8 |
61
|
|
|
$types = [$property->getType()]; |
62
|
|
|
|
63
|
|
|
return $this->normaliseTypes(...$types); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
private function normaliseTypes(?ReflectionType ...$types): array |
67
|
|
|
{ |
68
|
|
|
return array_filter(array_map( |
69
|
|
|
function (?ReflectionType $type) { |
70
|
|
|
if ($type instanceof ReflectionNamedType) { |
|
|
|
|
71
|
|
|
return $type->getName(); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return self::$typeMapping[$type] ?? $type; |
75
|
|
|
}, |
76
|
|
|
$types |
77
|
|
|
)); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|