Completed
Push — master ( 722a7f...28a19f )
by Albert
14:35
created

ArraySerializer   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 86.05%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 11
c 2
b 0
f 0
lcom 1
cbo 1
dl 0
loc 73
ccs 37
cts 43
cp 0.8605
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A serialize() 0 10 1
B serializeItem() 0 24 6
A serializeObject() 0 21 1
A isIterable() 0 4 2
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