Skip to content

Commit

Permalink
Add NullType & LiteralBooleanType support to TypeHelper::createTypeFr…
Browse files Browse the repository at this point in the history
…omTypeNode() (#708)
  • Loading branch information
leo108 authored Feb 8, 2025
1 parent f5f9b22 commit 544fa34
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/Support/Type/TypeHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ public static function createTypeFromTypeNode(Node $typeNode)
);
}

if ($typeNode->name === 'null') {
return new NullType;
}

if (in_array($typeNode->name, ['true', 'false'])) {
return new LiteralBooleanType($typeNode->name === 'true');
}

return new ObjectType($typeNode->toString());
}

Expand Down
23 changes: 23 additions & 0 deletions tests/Support/Type/TypeHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Dedoc\Scramble\Tests\Support\Type;

use Dedoc\Scramble\Support\Type\TypeHelper;
use PhpParser\Node;

test('create type from value', function ($value, string $expectedType) {
$type = TypeHelper::createTypeFromValue($value);
Expand All @@ -23,6 +24,28 @@
expect($type->toString())->toBe('list{Dedoc\Scramble\Tests\Support\Type\Foo_TypeHelperTest::Foo, Dedoc\Scramble\Tests\Support\Type\Foo_TypeHelperTest::Bar}');
});

test('create type from type node', function ($node, string $expectedType) {
$type = TypeHelper::createTypeFromTypeNode($node);

expect($type->toString())->toBe($expectedType);
})->with([
[new Node\Identifier('int'), 'int'],
[new Node\Identifier('string'), 'string'],
[new Node\Identifier('bool'), 'boolean'],
[new Node\Identifier('true'), 'boolean(true)'],
[new Node\Identifier('false'), 'boolean(false)'],
[new Node\Identifier('float'), 'float'],
[new Node\Identifier('array'), 'array<mixed>'],
[new Node\Identifier('null'), 'null'],
[new Node\Name('App\\Models\\User'), 'App\\Models\\User'],
[new Node\NullableType(new Node\Identifier('string')), 'null|string'],
[new Node\UnionType([
new Node\Identifier('int'),
new Node\Identifier('string'),
new Node\Identifier('null'),
]), 'int|string|null'],
]);

enum Foo_TypeHelperTest: string
{
case Foo = 'f';
Expand Down

0 comments on commit 544fa34

Please sign in to comment.