69 lines
2.5 KiB
PHP
69 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace KupShop\FeedGeneratorBundle\Configuration;
|
|
|
|
use Symfony\Component\Serializer\Exception\BadMethodCallException;
|
|
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
|
|
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
|
|
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
|
|
use Symfony\Component\Serializer\SerializerAwareInterface;
|
|
use Symfony\Component\Serializer\SerializerInterface;
|
|
|
|
/**
|
|
* This is just slightly modified Symfony\Component\Serializer\Normalizer\ArrayDenormalizer.
|
|
*/
|
|
class NodesDenormalizer implements DenormalizerInterface, SerializerAwareInterface
|
|
{
|
|
/**
|
|
* @var SerializerInterface|DenormalizerInterface
|
|
*/
|
|
private $serializer;
|
|
|
|
/**
|
|
* @throws NotNormalizableValueException
|
|
*/
|
|
public function denormalize($data, $class, $format = null, array $context = [])
|
|
{
|
|
if (null === $this->serializer) {
|
|
throw new BadMethodCallException('Please set a serializer before calling denormalize()!');
|
|
}
|
|
if (!is_array($data)) {
|
|
throw new InvalidArgumentException('Data expected to be an array, '.gettype($data).' given.');
|
|
}
|
|
if ('[]' !== substr($class, -2)) {
|
|
throw new InvalidArgumentException('Unsupported class: '.$class);
|
|
}
|
|
|
|
$serializer = $this->serializer;
|
|
|
|
$builtinType = isset($context['key_type']) ? $context['key_type']->getBuiltinType() : null;
|
|
foreach ($data as $key => $value) {
|
|
if (null !== $builtinType && !call_user_func('is_'.$builtinType, $key)) {
|
|
throw new NotNormalizableValueException(sprintf('The type of the key "%s" must be "%s" ("%s" given).', $key, $builtinType, gettype($key)));
|
|
}
|
|
|
|
// setup $class according to property "type"
|
|
$class = '\\'.__NAMESPACE__.'\\Nodes\\'.ucfirst($value['type']).'Node';
|
|
|
|
$data[$key] = $serializer->denormalize($value, $class, $format, $context);
|
|
}
|
|
|
|
return $data;
|
|
}
|
|
|
|
public function supportsDenormalization($data, $type, $format = null/* , array $context = array() */)
|
|
{
|
|
// when $type ends with INode[] its our case, so return true
|
|
return 'INode[]' === substr($type, -7);
|
|
}
|
|
|
|
public function setSerializer(SerializerInterface $serializer)
|
|
{
|
|
if (!$serializer instanceof DenormalizerInterface) {
|
|
throw new InvalidArgumentException('Expected a serializer that also implements DenormalizerInterface.');
|
|
}
|
|
|
|
$this->serializer = $serializer;
|
|
}
|
|
}
|