Skip to content

[Serializer] Fix denormalizing scalar with UnwrappingDenormalizer #39180

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
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
7 changes: 5 additions & 2 deletions src/Symfony/Component/Serializer/Serializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,10 @@ public function normalize($data, string $format = null, array $context = [])
*/
public function denormalize($data, string $type, string $format = null, array $context = [])
{
if (isset(self::SCALAR_TYPES[$type])) {
$normalizer = $this->getDenormalizer($data, $type, $format, $context);

// Check for a denormalizer first, e.g. the data is wrapped
if (!$normalizer && isset(self::SCALAR_TYPES[$type])) {
if (!('is_'.$type)($data)) {
throw new NotNormalizableValueException(sprintf('Data expected to be of type "%s" ("%s" given).', $type, get_debug_type($data)));
}
Expand All @@ -201,7 +204,7 @@ public function denormalize($data, string $type, string $format = null, array $c
throw new LogicException('You must register at least one normalizer to be able to denormalize objects.');
}

if ($normalizer = $this->getDenormalizer($data, $type, $format, $context)) {
if ($normalizer) {
return $normalizer->denormalize($data, $type, $format, $context);
}

Expand Down
7 changes: 7 additions & 0 deletions src/Symfony/Component/Serializer/Tests/SerializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -613,6 +613,13 @@ public function testDeserializeInconsistentScalarArray()
$serializer->deserialize('["42"]', 'int[]', 'json');
}

public function testDeserializeWrappedScalar()
{
$serializer = new Serializer([new UnwrappingDenormalizer()], ['json' => new JsonEncoder()]);

$this->assertSame(42, $serializer->deserialize('{"wrapper": 42}', 'int', 'json', [UnwrappingDenormalizer::UNWRAP_PATH => '[wrapper]']));
}

private function serializerWithClassDiscriminator()
{
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
Expand Down