1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Er1z\FakeMock\Decorator; |
4
|
|
|
|
5
|
|
|
use Er1z\FakeMock\Metadata\FieldMetadata; |
6
|
|
|
use phpDocumentor\Reflection\Types\Boolean; |
7
|
|
|
use phpDocumentor\Reflection\Types\String_; |
8
|
|
|
|
9
|
|
|
class PhpDocDecorator implements DecoratorInterface |
10
|
|
|
{ |
11
|
|
|
const CASTABLE_TYPES = [ |
12
|
|
|
'string', 'int', 'integer', 'float', 'double', 'boolean', 'bool', |
13
|
|
|
]; |
14
|
|
|
|
15
|
38 |
|
public function decorate(&$value, FieldMetadata $field, ?string $group = null): bool |
16
|
|
|
{ |
17
|
38 |
|
if (!$field->type) { |
18
|
19 |
|
return true; |
19
|
|
|
} |
20
|
|
|
|
21
|
22 |
|
$desiredType = (string) $field->type; |
22
|
|
|
|
23
|
22 |
|
if (in_array($desiredType, self::CASTABLE_TYPES) && gettype($value) != $desiredType) { |
24
|
3 |
|
$value = $this->convertTypes($field, $value, $desiredType); |
25
|
|
|
} |
26
|
|
|
|
27
|
22 |
|
return true; |
28
|
|
|
} |
29
|
|
|
|
30
|
3 |
|
protected function convertTypes(FieldMetadata $field, $value, $desiredType) |
31
|
|
|
{ |
32
|
|
|
switch (true) { |
33
|
3 |
|
case $field->type instanceof Boolean: |
34
|
|
|
return $this->castStringToBool($value); |
35
|
|
|
|
36
|
3 |
|
case $field->type instanceof String_: |
37
|
|
|
if ($value instanceof \DateTimeInterface) { |
38
|
|
|
return $this->castDateTime($value); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
if (is_bool($value)) { |
42
|
|
|
return $this->castBoolToString($value); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
return (string) $value; |
46
|
|
|
default: |
47
|
3 |
|
settype($value, $desiredType); |
48
|
|
|
} |
49
|
|
|
|
50
|
3 |
|
return $value; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
protected function castDateTime(\DateTimeInterface $dateTime) |
54
|
|
|
{ |
55
|
|
|
return $dateTime->format(DATE_ATOM); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
protected function castBoolToString($value) |
59
|
|
|
{ |
60
|
|
|
return $value ? 'true' : 'false'; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
protected function castStringToBool($value) |
64
|
|
|
{ |
65
|
|
|
$value = strtolower($value); |
66
|
|
|
|
67
|
|
|
switch ($value) { |
68
|
|
|
case 'false': |
69
|
|
|
case '0': |
70
|
|
|
default: |
71
|
|
|
return false; |
72
|
|
|
|
73
|
|
|
case 'true': |
74
|
|
|
case '1': |
75
|
|
|
return true; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|