Skip to content

Printer

Type printer component

The printer is the inverse of the parser: it turns a TypeLang\Type\TypeNode back into a string.

composer require type-lang/printer

Requirements:

  • PHP >= 8.1

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|null
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

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",
));

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.