ArrayCollectionNormalizer.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. namespace JMS\SerializerBundle\Serializer\Normalizer;
  3. use JMS\SerializerBundle\Exception\UnsupportedException;
  4. use Doctrine\Common\Collections\ArrayCollection;
  5. use Symfony\Component\Serializer\Normalizer\SerializerAwareNormalizer;
  6. /**
  7. * This normalizer is specifically designed for Doctrine's ArrayCollection.
  8. *
  9. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  10. */
  11. class ArrayCollectionNormalizer extends SerializerAwareNormalizer
  12. {
  13. public function normalize($data, $format = null)
  14. {
  15. throw new UnsupportedException('This normalizer is only used for denormalization.');
  16. }
  17. public function denormalize($data, $type, $format = null)
  18. {
  19. if (!is_array($data)) {
  20. throw new \InvalidArgumentException('$data must be an array.');
  21. }
  22. if (!$this->supportsDenormalization($data, $type, $format)) {
  23. throw new UnsupportedException(sprintf('The type "%s" is not supported.', $type));
  24. }
  25. return new ArrayCollection($this->serializer->denormalize($data, 'array'.substr($type, 15), $format));
  26. }
  27. public function supportsNormalization($data, $format = null)
  28. {
  29. return false;
  30. }
  31. public function supportsDenormalization($data, $type, $format = null)
  32. {
  33. return 0 === strpos($type, 'ArrayCollection<') && '>' === $type[strlen($type)-1];
  34. }
  35. }