fix denormalizing scalar with UnwrappingDenormalizer

This commit is contained in:
Camille Dejoye 2020-11-26 14:01:08 +01:00
parent 634d168d9c
commit 98cf389fb9
2 changed files with 12 additions and 2 deletions

View File

@ -189,7 +189,10 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface
*/ */
public function denormalize($data, string $type, 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)) { if (!('is_'.$type)($data)) {
throw new NotNormalizableValueException(sprintf('Data expected to be of type "%s" ("%s" given).', $type, get_debug_type($data))); throw new NotNormalizableValueException(sprintf('Data expected to be of type "%s" ("%s" given).', $type, get_debug_type($data)));
} }
@ -201,7 +204,7 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface
throw new LogicException('You must register at least one normalizer to be able to denormalize objects.'); 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); return $normalizer->denormalize($data, $type, $format, $context);
} }

View File

@ -613,6 +613,13 @@ class SerializerTest extends TestCase
$serializer->deserialize('["42"]', 'int[]', 'json'); $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() private function serializerWithClassDiscriminator()
{ {
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));