JMS Serializer Event Subscriber Filters Out Proxy Classes

178 Views Asked by At

I have an entity Acme\Bundle\Entity\Author which has a one to many relationship to Acme\Bundle\Entity\Article and I have two JMS serializer event subscribers for both entities.

Subscriber for Acme\Bundle\Entity\Author;

acm.author_serialization_listener:
    class: Acm\Bundle\Listener\AuthorSerializationListener
    tags:
        - { name: jms_serializer.event_subscriber }

class AuthorSerializationListener implements EventSubscriberInterface
    {
        /**
         * @inheritdoc
         */
        public static function getSubscribedEvents()
        {
            return array(
                array('event' => 'serializer.pre_serialize', 'class' => 'Acme\Bundle\Entity\Author' 'method' => 'onPreSerialize'),
            );
        }

    public function onPreSerialize(PreSerializeEvent $event)
    {
        if($event->getObject() instanceof Author) {
            return;
        }
    }
}

Subscriber for Acme\Bundle\Entity\Article;

acm.article_serialization_listener:
    class: Acm\Bundle\Listener\ArticleSerializationListener
    tags:
        - { name: jms_serializer.event_subscriber }

class ArticleSerializationListener implements EventSubscriberInterface
    {
        /**
         * @inheritdoc
         */
        public static function getSubscribedEvents()
        {
            return array(
                array('event' => 'serializer.pre_serialize', 'class' => 'Acme\Bundle\Entity\Article' 'method' => 'onPreSerialize'),
            );
        }

        public function onPreSerialize(PreSerializeEvent $event)
        {
            if($event->getObject() instanceof Article) {
                return;
            }
        }
    }

The problem occurs in the onPreSerialize function when serializing Author along with related Article s in the ArticleSerializationListener subscriber class where it injects Proxies\__CG__\Acme\Bundle\Entity\Article instead of Acme\Bundle\Entity\Article entities which lead to exclude the related Article entities. Is there something I am doing wrong or is there a workaround for this?

1

There are 1 best solutions below

2
On

Instead of get_class you should simply use the operator instanceof because the proxies inherit from the entities. You compare two strings.

if($event->getObject() instanceof \Acme\Bundle\Entity\Article) {
    return;
}

Sidenode: Also the operator !=== does not exist.