Skip to content

Commit

Permalink
Support nullable class type hints (#182)
Browse files Browse the repository at this point in the history
  • Loading branch information
thisispiers authored Apr 20, 2021
1 parent cbcc422 commit db541b0
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
7 changes: 6 additions & 1 deletion Dice.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
}
Expand Down
6 changes: 6 additions & 0 deletions tests/ConstructParamsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

}
8 changes: 8 additions & 0 deletions tests/TestData/ConstructParams.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}

0 comments on commit db541b0

Please sign in to comment.