ArrayDenormalizer.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Serializer\Normalizer;
  11. use Symfony\Component\Serializer\Exception\BadMethodCallException;
  12. use Symfony\Component\Serializer\Exception\InvalidArgumentException;
  13. use Symfony\Component\Serializer\Exception\UnexpectedValueException;
  14. use Symfony\Component\Serializer\SerializerAwareInterface;
  15. use Symfony\Component\Serializer\SerializerInterface;
  16. /**
  17. * Denormalizes arrays of objects.
  18. *
  19. * @author Alexander M. Turek <me@derrabus.de>
  20. */
  21. class ArrayDenormalizer implements DenormalizerInterface, SerializerAwareInterface
  22. {
  23. /**
  24. * @var SerializerInterface|DenormalizerInterface
  25. */
  26. private $serializer;
  27. /**
  28. * {@inheritdoc}
  29. *
  30. * @throws UnexpectedValueException
  31. */
  32. public function denormalize($data, $class, $format = null, array $context = array())
  33. {
  34. if ($this->serializer === null) {
  35. throw new BadMethodCallException('Please set a serializer before calling denormalize()!');
  36. }
  37. if (!is_array($data)) {
  38. throw new InvalidArgumentException('Data expected to be an array, '.gettype($data).' given.');
  39. }
  40. if (substr($class, -2) !== '[]') {
  41. throw new InvalidArgumentException('Unsupported class: '.$class);
  42. }
  43. $serializer = $this->serializer;
  44. $class = substr($class, 0, -2);
  45. $builtinType = isset($context['key_type']) ? $context['key_type']->getBuiltinType() : null;
  46. foreach ($data as $key => $value) {
  47. if (null !== $builtinType && !call_user_func('is_'.$builtinType, $key)) {
  48. throw new UnexpectedValueException(sprintf('The type of the key "%s" must be "%s" ("%s" given).', $key, $builtinType, gettype($key)));
  49. }
  50. $data[$key] = $serializer->denormalize($value, $class, $format, $context);
  51. }
  52. return $data;
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public function supportsDenormalization($data, $type, $format = null)
  58. {
  59. return substr($type, -2) === '[]'
  60. && $this->serializer->supportsDenormalization($data, substr($type, 0, -2), $format);
  61. }
  62. /**
  63. * {@inheritdoc}
  64. */
  65. public function setSerializer(SerializerInterface $serializer)
  66. {
  67. if (!$serializer instanceof DenormalizerInterface) {
  68. throw new InvalidArgumentException('Expected a serializer that also implements DenormalizerInterface.');
  69. }
  70. $this->serializer = $serializer;
  71. }
  72. }