diff --git a/Normalizer/AbstractNormalizer.php b/Normalizer/AbstractNormalizer.php index f6df34f2..06c316eb 100644 --- a/Normalizer/AbstractNormalizer.php +++ b/Normalizer/AbstractNormalizer.php @@ -445,6 +445,15 @@ protected function instantiateObject(array &$data, string $class, array &$contex unset($context['has_constructor']); + if (!$reflectionClass->isInstantiable()) { + throw NotNormalizableValueException::createForUnexpectedDataType( + sprintf('Failed to create object because the class "%s" is not instantiable.', $class), + $data, + ['unknown'], + $context['deserialization_path'] ?? null + ); + } + return new $class(); } diff --git a/Tests/Normalizer/AbstractNormalizerTest.php b/Tests/Normalizer/AbstractNormalizerTest.php index 924f07e3..10184995 100644 --- a/Tests/Normalizer/AbstractNormalizerTest.php +++ b/Tests/Normalizer/AbstractNormalizerTest.php @@ -16,6 +16,7 @@ use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Exception\MissingConstructorArgumentsException; +use Symfony\Component\Serializer\Exception\NotNormalizableValueException; use Symfony\Component\Serializer\Mapping\AttributeMetadata; use Symfony\Component\Serializer\Mapping\ClassMetadata; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; @@ -33,6 +34,7 @@ use Symfony\Component\Serializer\Tests\Fixtures\NullableOptionalConstructorArgumentDummy; use Symfony\Component\Serializer\Tests\Fixtures\StaticConstructorDummy; use Symfony\Component\Serializer\Tests\Fixtures\StaticConstructorNormalizer; +use Symfony\Component\Serializer\Tests\Fixtures\UnitEnumDummy; use Symfony\Component\Serializer\Tests\Fixtures\VariadicConstructorTypedArgsDummy; /** @@ -280,4 +282,16 @@ public function testIgnore() $this->assertSame([], $normalizer->normalize($dummy)); } + + /** + * @requires PHP 8.1 + */ + public function testDenormalizeWhenObjectNotInstantiable() + { + $this->expectException(NotNormalizableValueException::class); + + $normalizer = new ObjectNormalizer(); + + $normalizer->denormalize('{}', UnitEnumDummy::class); + } }