ArrayCollectionHandler.php 1.9 KB

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