Skip to content

Commit

Permalink
Fix resolving ParameterDefinition for optional parameters with unio…
Browse files Browse the repository at this point in the history
…n types
  • Loading branch information
vjik committed Dec 12, 2024
1 parent f8ebd40 commit ee4af91
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 4 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## 3.3.1 under development

- no changes in this release.
- Bug #100: Fix resolving `ParameterDefinition` for optional parameters with union types (@vjik)

## 3.3.0 March 16, 2024

Expand Down
2 changes: 1 addition & 1 deletion src/ParameterDefinition.php
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ private function resolveUnionType(ReflectionUnionType $parameterType, ContainerI
}

if ($this->parameter->isOptional()) {
return null;
return $this->parameter->getDefaultValue();
}

if (!isset($error)) {
Expand Down
2 changes: 1 addition & 1 deletion tests/Support/UnionOptionalDependency.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
final class UnionOptionalDependency
{
public function __construct(
private $value = null
private string|ColorInterface $value = 'test'
) {
}

Expand Down
13 changes: 12 additions & 1 deletion tests/Unit/ParameterDefinitionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit ee4af91

Please sign in to comment.