diff --git a/src/Builder/Reflection.php b/src/Builder/Reflection.php index e4eb9d5..0a33831 100644 --- a/src/Builder/Reflection.php +++ b/src/Builder/Reflection.php @@ -63,6 +63,10 @@ private function collect(ReflectionMethod $constructor, array $data): iterable if ($parameter->isDefaultValueAvailable()) { yield $parameter->getDefaultValue(); } + + if ($parameter->allowsNull()) { + yield null; + } } } diff --git a/test/SimpleNullableConstructor.php b/test/SimpleNullableConstructor.php new file mode 100644 index 0000000..c9b4416 --- /dev/null +++ b/test/SimpleNullableConstructor.php @@ -0,0 +1,17 @@ +someInt = $someInt; + $this->someString1 = $someString1; + $this->someString2 = $someString2; + } +} diff --git a/test/unit/Builder/ReflectionTest.php b/test/unit/Builder/ReflectionTest.php index 36f5bb9..53d90c9 100644 --- a/test/unit/Builder/ReflectionTest.php +++ b/test/unit/Builder/ReflectionTest.php @@ -14,6 +14,7 @@ use RstGroup\ObjectBuilder\Test\Object\SomeSecondObject; use RstGroup\ObjectBuilder\Test\SimpleMixedConstructor; use RstGroup\ObjectBuilder\Test\SimpleMixedConstructorWithDefaultValue; +use RstGroup\ObjectBuilder\Test\SimpleNullableConstructor; use RstGroup\ObjectBuilder\Test\SimpleScalarConstructor; use RstGroup\ObjectBuilder\Test\SomeAggregateRoot; use RstGroup\ObjectBuilder\Test\SomeObjectWithEmptyConstructor; @@ -234,4 +235,22 @@ public function iCanBuildAdvancedObjectHierarchy() $this->assertSame(1, $object->simpleObject1->someInt); $this->assertSame(2, $object->simpleObject2->someInt); } + + /** @test */ + public function iCanBuildObjectWithNullableParameterWithoutDefaultValue() + { + $data = [ + 'someString1' => 'some string1', + 'someString2' => 'some string2', + ]; + $class = SimpleNullableConstructor::class; + + /** @var SimpleNullableConstructor $object */ + $object = static::$builder->build($class, $data); + + $this->assertInstanceOf(SimpleNullableConstructor::class, $object); + $this->assertSame('some string1', $object->someString1); + $this->assertSame('some string2', $object->someString2); + $this->assertnull($object->someInt); + } }