Skip to content
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ vendor/
composer.lock
.php-cs-fixer.cache
.phpunit.result.cache
tests/cache/
18 changes: 15 additions & 3 deletions src/Transformer/NullableTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,21 @@ public function transform(Expr $input, Expr $target, PropertyMapping $propertyMa
$itemStatements[] = new Stmt\Expression(new $assignClass($newOutput, $output));
}

$statements[] = new Stmt\If_(new Expr\BinaryOp\NotIdentical(new Expr\ConstFetch(new Name('null')), $input), [
'stmts' => $itemStatements,
]);
if ($input instanceof Expr\ArrayDimFetch) {
/*
* if `$input` is an array access, let's validate if the array key exists and is not null:
*
* if (isset($value['key'])) {
*/
$statements[] = new Stmt\If_(new Expr\Isset_([$input]), ['stmts' => $itemStatements]);
} else {
/*
* otherwise, let's check the value is not null:
*
* if ($input !== null) {
*/
$statements[] = new Stmt\If_(new Expr\BinaryOp\NotIdentical(new Expr\ConstFetch(new Name('null')), $input), ['stmts' => $itemStatements]);
}

return [$newOutput ?? $output, $statements];
}
Expand Down
9 changes: 9 additions & 0 deletions tests/AutoMapperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use AutoMapper\Tests\Fixtures\AddressType;
use AutoMapper\Tests\Fixtures\AddressWithEnum;
use AutoMapper\Tests\Fixtures\ClassWithMapToContextAttribute;
use AutoMapper\Tests\Fixtures\ClassWithNullablePropertyInConstructor;
use AutoMapper\Tests\Fixtures\ClassWithPrivateProperty;
use AutoMapper\Tests\Fixtures\Fish;
use AutoMapper\Tests\Fixtures\ObjectWithDateTime;
Expand Down Expand Up @@ -1207,4 +1208,12 @@ public function testItCanDisablePrivatePropertiesMapping(): void
$this->autoMapper->map(new ClassWithPrivateProperty('foo'), 'array')
);
}

public function testItCanMapFromArrayWithMissingNullableProperty(): void
{
self::assertEquals(
new ClassWithNullablePropertyInConstructor(foo: 1),
$this->autoMapper->map(['foo' => 1], ClassWithNullablePropertyInConstructor::class)
);
}
}
12 changes: 12 additions & 0 deletions tests/Fixtures/ClassWithNullablePropertyInConstructor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

namespace AutoMapper\Tests\Fixtures;

readonly class ClassWithNullablePropertyInConstructor
{
public function __construct(public int $foo, public int|null $bar = null)
{
}
}