Completed
Push — master ( 28a19f...70d918 )
by Albert
04:58
created

ArraySerializer::serialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
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