4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Serializer\Normalizer;
14 use Symfony\Component\Serializer\Exception\BadMethodCallException;
15 use Symfony\Component\Serializer\Exception\InvalidArgumentException;
16 use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
17 use Symfony\Component\Serializer\SerializerAwareInterface;
18 use Symfony\Component\Serializer\SerializerInterface;
21 * Denormalizes arrays of objects.
23 * @author Alexander M. Turek <me@derrabus.de>
25 * @final since version 3.3.
27 class ArrayDenormalizer implements DenormalizerInterface, SerializerAwareInterface
30 * @var SerializerInterface|DenormalizerInterface
37 * @throws NotNormalizableValueException
39 public function denormalize($data, $class, $format = null, array $context = array())
41 if (null === $this->serializer) {
42 throw new BadMethodCallException('Please set a serializer before calling denormalize()!');
44 if (!\is_array($data)) {
45 throw new InvalidArgumentException('Data expected to be an array, '.\gettype($data).' given.');
47 if ('[]' !== substr($class, -2)) {
48 throw new InvalidArgumentException('Unsupported class: '.$class);
51 $serializer = $this->serializer;
52 $class = substr($class, 0, -2);
54 $builtinType = isset($context['key_type']) ? $context['key_type']->getBuiltinType() : null;
55 foreach ($data as $key => $value) {
56 if (null !== $builtinType && !\call_user_func('is_'.$builtinType, $key)) {
57 throw new NotNormalizableValueException(sprintf('The type of the key "%s" must be "%s" ("%s" given).', $key, $builtinType, \gettype($key)));
60 $data[$key] = $serializer->denormalize($value, $class, $format, $context);
69 public function supportsDenormalization($data, $type, $format = null/*, array $context = array()*/)
71 $context = \func_num_args() > 3 ? func_get_arg(3) : array();
73 return '[]' === substr($type, -2)
74 && $this->serializer->supportsDenormalization($data, substr($type, 0, -2), $format, $context);
80 public function setSerializer(SerializerInterface $serializer)
82 if (!$serializer instanceof DenormalizerInterface) {
83 throw new InvalidArgumentException('Expected a serializer that also implements DenormalizerInterface.');
86 $this->serializer = $serializer;