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 |
|
return $this->serializeItem($arg); |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
|
22
|
33 |
|
private function serializeItem($arg) |
23
|
|
|
{ |
24
|
33 |
|
if ($this->isIterable($arg)) { |
25
|
24 |
|
$serializedArray = []; |
26
|
24 |
|
foreach ($arg as $key => $value) { |
27
|
24 |
|
$serializedArray[$key] = $this->serializeItem($value); |
28
|
16 |
|
} |
29
|
|
|
|
30
|
24 |
|
return $serializedArray; |
31
|
|
|
} |
32
|
|
|
|
33
|
33 |
|
if (!\is_object($arg)) { |
34
|
30 |
|
return $arg; |
35
|
|
|
} |
36
|
|
|
|
37
|
27 |
|
if (null !== $this->strategies) { |
38
|
27 |
|
$serializedObjectDueToStrategy = $this->strategies->execute($arg); |
39
|
27 |
|
if (null !== $serializedObjectDueToStrategy) { |
40
|
3 |
|
return $serializedObjectDueToStrategy; |
41
|
|
|
} |
42
|
18 |
|
} |
43
|
|
|
|
44
|
27 |
|
return $this->serializeObject($arg); |
45
|
|
|
} |
46
|
|
|
|
47
|
27 |
|
private function serializeObject($arg) |
48
|
|
|
{ |
49
|
27 |
|
$reflectionClass = new \ReflectionClass(\get_class($arg)); |
50
|
27 |
|
$serializedObject = \array_reduce( |
51
|
27 |
|
$reflectionClass->getProperties(), |
52
|
27 |
|
function ($carry, $property) use ($arg) { |
53
|
|
|
/** @var \ReflectionProperty $property */ |
54
|
27 |
|
$property->setAccessible(true); |
55
|
27 |
|
$carry[$property->getName()] = $this->serializeItem($property->getValue($arg)); |
56
|
27 |
|
return $carry; |
57
|
27 |
|
}, |
58
|
27 |
|
[] |
59
|
18 |
|
); |
60
|
|
|
|
61
|
27 |
|
return $serializedObject; |
62
|
|
|
} |
63
|
|
|
|
64
|
33 |
|
private function isIterable($arg) |
65
|
|
|
{ |
66
|
33 |
|
return \is_array($arg) || $arg instanceof \Traversable; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|