From 018ab22c47b4363dc4b49a238d71716b5948bb31 Mon Sep 17 00:00:00 2001 From: Ilya Orlov Date: Thu, 12 Sep 2024 18:28:50 +0500 Subject: [PATCH] fix: error when mapping from stdClass to constructor with nullable/optional arguments --- src/Transformer/NullableTransformerFactory.php | 4 ++++ tests/AutoMapperTest.php | 9 +++++++++ 2 files changed, 13 insertions(+) diff --git a/src/Transformer/NullableTransformerFactory.php b/src/Transformer/NullableTransformerFactory.php index 13450c1c..bf48a575 100644 --- a/src/Transformer/NullableTransformerFactory.php +++ b/src/Transformer/NullableTransformerFactory.php @@ -21,6 +21,10 @@ final class NullableTransformerFactory implements TransformerFactoryInterface, P public function getTransformer(TypesMatching $types, SourcePropertyMetadata $source, TargetPropertyMetadata $target, MapperMetadata $mapperMetadata): ?TransformerInterface { + if (null !== $target->parameterInConstructor) { + return null; + } + $sourceType = $types->getSourceUniqueType(); if (null === $sourceType) { diff --git a/tests/AutoMapperTest.php b/tests/AutoMapperTest.php index 565cb8d8..2b30c20f 100644 --- a/tests/AutoMapperTest.php +++ b/tests/AutoMapperTest.php @@ -525,6 +525,15 @@ public function testConstructorForcedException(): void $this->autoMapper->map($data, ConstructorWithDefaultValues::class); } + public function testConstructorWithDefaultFromStdClass(): void + { + $data = (object) ['baz' => 'baz']; + /** @var ConstructorWithDefaultValues $object */ + $object = $this->autoMapper->map($data, ConstructorWithDefaultValues::class); + + self::assertInstanceOf(ConstructorWithDefaultValues::class, $object); + } + public function testConstructorWithDefault(): void { $user = new Fixtures\UserDTONoAge();