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\UnexpectedValueException;
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 class ArrayDenormalizer implements DenormalizerInterface, SerializerAwareInterface
28 * @var SerializerInterface|DenormalizerInterface
35 public function denormalize($data, $class, $format = null, array $context = array())
37 if ($this->serializer === null) {
38 throw new BadMethodCallException('Please set a serializer before calling denormalize()!');
40 if (!is_array($data)) {
41 throw new InvalidArgumentException('Data expected to be an array, '.gettype($data).' given.');
43 if (substr($class, -2) !== '[]') {
44 throw new InvalidArgumentException('Unsupported class: '.$class);
47 $serializer = $this->serializer;
48 $class = substr($class, 0, -2);
50 $builtinType = isset($context['key_type']) ? $context['key_type']->getBuiltinType() : null;
51 foreach ($data as $key => $value) {
52 if (null !== $builtinType && !call_user_func('is_'.$builtinType, $key)) {
53 throw new UnexpectedValueException(sprintf('The type of the key "%s" must be "%s" ("%s" given).', $key, $builtinType, gettype($key)));
56 $data[$key] = $serializer->denormalize($value, $class, $format, $context);
65 public function supportsDenormalization($data, $type, $format = null)
67 return substr($type, -2) === '[]'
68 && $this->serializer->supportsDenormalization($data, substr($type, 0, -2), $format);
74 public function setSerializer(SerializerInterface $serializer)
76 if (!$serializer instanceof DenormalizerInterface) {
77 throw new InvalidArgumentException('Expected a serializer that also implements DenormalizerInterface.');
80 $this->serializer = $serializer;