Skip to content

Commit 207f0da

Browse files
committed
feat: support for optional constructor parameters
1 parent e555763 commit 207f0da

2 files changed

Lines changed: 25 additions & 8 deletions

File tree

src/Container.php

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,13 +90,12 @@ private function resolve(string $id): object
9090
}
9191

9292
$dependencies = array_map(
93-
function (ReflectionParameter $reflectionParameter) use ($id): ?object {
93+
function (ReflectionParameter $reflectionParameter) use ($id) {
9494
$name = $reflectionParameter->getName();
9595
$type = $reflectionParameter->getType();
96-
$isOptional = $reflectionParameter->isOptional();
9796

98-
if ($isOptional) {
99-
return null;
97+
if ($reflectionParameter->isOptional()) {
98+
return $reflectionParameter->getDefaultValue();
10099
}
101100

102101
if (!$type) {

tests/ContainerTest.php

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,16 @@ public function test_it_throws_an_exception_when_the_class_has_a_union_type_hint
139139
$container->get(ExampleClassWithUnionTypeHint::class);
140140
}
141141

142+
public function test_it_resolves_optional_non_builtin_classes_constructor_parameters(): void
143+
{
144+
$container = new Container;
145+
146+
self::assertInstanceOf(
147+
ExampleClassWithAnOptionalConstructorParameter::class,
148+
$container->get(ExampleClassWithAnOptionalConstructorParameter::class)
149+
);
150+
}
151+
142152
/** @return array{0: class-string}[] */
143153
public static function nonInstantiableClassStringsDataProvider(): array
144154
{
@@ -180,8 +190,7 @@ public function __construct($parameter)
180190

181191
final class ExampleClassWithBuiltinConstructorParameter
182192
{
183-
/** @var int */
184-
public $parameter;
193+
public int $parameter;
185194

186195
public function __construct(int $parameter)
187196
{
@@ -191,15 +200,24 @@ public function __construct(int $parameter)
191200

192201
final class ExampleClassWithAnNonBuiltinConstructorParameter
193202
{
194-
/** @var DateTimeImmutable */
195-
public $dateTime;
203+
public DateTimeImmutable $dateTime;
196204

197205
public function __construct(DateTimeImmutable $dateTimeImmutable)
198206
{
199207
$this->dateTime = $dateTimeImmutable;
200208
}
201209
}
202210

211+
final class ExampleClassWithAnOptionalConstructorParameter
212+
{
213+
public string $parameter;
214+
215+
public function __construct(string $parameter = 'default')
216+
{
217+
$this->parameter = $parameter;
218+
}
219+
}
220+
203221
if (PHP_VERSION >= '8.0') {
204222
require_once __DIR__ . '/ExampleClassWithUnionTypeHint.php';
205223
}

0 commit comments

Comments
 (0)