Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow nullable constructor arguments. #24

Merged
merged 1 commit into from
Apr 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/Converter/DefaultConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ public function createObject(FixtureData $fixtureData)
$optional = (substr($arg, 0, 1) == '?');
$arg = ($optional) ? substr($arg, 1) : $arg;

if (!isset($data[$arg]) && !$optional) {
if (!\array_key_exists($arg, $data) && !$optional) {
throw new ConverterException(sprintf('Missing "%s" attribute', $arg));
}

if (isset($data[$arg])) {
if (\array_key_exists($arg, $data)) {
$value = $data[$arg];

if (is_string($value)) {
Expand Down
22 changes: 22 additions & 0 deletions tests/Converter/DefaultConverterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,26 @@ public function testDateTimeConstructor()
$this->assertEquals('test_name', $object->getName());
$this->assertInstanceOf('DateTime', $object->getDate());
}

public function testnullableCostructorArgument()
{
$fixture = new Fixture('test');
$fixture->setProperties(new ParameterBag([
'class' => User::class,
'constructor' => ['name', 'email'],
]));

$data = new FixtureData('test', [
'name' => 'test_name',
'email' => null,
]);

$data->setFixture($fixture);

$object = $this->converter->createObject($data);

$this->assertInstanceOf(User::class, $object);
$this->assertEquals('test_name', $object->getName());
$this->assertNull($object->getEmail());
}
}
6 changes: 3 additions & 3 deletions tests/TestObjects/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class User
private $groups = [];
private $birthdate;

public function __construct(string $name, string $email)
public function __construct(string $name, ?string $email)
{
$this->name = $name;
$this->email = $email;
Expand All @@ -30,12 +30,12 @@ public function setName(string $name): void
$this->name = $name;
}

public function getEmail(): string
public function getEmail(): ?string
{
return $this->email;
}

public function setEmail(string $email): void
public function setEmail(?string $email): void
{
$this->email = $email;
}
Expand Down