Printer
Native printer
TypeLang\Printer\NativeTypePrinter prints the closest type PHP itself
accepts: everything without a native equivalent is reduced to one. Use it
for generated code: a property type, a parameter or a return hint.
use TypeLang\Parser\TypeParser;use TypeLang\Printer\NativeTypePrinter;
$parser = new TypeParser();$printer = new NativeTypePrinter();
$printer->print($parser->parse('non-empty-list<positive-int>|null'));// array|nullConversion rules
Section titled “Conversion rules”| TypeLang | Native | Rule |
|---|---|---|
array{id: int}, array<int> |
array |
shapes and arguments are dropped |
callable(int $a): void |
callable |
a callable loses its signature |
int[] |
iterable |
a list suffix |
Collection[Key] |
mixed |
an offset access |
Foo::BAR, Foo::* |
mixed |
constants and masks |
42, "foo", 3.14 |
int, string, float |
a literal becomes its type |
true, false, true│false |
bool |
|
?int |
int│null |
a nullable is a union with null |
$this |
self |
|
$arg is A ? B : C |
B│C |
a conditional is the union of branches |
int│mixed |
mixed |
a union with mixed |
Type aliases
Section titled “Type aliases”A name is replaced by the native type of its alias. The names of PHPStan, Psalm and Phan are built in, a name without an alias is printed as it is:
$printer->print($parser->parse('positive-int')); // int$printer->print($parser->parse('class-string')); // string$printer->print($parser->parse('non-empty-list')); // array$printer->print($parser->parse('App\User')); // App\UserAliases of your own are the first argument, the options are the second. They win over the built-in ones and are matched without regard to case:
$printer = new NativeTypePrinter( aliases: ['Money' => 'int'], options: new PrinterOptions(),);
$printer->print($parser->parse('Money')); // intAn alias may be added later, also to a union or an intersection:
$printer->addTypeAlias('uuid', 'string');$printer->addUnionTypeAlias('id', ['string', 'int']);$printer->addIntersectionTypeAlias('Collection', [ 'Traversable', 'Countable',]);
$printer->print($parser->parse('uuid')); // string$printer->print($parser->parse('id')); // int|string$printer->print($parser->parse('Collection')); // Countable&Traversable