From db541b0c4031e77c94854963aa740206ab5d827a Mon Sep 17 00:00:00 2001 From: thisispiers Date: Tue, 20 Apr 2021 14:58:06 +0100 Subject: [PATCH] Support nullable class type hints (#182) --- Dice.php | 7 ++++++- tests/ConstructParamsTest.php | 6 ++++++ tests/TestData/ConstructParams.php | 8 ++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/Dice.php b/Dice.php index b75299b..92cead4 100644 --- a/Dice.php +++ b/Dice.php @@ -237,7 +237,12 @@ private function getParams(\ReflectionMethod $method, array $rule) { } // When nothing from $args or $share matches but a class is type hinted, create an instance to use, using a substitution if set else if ($class) try { - $parameters[] = $sub ? $this->expand($rule['substitutions'][$class], $share, true) : $this->create($class, [], $share); + if ($sub) { + $parameters[] = $this->expand($rule['substitutions'][$class], $share, true); + } + else { + $parameters[] = !$param->allowsNull() ? $this->create($class, [], $share) : null; + } } catch (\InvalidArgumentException $e) { } diff --git a/tests/ConstructParamsTest.php b/tests/ConstructParamsTest.php index 3508673..e40cec2 100644 --- a/tests/ConstructParamsTest.php +++ b/tests/ConstructParamsTest.php @@ -132,4 +132,10 @@ public function testNullScalarNested() { $this->assertEquals(null, $obj->nullScalar->string); } + public function testNullableClassTypeHint() { + $nullableClassTypeHint = $this->dice->create('NullableClassTypeHint'); + + $this->assertEquals(null, $nullableClassTypeHint->obj); + } + } \ No newline at end of file diff --git a/tests/TestData/ConstructParams.php b/tests/TestData/ConstructParams.php index ac93304..b5b9517 100644 --- a/tests/TestData/ConstructParams.php +++ b/tests/TestData/ConstructParams.php @@ -90,3 +90,11 @@ public function __construct($a = null, NB $b = null, NC $c = null) { } } + +class NullableClassTypeHint { + public $obj; + + public function __construct(?D $obj) { + $this->obj = $obj; + } +}