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 = []; |
32
|
8 |
|
foreach ($arg as $key => $value) { |
33
|
|
|
$serializedArray[$key] = $this->serializeItem($carry, $value); |
34
|
24 |
|
} |
35
|
|
|
|
36
|
|
|
return $serializedArray; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
if (!\is_object($arg)) { |
40
|
|
|
return $arg; |
41
|
|
|
} |
42
|
|
|
|
43
|
24 |
|
if (null !== $this->strategies) { |
44
|
24 |
|
$serializedObjectDueToStrategy = $this->strategies->execute($arg); |
45
|
|
|
if (null !== $serializedObjectDueToStrategy) { |
46
|
24 |
|
return $serializedObjectDueToStrategy; |
47
|
|
|
} |
48
|
|
|
} |
49
|
3 |
|
|
50
|
|
|
return $this->serializeObject($arg); |
51
|
3 |
|
} |
52
|
24 |
|
|
53
|
24 |
|
private function serializeObject($arg) |
54
|
8 |
|
{ |
55
|
|
|
$reflectionClass = new \ReflectionClass(\get_class($arg)); |
56
|
24 |
|
$serializedObject = \array_reduce( |
57
|
|
|
$reflectionClass->getProperties(), |
58
|
|
|
function ($carry, $property) use ($arg) { |
59
|
27 |
|
/** @var \ReflectionProperty $property */ |
60
|
24 |
|
$property->setAccessible(true); |
61
|
|
|
$carry[$property->getName()] = \array_reduce( |
62
|
|
|
[$property->getValue($arg)], |
63
|
24 |
|
[$this, "serializeItem"], |
64
|
24 |
|
[] |
65
|
24 |
|
); |
66
|
3 |
|
|
67
|
|
|
return $carry; |
68
|
8 |
|
}, |
69
|
|
|
[] |
70
|
24 |
|
); |
71
|
|
|
|
72
|
|
|
return $serializedObject; |
73
|
27 |
|
} |
74
|
|
|
|
75
|
27 |
|
private function isIterable($arg) |
76
|
27 |
|
{ |
77
|
27 |
|
return \is_array($arg) || $arg instanceof \Traversable; |
78
|
27 |
|
} |
79
|
|
|
} |
80
|
|
|
|