Skip to content

Commit

Permalink
[Serializer] Refactoring and object_to_populate support.
Browse files Browse the repository at this point in the history
  • Loading branch information
dunglas committed Jan 4, 2015
1 parent c1c5cd5 commit b5990be
Show file tree
Hide file tree
Showing 4 changed files with 109 additions and 71 deletions.
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]);

This comment has been minimized.

Copy link
@StanAngeloff

StanAngeloff Jul 22, 2015

unseting here seems like a bug since $data is not passed by reference. The GetSetMethodNormalizer will continue to work with the unmodified copy.

In the case of GetSetMethodNormalizer the construtor is called with the correct parameter and then a setter is also called (if defined) for the same parameter.

/**
 * A class which represents an attachment stored on disk.
 */
class Attachment
{
  /**
   * @var string
   */
  private $fileName;

  /**
   * Initialize a new instance of Attachment.
   *
   * @param string $fileName
   */
  public function __construct($fileName)
  {
    $this->setFileName($fileName);
  }

  /**
   * Set the file name.
   *
   * @param string $fileName
   *
   * @return void
   */
  private function setFileName($fileName)
  {
    $this->fileName = $fileName;
  }
}

Attempting to unserialize an instance of the above class will fail as setFileName is private, however GetSetMethodNormalizer will attempt to invoke it.

This comment has been minimized.

Copy link
@dunglas

dunglas Jul 22, 2015

Author Member

Can you open a bug to track that?

} 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

0 comments on commit b5990be

Please sign in to comment.