1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Uvinum\Joiner\Serializer; |
4
|
|
|
|
5
|
|
|
use Uvinum\Joiner\Strategy\Strategy; |
6
|
|
|
|
7
|
|
|
final class ArraySerializer implements Serializer |
8
|
|
|
{ |
9
|
|
|
private $strategies; |
10
|
|
|
|
11
|
33 |
|
public function __construct(Strategy $strategy = null) |
12
|
|
|
{ |
13
|
33 |
|
$this->strategies = $strategy; |
14
|
33 |
|
} |
15
|
|
|
|
16
|
33 |
|
public function serialize($arg) |
17
|
|
|
{ |
18
|
33 |
|
$serializedArguments = \array_reduce( |
19
|
33 |
|
[$arg], |
20
|
33 |
|
[$this, "serializeItem"], |
21
|
33 |
|
[] |
22
|
11 |
|
); |
23
|
|
|
|
24
|
33 |
|
return $serializedArguments; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
|
28
|
33 |
|
private function serializeItem($carry, $arg) |
29
|
|
|
{ |
30
|
33 |
|
if ($this->isIterable($arg)) { |
31
|
24 |
|
$serializedArray = \array_reduce( |
32
|
8 |
|
\array_keys($arg), |
33
|
|
|
function ($carry, $key) use ($arg) { |
34
|
24 |
|
if ($this->isIterable($arg[$key])) { |
35
|
|
|
$carry[$key] = \array_reduce( |
36
|
|
|
$arg[$key], |
37
|
|
|
[$this, "serializeItem"], |
38
|
|
|
[] |
39
|
|
|
); |
40
|
|
|
|
41
|
|
|
return $carry; |
42
|
|
|
} |
43
|
24 |
|
if (!\is_object($arg[$key])) { |
44
|
24 |
|
$carry[$key] = $arg[$key]; |
45
|
|
|
|
46
|
24 |
|
return $carry; |
47
|
|
|
} |
48
|
|
|
|
49
|
3 |
|
$carry[$key] = $this->serializeObject($arg[$key]); |
50
|
|
|
|
51
|
3 |
|
return $carry; |
52
|
24 |
|
}, |
53
|
24 |
|
[] |
54
|
8 |
|
); |
55
|
|
|
|
56
|
24 |
|
return $serializedArray; |
57
|
|
|
} |
58
|
|
|
|
59
|
27 |
|
if (!\is_object($arg)) { |
60
|
24 |
|
return $arg; |
61
|
|
|
} |
62
|
|
|
|
63
|
24 |
|
if (null !== $this->strategies) { |
64
|
24 |
|
$serializedObjectDueToStrategy = $this->strategies->execute($arg); |
65
|
24 |
|
if (null !== $serializedObjectDueToStrategy) { |
66
|
3 |
|
return $serializedObjectDueToStrategy; |
67
|
|
|
} |
68
|
8 |
|
} |
69
|
|
|
|
70
|
24 |
|
return $this->serializeObject($arg); |
71
|
|
|
} |
72
|
|
|
|
73
|
27 |
|
private function serializeObject($arg) |
74
|
|
|
{ |
75
|
27 |
|
$reflectionClass = new \ReflectionClass(\get_class($arg)); |
76
|
27 |
|
$serializedObject = \array_reduce( |
77
|
27 |
|
$reflectionClass->getProperties(), |
78
|
27 |
|
function ($carry, $property) use ($arg) { |
79
|
|
|
/** @var \ReflectionProperty $property */ |
80
|
27 |
|
$property->setAccessible(true); |
81
|
27 |
|
$carry[$property->getName()] = \array_reduce( |
82
|
27 |
|
[$property->getValue($arg)], |
83
|
27 |
|
[$this, "serializeItem"], |
84
|
27 |
|
[] |
85
|
9 |
|
); |
86
|
|
|
|
87
|
27 |
|
return $carry; |
88
|
27 |
|
}, |
89
|
27 |
|
[] |
90
|
9 |
|
); |
91
|
|
|
|
92
|
27 |
|
return $serializedObject; |
93
|
|
|
} |
94
|
|
|
|
95
|
33 |
|
private function isIterable($arg) |
96
|
|
|
{ |
97
|
33 |
|
return \is_array($arg) || $arg instanceof \Traversable; |
98
|
|
|
} |
99
|
|
|
} |
100
|
|
|
|