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 (#100)
  • Loading branch information
vjik authored Dec 16, 2024
1 parent 0a67ef0 commit 6647c83
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
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 6647c83

Please sign in to comment.