SetSerializedTypeEventSubscriber   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
c 1
b 0
f 0
lcom 0
cbo 1
dl 0
loc 35
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getSubscribedEvents() 0 9 1
A onPreSerialize() 0 19 3
1
<?php
2
3
/*
4
 * This file is part of the xAPI package.
5
 *
6
 * (c) Christian Flothmann <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Xabbuh\XApi\Serializer\Event;
13
14
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
15
use JMS\Serializer\EventDispatcher\PreSerializeEvent;
16
17
/**
18
 * Event listener that sets the proper class name for polymorphic objects
19
 * before they are serialized.
20
 *
21
 * @author Christian Flothmann <[email protected]>
22
 */
23
class SetSerializedTypeEventSubscriber implements EventSubscriberInterface
24
{
25
    /**
26
     * {@inheritDoc}
27
     */
28
    public static function getSubscribedEvents()
29
    {
30
        return array(
31
            array(
32
                'event' => 'serializer.pre_serialize',
33
                'method' => 'onPreSerialize',
34
            ),
35
        );
36
    }
37
38
    public function onPreSerialize(PreSerializeEvent $event)
39
    {
40
        /** @var object $object */
41
        $object = $event->getObject();
42
43
        if (!is_object($object)) {
44
            return;
45
        }
46
47
        $type = $event->getType();
48
        $polymorphicTypes = array(
49
            'Xabbuh\XApi\Model\Actor',
50
            'Xabbuh\XApi\Model\Object',
51
        );
52
53
        if (in_array($type['name'], $polymorphicTypes)) {
54
            $event->setType(get_class($object));
55
        }
56
    }
57
}
58