Skip to content

[Serializer] Integrate the PropertyInfo Component (recursive denormalization and hardening) #17660

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 19, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Component/Serializer/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ CHANGELOG
* added support for serializing objects that implement `DateTimeInterface`
* added `AbstractObjectNormalizer` as a base class for normalizers that deal
with objects
* added support to relation deserialization

2.7.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
use Symfony\Component\Serializer\Exception\CircularReferenceException;
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
use Symfony\Component\PropertyInfo\Type;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;

/**
* Base class for a normalizer dealing with objects.
Expand All @@ -26,8 +30,16 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer
const ENABLE_MAX_DEPTH = 'enable_max_depth';
const DEPTH_KEY_PATTERN = 'depth_%s::%s';

private $propertyTypeExtractor;
private $attributesCache = array();

public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, PropertyTypeExtractorInterface $propertyTypeExtractor = null)
{
parent::__construct($classMetadataFactory, $nameConverter);

$this->propertyTypeExtractor = $propertyTypeExtractor;
}

/**
* {@inheritdoc}
*/
Expand Down Expand Up @@ -76,7 +88,7 @@ public function normalize($object, $format = null, array $context = array())

foreach ($stack as $attribute => $attributeValue) {
if (!$this->serializer instanceof NormalizerInterface) {
throw new LogicException(sprintf('Cannot normalize attribute "%s" because injected serializer is not a normalizer', $attribute));
throw new LogicException(sprintf('Cannot normalize attribute "%s" because the injected serializer is not a normalizer', $attribute));
}

$data = $this->updateData($data, $attribute, $this->serializer->normalize($attributeValue, $format, $context));
Expand Down Expand Up @@ -173,12 +185,15 @@ public function denormalize($data, $class, $format = null, array $context = arra
$allowed = $allowedAttributes === false || in_array($attribute, $allowedAttributes);
$ignored = in_array($attribute, $this->ignoredAttributes);

if ($allowed && !$ignored) {
try {
$this->setAttributeValue($object, $attribute, $value, $format, $context);
} catch (InvalidArgumentException $e) {
throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
}
if (!$allowed || $ignored) {
continue;
}

$value = $this->validateAndDenormalize($class, $attribute, $value, $format, $context);
try {
$this->setAttributeValue($object, $attribute, $value, $format, $context);
} catch (InvalidArgumentException $e) {
throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
}
}

Expand Down Expand Up @@ -210,6 +225,54 @@ protected function isAttributeToNormalize($object, $attributeName, &$context)
return !in_array($attributeName, $this->ignoredAttributes) && !$this->isMaxDepthReached(get_class($object), $attributeName, $context);
}

/**
* Validates the submitted data and denormalizes it.
*
* @param string $currentClass
* @param string $attribute
* @param mixed $data
* @param string|null $format
* @param array $context
*
* @return mixed
*
* @throws UnexpectedValueException
* @throws LogicException
*/
private function validateAndDenormalize($currentClass, $attribute, $data, $format, array $context)
{
if (null === $this->propertyTypeExtractor || null === $types = $this->propertyTypeExtractor->getTypes($currentClass, $attribute)){
return $data;
}

$expectedTypes = array();
foreach ($types as $type) {
if (null === $data && $type->isNullable()) {
return;
}

$builtinType = $type->getBuiltinType();
$class = $type->getClassName();
$expectedTypes[Type::BUILTIN_TYPE_OBJECT === $builtinType && $class ? $class : $builtinType] = true;

if (Type::BUILTIN_TYPE_OBJECT === $builtinType) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will this ever be executed (if I don't miss anything, the function will terminate above when is_object() evaluates to true, won't it?)?

if (!$this->serializer instanceof DenormalizerInterface) {
throw new LogicException(sprintf('Cannot denormalize attribute "%s" for class "%s" because injected serializer is not a denormalizer', $attribute, $class));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[...] because the injected [...]

}

if ($this->serializer->supportsDenormalization($data, $class, $format)) {
return $this->serializer->denormalize($data, $class, $format, $context);
}
}

if (call_user_func('is_'.$builtinType, $data)) {
return $data;
}
}

throw new UnexpectedValueException(sprintf('The type of the "%s" attribute for class "%s" must be one of "%s" ("%s" given).', $attribute, $currentClass, implode('", "', array_keys($expectedTypes)), gettype($data)));
}

/**
* Sets an attribute and apply the name converter if necessary.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,40 @@ class GetSetMethodNormalizer extends AbstractObjectNormalizer
{
private static $setterAccessibleCache = array();

/**
* {@inheritdoc}
*
* @throws RuntimeException
*/
public function denormalize($data, $class, $format = null, array $context = array())
{
$allowedAttributes = $this->getAllowedAttributes($class, $context, true);
$normalizedData = $this->prepareForDenormalization($data);

$reflectionClass = new \ReflectionClass($class);
$object = $this->instantiateObject($normalizedData, $class, $context, $reflectionClass, $allowedAttributes);

$classMethods = get_class_methods($object);
foreach ($normalizedData as $attribute => $value) {
if ($this->nameConverter) {
$attribute = $this->nameConverter->denormalize($attribute);
}

$allowed = $allowedAttributes === false || in_array($attribute, $allowedAttributes);
$ignored = in_array($attribute, $this->ignoredAttributes);

if ($allowed && !$ignored) {
$setter = 'set'.ucfirst($attribute);

if (in_array($setter, $classMethods) && !$reflectionClass->getMethod($setter)->isStatic()) {
$object->$setter($value);
}
}
}

return $object;
}

/**
* {@inheritdoc}
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;

Expand All @@ -29,9 +30,9 @@ class ObjectNormalizer extends AbstractObjectNormalizer
*/
protected $propertyAccessor;

public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, PropertyAccessorInterface $propertyAccessor = null)
public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, PropertyAccessorInterface $propertyAccessor = null, PropertyTypeExtractorInterface $propertyTypeExtractor = null)
{
parent::__construct($classMetadataFactory, $nameConverter);
parent::__construct($classMetadataFactory, $nameConverter, $propertyTypeExtractor);

$this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ public function provideCallbacks()

/**
* @expectedException \Symfony\Component\Serializer\Exception\LogicException
* @expectedExceptionMessage Cannot normalize attribute "object" because injected serializer is not a normalizer
* @expectedExceptionMessage Cannot normalize attribute "object" because the injected serializer is not a normalizer
*/
public function testUnableToNormalizeObjectAttribute()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@
namespace Symfony\Component\Serializer\Tests\Normalizer;

use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\SerializerInterface;
Expand Down Expand Up @@ -372,7 +375,7 @@ public function provideCallbacks()

/**
* @expectedException \Symfony\Component\Serializer\Exception\LogicException
* @expectedExceptionMessage Cannot normalize attribute "object" because injected serializer is not a normalizer
* @expectedExceptionMessage Cannot normalize attribute "object" because the injected serializer is not a normalizer
*/
public function testUnableToNormalizeObjectAttribute()
{
Expand Down Expand Up @@ -506,6 +509,29 @@ public function testThrowUnexpectedValueException()
{
$this->normalizer->denormalize(array('foo' => 'bar'), ObjectTypeHinted::class);
}

public function testDenomalizeRecursive()
{
$normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor());
$serializer = new Serializer(array(new DateTimeNormalizer(), $normalizer));

$obj = $serializer->denormalize(array('inner' => array('foo' => 'foo', 'bar' => 'bar'), 'date' => '1988/01/21'), ObjectOuter::class);
$this->assertEquals('foo', $obj->getInner()->foo);
$this->assertEquals('bar', $obj->getInner()->bar);
$this->assertEquals('1988-01-21', $obj->getDate()->format('Y-m-d'));
}

/**
* @expectedException UnexpectedValueException
* @expectedExceptionMessage The type of the "date" attribute for class "Symfony\Component\Serializer\Tests\Normalizer\ObjectOuter" must be one of "DateTimeInterface" ("string" given).
*/
public function testRejectInvalidType()
{
$normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor());
$serializer = new Serializer(array($normalizer));

$serializer->denormalize(array('date' => 'foo'), ObjectOuter::class);
}
}

class ObjectDummy
Expand Down Expand Up @@ -673,3 +699,35 @@ public function setFoo(array $f)
{
}
}

class ObjectOuter
{
private $inner;
private $date;

public function getInner()
{
return $this->inner;
}

public function setInner(ObjectInner $inner)
{
$this->inner = $inner;
}

public function setDate(\DateTimeInterface $date)
{
$this->date = $date;
}

public function getDate()
{
return $this->date;
}
}

class ObjectInner
{
public $foo;
public $bar;
}
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ public function testDenormalizeShouldIgnoreStaticProperty()

/**
* @expectedException \Symfony\Component\Serializer\Exception\LogicException
* @expectedExceptionMessage Cannot normalize attribute "bar" because injected serializer is not a normalizer
* @expectedExceptionMessage Cannot normalize attribute "bar" because the injected serializer is not a normalizer
*/
public function testUnableToNormalizeObjectAttribute()
{
Expand Down
2 changes: 2 additions & 0 deletions src/Symfony/Component/Serializer/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"symfony/property-access": "~2.8|~3.0",
"symfony/http-foundation": "~2.8|~3.0",
"symfony/cache": "~3.1",
"symfony/property-info": "~2.8|~3.0",
"doctrine/annotations": "~1.0",
"doctrine/cache": "~1.0"
},
Expand All @@ -32,6 +33,7 @@
},
"suggest": {
"psr/cache-implementation": "For using the metadata cache.",
"symfony/property-info": "To deserialize relations.",
"symfony/yaml": "For using the default YAML mapping loader.",
"symfony/config": "For using the XML mapping loader.",
"symfony/property-access": "For using the ObjectNormalizer.",
Expand Down