Skip to content

Commit

Permalink
Merge pull request #4 from rstgroup/nullable-arguments-without-defaul…
Browse files Browse the repository at this point in the history
…t-value

Pass null for nullable parameter without default value
  • Loading branch information
snapshotpl authored Aug 2, 2018
2 parents 9395342 + 31f9b61 commit 2a362f2
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Builder/Reflection.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ private function collect(ReflectionMethod $constructor, array $data): iterable
if ($parameter->isDefaultValueAvailable()) {
yield $parameter->getDefaultValue();
}

if ($parameter->allowsNull()) {
yield null;
}
}
}

Expand Down
17 changes: 17 additions & 0 deletions test/SimpleNullableConstructor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php declare(strict_types=1);

namespace RstGroup\ObjectBuilder\Test;

class SimpleNullableConstructor
{
public $someInt;
public $someString1;
public $someString2;

public function __construct(string $someString1, ?int $someInt, string $someString2)
{
$this->someInt = $someInt;
$this->someString1 = $someString1;
$this->someString2 = $someString2;
}
}
19 changes: 19 additions & 0 deletions test/unit/Builder/ReflectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
}

0 comments on commit 2a362f2

Please sign in to comment.