JMS Serializer event is not working

2.7k views Asked by At

I am sure it is a small error but I cannot find it. I am trying to follow the official doc and implement an event listener on the pre_serialize event.

My service declaration:

 <service id="app.question_serializer_subscriber" class="AppBundle\Serializer\QuestionSerializerSubscriber">
     <tag name="jms_serializer.event_subscriber"/>
 </service>

My subscriber:

<?php

namespace AppBundle\Serializer;

use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
use JMS\Serializer\EventDispatcher\ObjectEvent;

class QuestionSerializerSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            array(
                'event'  => 'serializer.pre_serialize',
                'method' => 'onPreSerialize',
            )
        );
    }

    public function onPreSerialize(ObjectEvent $event)
    {
        die('in event');
    }
}

And my controller:

        $question   = $repo->findLastVersionByQuestionId((int) $questionId);
        $serializer = SerializerBuilder::create()->build();

        $context = new SerializationContext();
        return new JsonResponse(json_decode(
            $serializer->serialize(
                $question,
                'json',
                $context
            ),
            true
        ));

When I access the route my entity Question is serialized and displayed, but why does the die('in event'); is not displayed ?

Maybe it has a relation with the fact that my object is a Doctrine entity (issue 666 or PR 677 )

2

There are 2 answers

0
iBadGamer On BEST ANSWER

I finally find the issue. The problem is

$serializer = SerializerBuilder::create()->build();

This does not work but this does:

$serializer =  $this->get('jms_serializer');
7
Matteo On

Try adding the class attribute, as example:

public static function getSubscribedEvents()
{
    return array(
        array(
            'event'  => 'serializer.pre_serialize',
            'class'  => 'FQCN_class_name',
            'method' => 'onPreSerialize',
        )
    );
}

Another difference regarding the doc is in the argument of the class method: you should use PreSerializeEvent instead of ObjectEvent:

So like this:

public function onPreSerialize(PreSerializeEvent $event)
{
    // ...
}

Check your service is correctly load from the container as example with the console command:

php app/console debug:container --tag=jms_serializer.event_subscriber

Hope this help