ObjectToArrayConverter::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Clearcode\SimpleBusElkBundle\Converter;
4
5
use JMS\Serializer\SerializationContext;
6
use JMS\Serializer\Serializer;
7
8
class ObjectToArrayConverter implements ObjectToArrayConverterInterface
9
{
10
    /** @var Serializer */
11
    private $serializer;
12
13
    public function __construct(Serializer $serializer)
14
    {
15
        $this->serializer = $serializer;
16
    }
17
18
    /**
19
     * {@inheritdoc}
20
     */
21
    public function toArray($object)
22
    {
23
        $this->guardAgainstNotObject($object);
24
25
        return $this->convert($object);
26
    }
27
28
    private function convert($object)
29
    {
30
        return [
31
            'event' => [
32
                'name' => $this->getClassName($object),
33
                'data' => $this->serializer->toArray($object, SerializationContext::create()->setSerializeNull(true)),
34
            ],
35
        ];
36
    }
37
38
    private function getClassName($object)
39
    {
40
        $class = new \ReflectionClass(get_class($object));
41
42
        return $class->getShortName();
43
    }
44
45
    private function guardAgainstNotObject($event)
46
    {
47
        if (!is_object($event)) {
48
            throw new DataToConvertIsNotAnObject();
49
        }
50
    }
51
}
52