Printer
Type printer component
The printer is the inverse of the parser: it turns a
TypeLang\Type\TypeNode back into a string.
Installation
Section titled “Installation”composer require type-lang/printerRequirements:
PHP >= 8.1
Quick start
Section titled “Quick start”Both printers implement TypeLang\Printer\TypePrinterInterface with a
single print() method:
use TypeLang\Parser\TypeParser;use TypeLang\Printer\NativeTypePrinter;use TypeLang\Printer\PrettyTypePrinter;
$type = new TypeParser()->parse('non-empty-list<positive-int>|null');
new PrettyTypePrinter()->print($type);// non-empty-list<positive-int>|null
new NativeTypePrinter()->print($type);// array|nullChoosing a printer
Section titled “Choosing a printer”| Pretty | Native | |
|---|---|---|
| Goal | the type as it is, for a human | valid PHP syntax, for code |
array{id: int} |
array{id: int} |
array |
int[] |
int[] |
iterable |
positive-int |
positive-int |
int |
Foo::BAR |
Foo::BAR |
mixed |
int<0, max> |
int<0, max> |
int |
$arg is null ? A : B |
($arg is null ? A : B) |
A│B |
?int |
?int |
int│null |
Formatting
Section titled “Formatting”Both printers take a TypeLang\Printer\PrinterOptions: line breaks,
indentation, spacing, the style of nullable types and lists. See the
options.
use TypeLang\Printer\PrettyTypePrinter;use TypeLang\Printer\PrinterOptions;
$printer = new PrettyTypePrinter(new PrinterOptions( newLine: "\r\n", indentation: "\t",));Error handling
Section titled “Error handling”A tree built by the parser is always printable. A node of a class the
printer does not know, such as a subclass of your own, throws a
NonPrintableNodeException. Every exception of the printer implements
TypeLang\Printer\Exception\PrinterExceptionInterface.