Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Serializer] Add ability to collect denormalization errors #38968

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

Closed
wants to merge 1 commit into from
Closed
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Serializer\Exception;

interface AggregableExceptionInterface extends ExceptionInterface
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Serializer\Exception;

final class AggregatedException extends RuntimeException implements AggregableExceptionInterface
{
/**
* This property is public for performance reasons to reduce the number of hot path function calls.
*
* @var bool
*
* @internal
*/
public $isEmpty = true;

/**
* @var array<string, AggregableExceptionInterface>
*/
private $collection;

public function __construct()
{
parent::__construct('Errors occurred during the denormalization process');
}

public function put(string $param, AggregableExceptionInterface $exception): self
{
$this->isEmpty = false;
$this->collection[$param] = $exception;

return $this;
}

/**
* @return array<string, AggregableExceptionInterface>
*/
public function all(): array
{
$result = [];

foreach ($this->collection as $param => $exception) {
if ($exception instanceof self) {
foreach ($exception->all() as $nestedParams => $nestedException) {
$result["$param.$nestedParams"] = $nestedException;
}

continue;
}

$result[$param] = $exception;
}

return $result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface, AggregableExceptionInterface
Copy link
Contributor

Choose a reason for hiding this comment

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

After a quick look I think there is two spots that should not be handled:

throw new InvalidArgumentException(sprintf('Cannot denormalize to a "%s" without the HttpFoundation component installed. Try running "composer require symfony/http-foundation".', File::class));

throw new InvalidArgumentException('Unsupported class: '.$type);

Those cases are because of an invalid type or missing class, I think they should stop the denormalization process as usual.

{
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@
/**
* @author Maxime VEBER <maxime.veber@nekland.fr>
*/
class MissingConstructorArgumentsException extends RuntimeException
class MissingConstructorArgumentsException extends RuntimeException implements AggregableExceptionInterface
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@
/**
* @author Christian Flothmann <christian.flothmann@sensiolabs.de>
*/
class NotNormalizableValueException extends UnexpectedValueException
class NotNormalizableValueException extends UnexpectedValueException implements AggregableExceptionInterface
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Serializer\Exception;

final class VariadicConstructorArgumentsException extends RuntimeException implements AggregableExceptionInterface
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,14 @@

namespace Symfony\Component\Serializer\Normalizer;

use Symfony\Component\Serializer\Exception\AggregableExceptionInterface;
use Symfony\Component\Serializer\Exception\AggregatedException;
use Symfony\Component\Serializer\Exception\CircularReferenceException;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Exception\MissingConstructorArgumentsException;
use Symfony\Component\Serializer\Exception\RuntimeException;
use Symfony\Component\Serializer\Exception\VariadicConstructorArgumentsException;
use Symfony\Component\Serializer\Mapping\AttributeMetadataInterface;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
Expand Down Expand Up @@ -351,6 +354,7 @@ protected function instantiateObject(array &$data, string $class, array &$contex

$constructorParameters = $constructor->getParameters();

$aggregatedException = new AggregatedException();
$params = [];
foreach ($constructorParameters as $constructorParameter) {
$paramName = $constructorParameter->name;
Expand All @@ -361,12 +365,28 @@ protected function instantiateObject(array &$data, string $class, array &$contex
if ($constructorParameter->isVariadic()) {
if ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
if (!\is_array($data[$paramName])) {
throw new RuntimeException(sprintf('Cannot create an instance of "%s" from serialized data because the variadic parameter "%s" can only accept an array.', $class, $constructorParameter->name));
$e = new VariadicConstructorArgumentsException(sprintf('Cannot create an instance of "%s" from serialized data because the variadic parameter "%s" can only accept an array.', $class, $constructorParameter->name));
if (!($context[self::COLLECT_EXCEPTIONS] ?? false)) {
throw $e;
}

$aggregatedException->put($paramName, $e);
unset($data[$key]);
continue;
}

$variadicParameters = [];
foreach ($data[$paramName] as $parameterData) {
$variadicParameters[] = $this->denormalizeParameter($reflectionClass, $constructorParameter, $paramName, $parameterData, $context, $format);
foreach ($data[$paramName] as $paramKey => $parameterData) {
try {
$variadicParameters[] = $this->denormalizeParameter($reflectionClass, $constructorParameter, $paramName, $parameterData, $context, $format);
} catch (AggregableExceptionInterface $e) {
if (!($context[self::COLLECT_EXCEPTIONS] ?? false)) {
throw $e;
}

$aggregatedException->put("$paramName.$paramKey", $e);
continue;
}
}

$params = array_merge($params, $variadicParameters);
Expand All @@ -382,7 +402,15 @@ protected function instantiateObject(array &$data, string $class, array &$contex
}

// Don't run set for a parameter passed to the constructor
$params[] = $this->denormalizeParameter($reflectionClass, $constructorParameter, $paramName, $parameterData, $context, $format);
try {
$params[] = $this->denormalizeParameter($reflectionClass, $constructorParameter, $paramName, $parameterData, $context, $format);
greedyivan marked this conversation as resolved.
Show resolved Hide resolved
} catch (AggregableExceptionInterface $e) {
if (!($context[self::COLLECT_EXCEPTIONS] ?? false)) {
throw $e;
}

$aggregatedException->put($paramName, $e);
}
unset($data[$key]);
} elseif (\array_key_exists($key, $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class] ?? [])) {
$params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key];
Expand All @@ -391,10 +419,20 @@ protected function instantiateObject(array &$data, string $class, array &$contex
} elseif ($constructorParameter->isDefaultValueAvailable()) {
$params[] = $constructorParameter->getDefaultValue();
} else {
throw new MissingConstructorArgumentsException(sprintf('Cannot create an instance of "%s" from serialized data because its constructor requires parameter "%s" to be present.', $class, $constructorParameter->name));
$e = new MissingConstructorArgumentsException(sprintf('Cannot create an instance of "%s" from serialized data because its constructor requires parameter "%s" to be present.', $class, $constructorParameter->name));

if (!($context[self::COLLECT_EXCEPTIONS] ?? false)) {
throw $e;
}

$aggregatedException->put($paramName, $e);
}
}

if (($context[self::COLLECT_EXCEPTIONS] ?? false) && !$aggregatedException->isEmpty) {
throw $aggregatedException;
}

if ($constructor->isConstructor()) {
return $reflectionClass->newInstanceArgs($params);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
use Symfony\Component\Serializer\Encoder\CsvEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Exception\AggregableExceptionInterface;
use Symfony\Component\Serializer\Exception\AggregatedException;
use Symfony\Component\Serializer\Exception\ExtraAttributesException;
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
Expand Down Expand Up @@ -311,6 +313,8 @@ public function denormalize($data, string $type, string $format = null, array $c
$object = $this->instantiateObject($normalizedData, $type, $context, $reflectionClass, $allowedAttributes, $format);
$resolvedClass = $this->objectClassResolver ? ($this->objectClassResolver)($object) : \get_class($object);

$aggregatedException = new AggregatedException();

foreach ($normalizedData as $attribute => $value) {
if ($this->nameConverter) {
$attribute = $this->nameConverter->denormalize($attribute, $resolvedClass, $format, $context);
Expand All @@ -331,18 +335,31 @@ public function denormalize($data, string $type, string $format = null, array $c
}
}

$value = $this->validateAndDenormalize($resolvedClass, $attribute, $value, $format, $context);
try {
$this->setAttributeValue($object, $attribute, $value, $format, $context);
} catch (InvalidArgumentException $e) {
throw new NotNormalizableValueException(sprintf('Failed to denormalize attribute "%s" value for class "%s": '.$e->getMessage(), $attribute, $type), $e->getCode(), $e);
$value = $this->validateAndDenormalize($resolvedClass, $attribute, $value, $format, $context);
try {
$this->setAttributeValue($object, $attribute, $value, $format, $context);
} catch (InvalidArgumentException $e) {
throw new NotNormalizableValueException(sprintf('Failed to denormalize attribute "%s" value for class "%s": '.$e->getMessage(), $attribute, $type), $e->getCode(), $e);
Copy link
Member

Choose a reason for hiding this comment

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

Could we try to avoid the extra try / catch. I'm nitpicking but catching and throwing is very costly in PHP so let's avoid it when not strictly necessary.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The inner try / catch was here for some reason. It was wrapped around to handle all calls that throw exceptions.

Copy link
Contributor

Choose a reason for hiding this comment

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

I think he suggested to remove the inner try/catch, add another catch clause to the outer one when you deal with this exception by throwing or aggregating it depending on the context

}
} catch (AggregableExceptionInterface $e) {
if (!($context[self::COLLECT_EXCEPTIONS] ?? false)) {
throw $e;
}

$aggregatedException->put($attribute, $e);
continue;
}
}

if (!empty($extraAttributes)) {
throw new ExtraAttributesException($extraAttributes);
}

if (($context[self::COLLECT_EXCEPTIONS] ?? false) && !$aggregatedException->isEmpty) {
throw $aggregatedException;
}

return $object;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@
*/
interface DenormalizerInterface
{
/**
* Collects denormalization exceptions instead of throwing out the first one.
*/
public const COLLECT_EXCEPTIONS = 'collect_exceptions';

/**
* Denormalizes data back into an object of the given class.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Symfony\Component\Serializer\Tests\Fixtures;

class CollectErrorsArrayDummy
{
/**
* @var \DateTimeImmutable
*/
public $date;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace Symfony\Component\Serializer\Tests\Fixtures;

class CollectErrorsDummy
{
/**
* @var int
*/
public $int;

/**
* @var array
*/
public $array;

/**
* @var CollectErrorsArrayDummy[]
*/
public $arrayOfObjects;

/**
* @var CollectErrorsArrayDummy[]
*/
public $stringArrayOfObjects;

/**
* @var CollectErrorsObjectDummy
*/
public $object;

/**
* @var CollectErrorsVariadicObjectDummy
*/
public $variadicObject;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Symfony\Component\Serializer\Tests\Fixtures;

class CollectErrorsObjectDummy
{
public $foo;
public $bar;
public $baz;

public function __construct(int $foo, int $bar, int $baz)
{
$this->foo = $foo;
$this->bar = $bar;
$this->baz = $baz;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Symfony\Component\Serializer\Tests\Fixtures;

class CollectErrorsVariadicObjectDummy
{
public $foo;

/** @var CollectErrorsVariadicObjectDummy[] */
public $args;

public function __construct(int $foo, CollectErrorsVariadicObjectDummy ...$args)
{
$this->foo = $foo;
$this->args = $args;
}
}
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.