From f9119da0ca1092056955c9b4fa514b3347f145a9 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 --- CHANGELOG.md | 5 ++++- src/Transformer/NullableTransformerFactory.php | 4 ++++ tests/AutoMapperTest.php | 9 +++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c238b823..302b4b37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - [GH#180](https://github.com/jolicode/automapper/pull/180) Add configuration to generate code with strict types +### Fixed +- [GH#184](https://github.com/jolicode/automapper/pull/184) Fix error when mapping from stdClass to constructor with nullable/optional arguments + ## [9.1.2] - 2024-09-03 ### Fixed - [GH#174](https://github.com/jolicode/automapper/pull/174) Fix race condition when writing generated mappers @@ -157,7 +160,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - [GH#22](https://github.com/jolicode/automapper/pull/22) Added generic AST extractor - [GH#21](https://github.com/jolicode/automapper/pull/21) Add VERSION constants within AutoMapper class and use it for transformers hashes - + ### Changed - [GH#19](https://github.com/jolicode/automapper/pull/19) Use attributes everywhere instead of annotations - [GH#18](https://github.com/jolicode/automapper/pull/18) Symfony 7 support 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();