Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\Serializer\Normalizer; Chris@0: Chris@0: use Symfony\Component\Serializer\Exception\BadMethodCallException; Chris@0: use Symfony\Component\Serializer\Exception\InvalidArgumentException; Chris@0: use Symfony\Component\Serializer\Exception\UnexpectedValueException; Chris@0: use Symfony\Component\Serializer\SerializerAwareInterface; Chris@0: use Symfony\Component\Serializer\SerializerInterface; Chris@0: Chris@0: /** Chris@0: * Denormalizes arrays of objects. Chris@0: * Chris@0: * @author Alexander M. Turek Chris@0: */ Chris@0: class ArrayDenormalizer implements DenormalizerInterface, SerializerAwareInterface Chris@0: { Chris@0: /** Chris@0: * @var SerializerInterface|DenormalizerInterface Chris@0: */ Chris@0: private $serializer; Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: * Chris@0: * @throws UnexpectedValueException Chris@0: */ Chris@0: public function denormalize($data, $class, $format = null, array $context = array()) Chris@0: { Chris@0: if ($this->serializer === null) { Chris@0: throw new BadMethodCallException('Please set a serializer before calling denormalize()!'); Chris@0: } Chris@0: if (!is_array($data)) { Chris@0: throw new InvalidArgumentException('Data expected to be an array, '.gettype($data).' given.'); Chris@0: } Chris@0: if (substr($class, -2) !== '[]') { Chris@0: throw new InvalidArgumentException('Unsupported class: '.$class); Chris@0: } Chris@0: Chris@0: $serializer = $this->serializer; Chris@0: $class = substr($class, 0, -2); Chris@0: Chris@0: $builtinType = isset($context['key_type']) ? $context['key_type']->getBuiltinType() : null; Chris@0: foreach ($data as $key => $value) { Chris@0: if (null !== $builtinType && !call_user_func('is_'.$builtinType, $key)) { Chris@0: throw new UnexpectedValueException(sprintf('The type of the key "%s" must be "%s" ("%s" given).', $key, $builtinType, gettype($key))); Chris@0: } Chris@0: Chris@0: $data[$key] = $serializer->denormalize($value, $class, $format, $context); Chris@0: } Chris@0: Chris@0: return $data; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function supportsDenormalization($data, $type, $format = null) Chris@0: { Chris@0: return substr($type, -2) === '[]' Chris@0: && $this->serializer->supportsDenormalization($data, substr($type, 0, -2), $format); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function setSerializer(SerializerInterface $serializer) Chris@0: { Chris@0: if (!$serializer instanceof DenormalizerInterface) { Chris@0: throw new InvalidArgumentException('Expected a serializer that also implements DenormalizerInterface.'); Chris@0: } Chris@0: Chris@0: $this->serializer = $serializer; Chris@0: } Chris@0: }