Skip to content

Commit

Permalink
support nullable types with union syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
JanTvrdik committed Aug 8, 2023
1 parent 0e5669c commit 2579f60
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Compiler/MapperFactory/DefaultMapperCompilerFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
use PHPStan\PhpDocParser\Lexer\Lexer;
use PHPStan\PhpDocParser\Parser\PhpDocParser;
use PHPStan\PhpDocParser\Parser\TokenIterator;
Expand Down Expand Up @@ -57,6 +58,7 @@
use function count;
use function enum_exists;
use function interface_exists;
use function strcasecmp;
use function strtolower;
use function substr;

Expand Down Expand Up @@ -175,6 +177,23 @@ public function create(TypeNode $type, array $options = []): MapperCompiler
return new MapArrayShape($items, $type->sealed);
}

if ($type instanceof UnionTypeNode) {
$isNullable = false;
$subTypesWithoutNull = [];

foreach ($type->types as $subType) {
if ($subType instanceof IdentifierTypeNode && strcasecmp($subType->name, 'null') === 0) {
$isNullable = true;
} else {
$subTypesWithoutNull[] = $subType;
}
}

if ($isNullable && count($subTypesWithoutNull) === 1) {
return new MapNullable($this->createInner($subTypesWithoutNull[0], $options));
}
}

throw CannotCreateMapperCompilerException::fromType($type);
}

Expand Down
12 changes: 12 additions & 0 deletions tests/Compiler/MapperFactory/DefaultMapperCompilerFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,18 @@ public static function provideCreateOkData(): iterable
new MapString(),
];

yield '?int' => [
'?int',
[],
new MapNullable(new MapInt()),
];

yield 'int|null' => [
'int|null',
[],
new MapNullable(new MapInt()),
];

yield 'int[]' => [
'int[]',
[],
Expand Down

0 comments on commit 2579f60

Please sign in to comment.