ArrayCollectionHandler.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace JMS\SerializerBundle\Serializer\Handler;
  3. use Doctrine\Common\Collections\ArrayCollection;
  4. use JMS\SerializerBundle\Serializer\GraphNavigator;
  5. use JMS\SerializerBundle\Serializer\VisitorInterface;
  6. use Doctrine\Common\Collections\Collection;
  7. use JMS\SerializerBundle\Serializer\Handler\SubscribingHandlerInterface;
  8. class ArrayCollectionHandler implements SubscribingHandlerInterface
  9. {
  10. public static function getSubscribingMethods()
  11. {
  12. $methods = array();
  13. $formats = array('json', 'xml', 'yml');
  14. $collectionTypes = array('ArrayCollection', 'Doctrine\Common\Collections\ArrayCollection', 'Doctrine\ORM\PersistentCollection', 'Doctrine\ODM\MongoDB\PersistentCollection');
  15. foreach ($collectionTypes as $type) {
  16. foreach ($formats as $format) {
  17. $methods[] = array(
  18. 'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
  19. 'type' => $type,
  20. 'format' => $format,
  21. 'method' => 'serializeCollection',
  22. );
  23. $methods[] = array(
  24. 'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
  25. 'type' => $type,
  26. 'format' => $format,
  27. 'method' => 'deserializeCollection',
  28. );
  29. }
  30. }
  31. return $methods;
  32. }
  33. public function serializeCollection(VisitorInterface $visitor, Collection $collection, array $type)
  34. {
  35. // We change the base type, and pass through possible parameters.
  36. $type['name'] = 'array';
  37. return $visitor->visitArray($collection->toArray(), $type);
  38. }
  39. public function deserializeCollection(VisitorInterface $visitor, $data, array $type)
  40. {
  41. // See above.
  42. $type['name'] = 'array';
  43. return new ArrayCollection($visitor->visitArray($data, $type));
  44. }
  45. }