Search code examples
symfonyjmsserializerbundlejms-serializer

JMSSerializer events do not work for concrete types


I am trying to create an EventSubscriber for different serialization events using Symfony 3.4.21, JMSSerializer 2.1.0 and JMSSerializerBundle 3.0.0.

Problem is, that the subscribers only work if they are not registered for a concrete type. Why is this?

My setup:

// src/AppBundle\EventListener\SerializationEventSubscriber.php
use JMS\Serializer\EventDispatcher\Events;
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
use JMS\Serializer\EventDispatcher\PreSerializeEvent;
use JMS\Serializer\EventDispatcher\ObjectEvent;

class SerializationEventSubscriber implements EventSubscriberInterface {
    public static function getSubscribedEvents() {        
        return array(       
            // Subscribe with NO specific class       
            array('event' => Events::PRE_SERIALIZE, 'method' => 'onPreSerialize_NoClass'),
            array('event' => Events::POST_DESERIALIZE, 'method' => 'onPostDeserialize_NoClass'),


            // Subscribe WITH specific class       
            array('event' => Events::PRE_SERIALIZE, 'method' => 'onPreSerialize_Class', 'class' => 'AppBundle\Entity\MyEntity'),
            array('event' => Events::POST_DESERIALIZE, 'method' => 'onPostDeserialize_Class', 'class' => 'AppBundle\Entity\MyEntity'),
        );
    }

    public function onPreSerialize_NoClass(PreSerializeEvent $event) {
        // log...
    }

    public function onPostDeserialize_NoClass(PreSerializeEvent $event) {
        // log...
    }

    public function onPreSerialize_Class(PreSerializeEvent $event) {
        // log...
    }

    public function onPreSerialize_Class(PreSerializeEvent $event) {
        // log...
    }
}


// app/config/services.yml
AppBundle\EventListener\SerializationEventSubscriber:
    tags:
        - { name: "jms_serializer.event_subscriber" }  

While first two handlers (defined with no specific class) are correctly called, the two handlers with a specific class are not called.

If I check the class of the event object in the ..._NoClass handlers, it perfectly matches the type used in the ..._Class handlers.

According to the docs it should be no problem to define a handler for a specific class. What is wrong with my config?


Solution

  • It seems that this was a bug in JMSSerializerBundle 3.0.0. An Update to 3.1.0 solved the issue.