Skip to content

[Serializer] Refactoring and object_to_populate support. #13252

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 1 commit into from
Jan 7, 2015
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
84 changes: 84 additions & 0 deletions src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,88 @@ protected function getAllowedAttributes($classOrObject, array $context)

return array_unique($allowedAttributes);
}

/**
* Normalizes the given data to an array. It's particularly useful during
* the denormalization process.
*
* @param object|array $data
*
* @return array
*/
protected function prepareForDenormalization($data)
{
if (is_array($data) || is_object($data) && $data instanceof \ArrayAccess) {
$normalizedData = $data;
} elseif (is_object($data)) {
$normalizedData = array();

foreach ($data as $attribute => $value) {
$normalizedData[$attribute] = $value;
}
} else {
$normalizedData = array();
}

return $normalizedData;
}

/**
* Instantiates an object using contructor parameters when needed.
*
* This method also allows to denormalize data into an existing object if
* it is present in the context with the object_to_populate key.
*
* @param array $data
* @param string $class
* @param array $context
* @param \ReflectionClass $reflectionClass
* @param array|bool $allowedAttributes
*
* @return object
*
* @throws RuntimeException
*/
protected function instantiateObject(array $data, $class, array &$context, \ReflectionClass $reflectionClass, $allowedAttributes)
{
if (
isset($context['object_to_populate']) &&
is_object($context['object_to_populate']) &&
$class === get_class($context['object_to_populate'])
) {
return $context['object_to_populate'];
}

$constructor = $reflectionClass->getConstructor();
if ($constructor) {
$constructorParameters = $constructor->getParameters();

$params = array();
foreach ($constructorParameters as $constructorParameter) {
$paramName = lcfirst($this->formatAttribute($constructorParameter->name));

$allowed = $allowedAttributes === false || in_array($paramName, $allowedAttributes);
$ignored = in_array($paramName, $this->ignoredAttributes);
if ($allowed && !$ignored && isset($data[$paramName])) {
$params[] = $data[$paramName];
// don't run set for a parameter passed to the constructor
unset($data[$paramName]);
} elseif ($constructorParameter->isOptional()) {
$params[] = $constructorParameter->getDefaultValue();
} else {
throw new RuntimeException(
sprintf(
'Cannot create an instance of %s from serialized data because its constructor requires parameter "%s" to be present.',
$class,
$constructorParameter->name
)
);
}
}

return $reflectionClass->newInstanceArgs($params);
}

return new $class();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -136,54 +136,16 @@ public function normalize($object, $format = null, array $context = array())

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

if (is_array($data) || is_object($data) && $data instanceof \ArrayAccess) {
$normalizedData = $data;
} elseif (is_object($data)) {
$normalizedData = array();

foreach ($data as $attribute => $value) {
$normalizedData[$attribute] = $value;
}
} else {
$normalizedData = array();
}
$normalizedData = $this->prepareForDenormalization($data);

$reflectionClass = new \ReflectionClass($class);
$constructor = $reflectionClass->getConstructor();

if ($constructor) {
$constructorParameters = $constructor->getParameters();

$params = array();
foreach ($constructorParameters as $constructorParameter) {
$paramName = lcfirst($this->formatAttribute($constructorParameter->name));

$allowed = $allowedAttributes === false || in_array($paramName, $allowedAttributes);
$ignored = in_array($paramName, $this->ignoredAttributes);
if ($allowed && !$ignored && isset($normalizedData[$paramName])) {
$params[] = $normalizedData[$paramName];
// don't run set for a parameter passed to the constructor
unset($normalizedData[$paramName]);
} elseif ($constructorParameter->isOptional()) {
$params[] = $constructorParameter->getDefaultValue();
} else {
throw new RuntimeException(
'Cannot create an instance of '.$class.
' from serialized data because its constructor requires '.
'parameter "'.$constructorParameter->name.
'" to be present.');
}
}

$object = $reflectionClass->newInstanceArgs($params);
} else {
$object = new $class();
}
$object = $this->instantiateObject($normalizedData, $class, $context, $reflectionClass, $allowedAttributes);

foreach ($normalizedData as $attribute => $value) {
$allowed = $allowedAttributes === false || in_array($attribute, $allowedAttributes);
Expand Down
33 changes: 4 additions & 29 deletions src/Symfony/Component/Serializer/Normalizer/PropertyNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,41 +72,16 @@ public function normalize($object, $format = null, array $context = array())

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

$reflectionClass = new \ReflectionClass($class);
$constructor = $reflectionClass->getConstructor();

if ($constructor) {
$constructorParameters = $constructor->getParameters();

$params = array();
foreach ($constructorParameters as $constructorParameter) {
$paramName = lcfirst($this->formatAttribute($constructorParameter->name));

$allowed = $allowedAttributes === false || in_array($paramName, $allowedAttributes);
$ignored = in_array($paramName, $this->ignoredAttributes);
if ($allowed && !$ignored && isset($data[$paramName])) {
$params[] = $data[$paramName];
// don't run set for a parameter passed to the constructor
unset($data[$paramName]);
} elseif (!$constructorParameter->isOptional()) {
throw new RuntimeException(sprintf(
'Cannot create an instance of %s from serialized data because '.
'its constructor requires parameter "%s" to be present.',
$class,
$constructorParameter->name
));
}
}

$object = $reflectionClass->newInstanceArgs($params);
} else {
$object = new $class();
}
$object = $this->instantiateObject($data, $class, $context, $reflectionClass, $allowedAttributes);

foreach ($data as $propertyName => $value) {
$propertyName = lcfirst($this->formatAttribute($propertyName));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,23 @@ public function testCircularReferenceHandler()
$expected = array('me' => 'Symfony\Component\Serializer\Tests\Fixtures\CircularReferenceDummy');
$this->assertEquals($expected, $this->normalizer->normalize($obj));
}

public function testObjectToPopulate()
{
$dummy = new GetSetDummy();
$dummy->setFoo('foo');

$obj = $this->normalizer->denormalize(
array('bar' => 'bar'),
__NAMESPACE__.'\GetSetDummy',
null,
array('object_to_populate' => $dummy)
);

$this->assertEquals($dummy, $obj);
$this->assertEquals('foo', $obj->getFoo());
$this->assertEquals('bar', $obj->getBar());
}
}

class GetSetDummy
Expand Down