Skip to content

Commit 6647c83

Browse files
authored
Fix resolving ParameterDefinition for optional parameters with union types (#100)
1 parent 0a67ef0 commit 6647c83

File tree

4 files changed

+15
-3
lines changed

4 files changed

+15
-3
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
## 3.3.1 under development
44

5+
- Bug #100: Fix resolving `ParameterDefinition` for optional parameters with union types (@vjik)
56
- Enh #101: Minor performance improvement by removing unnecessary code in `DefinitionStorage` (@vjik)
67

78
## 3.3.0 March 16, 2024

src/ParameterDefinition.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ private function resolveUnionType(ReflectionUnionType $parameterType, ContainerI
192192
}
193193

194194
if ($this->parameter->isOptional()) {
195-
return null;
195+
return $this->parameter->getDefaultValue();
196196
}
197197

198198
if (!isset($error)) {

tests/Support/UnionOptionalDependency.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
final class UnionOptionalDependency
88
{
99
public function __construct(
10-
private $value = null
10+
private string|ColorInterface $value = 'test'
1111
) {
1212
}
1313

tests/Unit/ParameterDefinitionTest.php

+12-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
use Yiisoft\Definitions\Exception\NotInstantiableException;
1717
use Yiisoft\Definitions\ParameterDefinition;
1818
use Yiisoft\Definitions\Tests\Support\CircularReferenceExceptionDependency;
19+
use Yiisoft\Definitions\Tests\Support\ColorInterface;
1920
use Yiisoft\Definitions\Tests\Support\GearBox;
2021
use Yiisoft\Definitions\Tests\Support\RuntimeExceptionDependency;
2122
use Yiisoft\Definitions\Tests\Support\Car;
@@ -332,13 +333,23 @@ public function testResolveOptionalUnionTypeWithIncorrectTypeInContainer(): void
332333
}
333334

334335
public function testResolveOptionalUnionType(): void
336+
{
337+
$definition = new ParameterDefinition(
338+
$this->getFirstParameter(static fn (string|ColorInterface $value = 'test') => true)
339+
);
340+
$container = new SimpleContainer();
341+
342+
$this->assertSame('test', $definition->resolve($container));
343+
}
344+
345+
public function testResolveOptionalPromotedPropertyUnionType(): void
335346
{
336347
$definition = new ParameterDefinition(
337348
$this->getFirstConstructorParameter(UnionOptionalDependency::class)
338349
);
339350
$container = new SimpleContainer();
340351

341-
$this->assertNull($definition->resolve($container));
352+
$this->assertSame('test', $definition->resolve($container));
342353
}
343354

344355
public function testResolveUnionBuiltin(): void

0 commit comments

Comments
 (0)