ArrayCollectionHandler.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /*
  3. * Copyright 2013 Johannes M. Schmitt <schmittjoh@gmail.com>
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. namespace JMS\Serializer\Handler;
  18. use Doctrine\Common\Collections\ArrayCollection;
  19. use JMS\Serializer\Context;
  20. use JMS\Serializer\GraphNavigator;
  21. use JMS\Serializer\VisitorInterface;
  22. use Doctrine\Common\Collections\Collection;
  23. use JMS\Serializer\Handler\SubscribingHandlerInterface;
  24. class ArrayCollectionHandler implements SubscribingHandlerInterface
  25. {
  26. public static function getSubscribingMethods()
  27. {
  28. $methods = array();
  29. $formats = array('json', 'xml', 'yml');
  30. $collectionTypes = array('ArrayCollection', 'Doctrine\Common\Collections\ArrayCollection', 'Doctrine\ORM\PersistentCollection', 'Doctrine\ODM\MongoDB\PersistentCollection', 'Doctrine\ODM\PHPCR\ChildrenCollection');
  31. foreach ($collectionTypes as $type) {
  32. foreach ($formats as $format) {
  33. $methods[] = array(
  34. 'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
  35. 'type' => $type,
  36. 'format' => $format,
  37. 'method' => 'serializeCollection',
  38. );
  39. $methods[] = array(
  40. 'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
  41. 'type' => $type,
  42. 'format' => $format,
  43. 'method' => 'deserializeCollection',
  44. );
  45. }
  46. }
  47. return $methods;
  48. }
  49. public function serializeCollection(VisitorInterface $visitor, Collection $collection, array $type, Context $context)
  50. {
  51. // We change the base type, and pass through possible parameters.
  52. $type['name'] = 'array';
  53. return $visitor->visitArray($collection->toArray(), $type, $context);
  54. }
  55. public function deserializeCollection(VisitorInterface $visitor, $data, array $type, Context $context)
  56. {
  57. // See above.
  58. $type['name'] = 'array';
  59. return new ArrayCollection($visitor->visitArray($data, $type, $context));
  60. }
  61. }