diff --git a/CHANGELOG.md b/CHANGELOG.md index 237541a..cc1f5da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## 3.3.1 under development +- Bug #100: Fix resolving `ParameterDefinition` for optional parameters with union types (@vjik) - Enh #101: Minor performance improvement by removing unnecessary code in `DefinitionStorage` (@vjik) ## 3.3.0 March 16, 2024 diff --git a/src/ParameterDefinition.php b/src/ParameterDefinition.php index 5e74989..e11fc05 100644 --- a/src/ParameterDefinition.php +++ b/src/ParameterDefinition.php @@ -192,7 +192,7 @@ private function resolveUnionType(ReflectionUnionType $parameterType, ContainerI } if ($this->parameter->isOptional()) { - return null; + return $this->parameter->getDefaultValue(); } if (!isset($error)) { diff --git a/tests/Support/UnionOptionalDependency.php b/tests/Support/UnionOptionalDependency.php index 0ac3752..806ad3b 100644 --- a/tests/Support/UnionOptionalDependency.php +++ b/tests/Support/UnionOptionalDependency.php @@ -7,7 +7,7 @@ final class UnionOptionalDependency { public function __construct( - private $value = null + private string|ColorInterface $value = 'test' ) { } diff --git a/tests/Unit/ParameterDefinitionTest.php b/tests/Unit/ParameterDefinitionTest.php index 4eb3117..6ddcc9f 100644 --- a/tests/Unit/ParameterDefinitionTest.php +++ b/tests/Unit/ParameterDefinitionTest.php @@ -16,6 +16,7 @@ use Yiisoft\Definitions\Exception\NotInstantiableException; use Yiisoft\Definitions\ParameterDefinition; use Yiisoft\Definitions\Tests\Support\CircularReferenceExceptionDependency; +use Yiisoft\Definitions\Tests\Support\ColorInterface; use Yiisoft\Definitions\Tests\Support\GearBox; use Yiisoft\Definitions\Tests\Support\RuntimeExceptionDependency; use Yiisoft\Definitions\Tests\Support\Car; @@ -332,13 +333,23 @@ public function testResolveOptionalUnionTypeWithIncorrectTypeInContainer(): void } public function testResolveOptionalUnionType(): void + { + $definition = new ParameterDefinition( + $this->getFirstParameter(static fn (string|ColorInterface $value = 'test') => true) + ); + $container = new SimpleContainer(); + + $this->assertSame('test', $definition->resolve($container)); + } + + public function testResolveOptionalPromotedPropertyUnionType(): void { $definition = new ParameterDefinition( $this->getFirstConstructorParameter(UnionOptionalDependency::class) ); $container = new SimpleContainer(); - $this->assertNull($definition->resolve($container)); + $this->assertSame('test', $definition->resolve($container)); } public function testResolveUnionBuiltin(): void