DoctrineProxySubscriber.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. <?php
  2. namespace JMS\SerializerBundle\Serializer\EventDispatcher\Subscriber;
  3. use Doctrine\ORM\PersistentCollection;
  4. use Doctrine\Common\Persistence\Proxy;
  5. use Doctrine\ORM\Proxy\Proxy as ORMProxy;
  6. use JMS\SerializerBundle\Serializer\EventDispatcher\PreSerializeEvent;
  7. use JMS\SerializerBundle\Serializer\EventDispatcher\EventSubscriberInterface;
  8. class DoctrineProxySubscriber implements EventSubscriberInterface
  9. {
  10. public function onPreSerialize(PreSerializeEvent $event)
  11. {
  12. $object = $event->getObject();
  13. if ($object instanceof PersistentCollection) {
  14. $event->setType('ArrayCollection');
  15. return;
  16. }
  17. if ( ! $object instanceof Proxy && ! $object instanceof ORMProxy) {
  18. return;
  19. }
  20. $object->__load();
  21. $event->setType(get_parent_class($object));
  22. }
  23. public static function getSubscribedEvents()
  24. {
  25. return array(
  26. array('event' => 'serializer.pre_serialize', 'method' => 'onPreSerialize'),
  27. );
  28. }
  29. }