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

ArraySerializer   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 11
c 3
b 0
f 0
lcom 1
cbo 1
dl 0
loc 62
ccs 34
cts 34
cp 1
rs 10

5 Methods

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