getSubscribedEvents()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 1
eloc 5
nc 1
nop 0
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