1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\DataTransferObject; |
4
|
|
|
|
5
|
|
|
class ValueCaster |
6
|
|
|
{ |
7
|
|
|
public function cast($value, FieldValidator $validator) |
8
|
|
|
{ |
9
|
|
|
return $this->shouldBeCastToCollection($value) |
10
|
|
|
? $this->castCollection($value, $validator->allowedArrayTypes, $this->collectionType($validator->allowedTypes)) |
11
|
|
|
: $this->castValue($value, $validator->allowedTypes); |
12
|
|
|
} |
13
|
|
|
|
14
|
|
|
public function castValue($value, array $allowedTypes) |
15
|
|
|
{ |
16
|
|
|
$castTo = null; |
17
|
|
|
|
18
|
|
|
foreach ($allowedTypes as $type) { |
19
|
|
|
if (! is_subclass_of($type, DataTransferObject::class)) { |
20
|
|
|
continue; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
$castTo = $type; |
24
|
|
|
|
25
|
|
|
break; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
if (! $castTo) { |
29
|
|
|
return $value; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
return new $castTo($value); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function castCollection($values, array $allowedArrayTypes, string $collectionClass = null) |
36
|
|
|
{ |
37
|
|
|
$castTo = null; |
38
|
|
|
|
39
|
|
|
foreach ($allowedArrayTypes as $type) { |
40
|
|
|
if (! is_subclass_of($type, DataTransferObject::class)) { |
41
|
|
|
continue; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$castTo = $type; |
45
|
|
|
|
46
|
|
|
break; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
if (! $castTo) { |
50
|
|
|
return $collectionClass ? new $collectionClass($values) : $values; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
$casts = []; |
54
|
|
|
|
55
|
|
|
foreach ($values as $value) { |
56
|
|
|
$casts[] = new $castTo($value); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return $collectionClass ? new $collectionClass($casts) : $casts; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
public function collectionType(array $types): string |
63
|
|
|
{ |
64
|
|
|
foreach ($types as $type) { |
65
|
|
|
if (is_subclass_of($type, DataTransferObjectCollection::class)) { |
66
|
|
|
return $type; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return false; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
public function shouldBeCastToCollection(array $values): bool |
74
|
|
|
{ |
75
|
|
|
if (empty($values)) { |
76
|
|
|
return false; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
foreach ($values as $key => $value) { |
80
|
|
|
if (is_string($key)) { |
81
|
|
|
return false; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
if (! is_array($value)) { |
85
|
|
|
return false; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
return true; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|