Skip to content

[Serializer] Fix denormalize constructor arguments #52578

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
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
Expand Up @@ -350,6 +350,7 @@ protected function instantiateObject(array &$data, string $class, array &$contex
$constructorParameters = $constructor->getParameters();
$missingConstructorArguments = [];
$params = [];
$unsetKeys = [];
foreach ($constructorParameters as $constructorParameter) {
$paramName = $constructorParameter->name;
$key = $this->nameConverter ? $this->nameConverter->normalize($paramName, $class, $format, $context) : $paramName;
Expand All @@ -368,18 +369,17 @@ protected function instantiateObject(array &$data, string $class, array &$contex
}

$params = array_merge($params, $variadicParameters);
unset($data[$key]);
$unsetKeys[] = $key;
}
} elseif ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
$parameterData = $data[$key];
if (null === $parameterData && $constructorParameter->allowsNull()) {
$params[] = null;
// Don't run set for a parameter passed to the constructor
unset($data[$key]);
$unsetKeys[] = $key;

continue;
}

// Don't run set for a parameter passed to the constructor
try {
$params[] = $this->denormalizeParameter($reflectionClass, $constructorParameter, $paramName, $parameterData, $context, $format);
} catch (NotNormalizableValueException $exception) {
Expand All @@ -390,7 +390,8 @@ protected function instantiateObject(array &$data, string $class, array &$contex
$context['not_normalizable_value_exceptions'][] = $exception;
$params[] = $parameterData;
}
unset($data[$key]);

$unsetKeys[] = $key;
} elseif (\array_key_exists($key, $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class] ?? [])) {
$params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key];
} elseif (\array_key_exists($key, $this->defaultContext[self::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class] ?? [])) {
Expand Down Expand Up @@ -421,11 +422,25 @@ protected function instantiateObject(array &$data, string $class, array &$contex
}

if (!$constructor->isConstructor()) {
return $constructor->invokeArgs(null, $params);
$instance = $constructor->invokeArgs(null, $params);

// do not set a parameter that has been set in the constructor
foreach ($unsetKeys as $key) {
unset($data[$key]);
}

return $instance;
}

try {
return $reflectionClass->newInstanceArgs($params);
$instance = $reflectionClass->newInstanceArgs($params);

// do not set a parameter that has been set in the constructor
foreach ($unsetKeys as $key) {
unset($data[$key]);
}

return $instance;
} catch (\TypeError $e) {
if (!isset($context['not_normalizable_value_exceptions'])) {
throw $e;
Expand Down
14 changes: 13 additions & 1 deletion src/Symfony/Component/Serializer/Serializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,20 @@ public function denormalize($data, string $type, string $format = null, array $c
$context['not_normalizable_value_exceptions'] = [];
$errors = &$context['not_normalizable_value_exceptions'];
$denormalized = $normalizer->denormalize($data, $type, $format, $context);

if ($errors) {
throw new PartialDenormalizationException($denormalized, $errors);
// merge errors so that one path has only one error
$uniqueErrors = [];
foreach ($errors as $error) {
if (null === $error->getPath()) {
$uniqueErrors[] = $error;
continue;
}

$uniqueErrors[$error->getPath()] = $uniqueErrors[$error->getPath()] ?? $error;
}

throw new PartialDenormalizationException($denormalized, array_values($uniqueErrors));
}

return $denormalized;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public function __construct($constructorArgument)

final class Php74FullWithTypedConstructor
{
public function __construct(float $something)
public function __construct(float $something, bool $somethingElse)
{
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,23 +58,23 @@ public function testMetadataAwareNameConvertorWithNotSerializedConstructorParame
public function testConstructorWithMissingData()
{
$data = [
'foo' => 10,
'bar' => 10,
];

$normalizer = $this->getDenormalizerForConstructArguments();
try {
$normalizer->denormalize($data, ConstructorArgumentsObject::class);
self::fail(sprintf('Failed asserting that exception of type "%s" is thrown.', MissingConstructorArgumentsException::class));
} catch (MissingConstructorArgumentsException $e) {
self::assertSame(sprintf('Cannot create an instance of "%s" from serialized data because its constructor requires the following parameters to be present : "$bar", "$baz".', ConstructorArgumentsObject::class), $e->getMessage());
self::assertSame(['bar', 'baz'], $e->getMissingConstructorArguments());
self::assertSame(sprintf('Cannot create an instance of "%s" from serialized data because its constructor requires the following parameters to be present : "$foo", "$baz".', ConstructorArgumentsObject::class), $e->getMessage());
self::assertSame(['foo', 'baz'], $e->getMissingConstructorArguments());
}
}

public function testExceptionsAreCollectedForConstructorWithMissingData()
{
$data = [
'foo' => 10,
'bar' => 10,
];

$exceptions = [];
Expand All @@ -85,7 +85,7 @@ public function testExceptionsAreCollectedForConstructorWithMissingData()
]);

self::assertCount(2, $exceptions);
self::assertSame('Failed to create object because the class misses the "bar" property.', $exceptions[0]->getMessage());
self::assertSame('Failed to create object because the class misses the "foo" property.', $exceptions[0]->getMessage());
self::assertSame('Failed to create object because the class misses the "baz" property.', $exceptions[1]->getMessage());
}
}
21 changes: 20 additions & 1 deletion src/Symfony/Component/Serializer/Tests/SerializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -868,7 +868,8 @@ public function testCollectDenormalizationErrors(?ClassMetadataFactory $classMet
],
"php74FullWithConstructor": {},
"php74FullWithTypedConstructor": {
"something": "not a float"
"something": "not a float",
"somethingElse": "not a bool"
},
"dummyMessage": {
},
Expand Down Expand Up @@ -1032,6 +1033,24 @@ public function testCollectDenormalizationErrors(?ClassMetadataFactory $classMet
'useMessageForUser' => false,
'message' => 'The type of the "something" attribute for class "Symfony\Component\Serializer\Tests\Fixtures\Php74FullWithTypedConstructor" must be one of "float" ("string" given).',
],
[
'currentType' => 'string',
'expectedTypes' => [
'float',
],
'path' => 'php74FullWithTypedConstructor.something',
'useMessageForUser' => false,
'message' => 'The type of the "something" attribute for class "Symfony\Component\Serializer\Tests\Fixtures\Php74FullWithTypedConstructor" must be one of "float" ("string" given).',
],
[
'currentType' => 'string',
'expectedTypes' => [
'bool',
],
'path' => 'php74FullWithTypedConstructor.somethingElse',
'useMessageForUser' => false,
'message' => 'The type of the "somethingElse" attribute for class "Symfony\Component\Serializer\Tests\Fixtures\Php74FullWithTypedConstructor" must be one of "bool" ("string" given).',
],
$classMetadataFactory ?
[
'currentType' => 'null',
Expand Down