Documentation

PrettyPrinterAbstract
in package
implements PrettyPrinter

AbstractYes

Table of Contents

Interfaces

PrettyPrinter

Constants

FIXUP_BRACED_NAME  = 6
FIXUP_CALL_LHS  = 3
FIXUP_DEREF_LHS  = 4
FIXUP_ENCAPSED  = 8
FIXUP_NEW  = 9
FIXUP_PREC_LEFT  = 0
FIXUP_PREC_RIGHT  = 1
FIXUP_PREC_UNARY  = 2
FIXUP_STATIC_DEREF_LHS  = 5
FIXUP_VAR_BRACED_NAME  = 7
MAX_PRECEDENCE  = 1000

Properties

$canUseSemicolonNamespaces  : bool
$docStringEndToken  : string|null
$emptyListInsertionMap  : array<string, array{: int|string|null, : string, : string}>
$fixupMap  : array<string, array<string, int>>
$indentLevel  : int
$insertionMap  : array<string, array{: int|string|null, : bool, : string|null, : string|null}>
$labelCharMap  : array<string, bool>
$listInsertionMap  : array<string, string>
$modifierChangeMap  : array<string, array{: string, : int}>
$newline  : string
$nl  : string
$nodeListDiffer  : Differ<string|int, Node>
$origTokens  : TokenStream|null
$phpVersion  : PhpVersion
$precedenceMap  : array<class-string, array{: int, : int, : int}>
$removalMap  : array<string, array{left?: int|string, right?: int|string}>
$shortArraySyntax  : bool

Methods

__construct()  : mixed
Creates a pretty printer instance using the given options.
prettyPrint()  : string
Pretty prints an array of statements.
prettyPrintExpr()  : string
Pretty prints an expression.
prettyPrintFile()  : string
Pretty prints a file of statements (includes the opening <?php tag if it is required).
printFormatPreserving()  : string
Perform a format-preserving pretty print of an AST.
callLhsRequiresParens()  : bool
Determines whether the LHS of a call must be wrapped in parenthesis.
dereferenceLhsRequiresParens()  : bool
Determines whether the LHS of an array/object operation must be wrapped in parentheses.
handleMagicTokens()  : string
Handles (and removes) doc-string-end tokens.
indent()  : void
Increase indentation level.
initializeEmptyListInsertionMap()  : void
initializeFixupMap()  : void
Lazily initializes fixup map.
initializeInsertionMap()  : void
initializeLabelCharMap()  : void
Lazily initializes label char map.
initializeListInsertionMap()  : void
initializeModifierChangeMap()  : void
initializeNodeListDiffer()  : void
Lazily initializes node list differ.
initializeRemovalMap()  : void
Lazily initializes the removal map.
isMultiline()  : bool
Determine whether a list of nodes uses multiline formatting.
newOperandRequiresParens()  : bool
Determines whether an expression used in "new" or "instanceof" requires parentheses.
outdent()  : void
Decrease indentation level.
p()  : string
Pretty prints a node.
pArray()  : null|string
Perform a format-preserving pretty print of an array.
pCommaSeparated()  : string
Pretty prints an array of nodes and implodes the printed values with commas.
pCommaSeparatedMultiline()  : string
Pretty prints a comma-separated list of nodes in multiline style, including comments.
pComments()  : string
Prints reformatted text of the passed comments.
pFallback()  : string
pFixup()  : string
Print node with fixups.
pImplode()  : string
Pretty prints an array of nodes and implodes the printed values.
pInfixOp()  : string
Pretty-print an infix operation while taking precedence into account.
pModifiers()  : string
Print modifiers, including trailing whitespace.
pPostfixOp()  : string
Pretty-print a postfix operation while taking precedence into account.
pPrefixOp()  : string
Pretty-print a prefix operation while taking precedence into account.
preprocessNodes()  : void
Preprocesses the top-level nodes to initialize pretty printer state.
pStatic()  : string
pStmts()  : string
Pretty prints an array of nodes (statements) and indents them optionally.
resetState()  : void
Reset pretty printing state.
safeAppend()  : void
Appends to a string, ensuring whitespace between label characters.
setIndentLevel()  : void
Set indentation level
staticDereferenceLhsRequiresParens()  : bool
Determines whether the LHS of a static operation must be wrapped in parentheses.

Constants

Properties

$canUseSemicolonNamespaces

protected bool $canUseSemicolonNamespaces

Whether semicolon namespaces can be used (i.e. no global namespace is used)

$docStringEndToken

protected string|null $docStringEndToken

Token placed at end of doc string to ensure it is followed by a newline. Null if flexible doc strings are used.

$emptyListInsertionMap

protected array<string, array{: int|string|null, : string, : string}> $emptyListInsertionMap

$fixupMap

protected array<string, array<string, int>> $fixupMap

Map from token classes and subnode names to FIXUP_* constants. This is used during format-preserving prints to place additional parens/braces if necessary.

$insertionMap

protected array<string, array{: int|string|null, : bool, : string|null, : string|null}> $insertionMap

Map from "{$node->getType()}->{$subNode}" to [$find, $beforeToken, $extraLeft, $extraRight]. $find is an optional token after which the insertion occurs. $extraLeft/Right are optionally added before/after the main insertions.

$labelCharMap

protected array<string, bool> $labelCharMap

Map determining whether a certain character is a label character

$listInsertionMap

protected array<string, string> $listInsertionMap

Map From "{$class}->{$subNode}" to string that should be inserted between elements of this list subnode.

$modifierChangeMap

protected array<string, array{: string, : int}> $modifierChangeMap

Map from "{$class}->{$subNode}" to [$printFn, $token] where $printFn is the function to print the modifiers and $token is the token before which the modifiers should be reprinted.

$origTokens

protected TokenStream|null $origTokens

Original tokens for use in format-preserving pretty print

$precedenceMap

protected array<class-string, array{: int, : int, : int}> $precedenceMap = [ // [precedence, precedenceLHS, precedenceRHS] // Where the latter two are the precedences to use for the LHS and RHS of a binary operator, // where 1 is added to one of the sides depending on associativity. This information is not // used for unary operators and set to -1. \PhpParser\Node\Expr\Clone_::class => [-10, 0, 1], \PhpParser\Node\Expr\BinaryOp\Pow::class => [0, 0, 1], \PhpParser\Node\Expr\BitwiseNot::class => [10, -1, -1], \PhpParser\Node\Expr\UnaryPlus::class => [10, -1, -1], \PhpParser\Node\Expr\UnaryMinus::class => [10, -1, -1], \PhpParser\Node\Expr\Cast\Int_::class => [10, -1, -1], \PhpParser\Node\Expr\Cast\Double::class => [10, -1, -1], \PhpParser\Node\Expr\Cast\String_::class => [10, -1, -1], \PhpParser\Node\Expr\Cast\Array_::class => [10, -1, -1], \PhpParser\Node\Expr\Cast\Object_::class => [10, -1, -1], \PhpParser\Node\Expr\Cast\Bool_::class => [10, -1, -1], \PhpParser\Node\Expr\Cast\Unset_::class => [10, -1, -1], \PhpParser\Node\Expr\ErrorSuppress::class => [10, -1, -1], \PhpParser\Node\Expr\Instanceof_::class => [20, -1, -1], \PhpParser\Node\Expr\BooleanNot::class => [30, -1, -1], \PhpParser\Node\Expr\BinaryOp\Mul::class => [40, 41, 40], \PhpParser\Node\Expr\BinaryOp\Div::class => [40, 41, 40], \PhpParser\Node\Expr\BinaryOp\Mod::class => [40, 41, 40], \PhpParser\Node\Expr\BinaryOp\Plus::class => [50, 51, 50], \PhpParser\Node\Expr\BinaryOp\Minus::class => [50, 51, 50], \PhpParser\Node\Expr\BinaryOp\Concat::class => [50, 51, 50], \PhpParser\Node\Expr\BinaryOp\ShiftLeft::class => [60, 61, 60], \PhpParser\Node\Expr\BinaryOp\ShiftRight::class => [60, 61, 60], \PhpParser\Node\Expr\BinaryOp\Smaller::class => [70, 70, 70], \PhpParser\Node\Expr\BinaryOp\SmallerOrEqual::class => [70, 70, 70], \PhpParser\Node\Expr\BinaryOp\Greater::class => [70, 70, 70], \PhpParser\Node\Expr\BinaryOp\GreaterOrEqual::class => [70, 70, 70], \PhpParser\Node\Expr\BinaryOp\Equal::class => [80, 80, 80], \PhpParser\Node\Expr\BinaryOp\NotEqual::class => [80, 80, 80], \PhpParser\Node\Expr\BinaryOp\Identical::class => [80, 80, 80], \PhpParser\Node\Expr\BinaryOp\NotIdentical::class => [80, 80, 80], \PhpParser\Node\Expr\BinaryOp\Spaceship::class => [80, 80, 80], \PhpParser\Node\Expr\BinaryOp\BitwiseAnd::class => [90, 91, 90], \PhpParser\Node\Expr\BinaryOp\BitwiseXor::class => [100, 101, 100], \PhpParser\Node\Expr\BinaryOp\BitwiseOr::class => [110, 111, 110], \PhpParser\Node\Expr\BinaryOp\BooleanAnd::class => [120, 121, 120], \PhpParser\Node\Expr\BinaryOp\BooleanOr::class => [130, 131, 130], \PhpParser\Node\Expr\BinaryOp\Coalesce::class => [140, 140, 141], \PhpParser\Node\Expr\Ternary::class => [150, -1, -1], \PhpParser\Node\Expr\Assign::class => [160, -1, -1], \PhpParser\Node\Expr\AssignRef::class => [160, -1, -1], \PhpParser\Node\Expr\AssignOp\Plus::class => [160, -1, -1], \PhpParser\Node\Expr\AssignOp\Minus::class => [160, -1, -1], \PhpParser\Node\Expr\AssignOp\Mul::class => [160, -1, -1], \PhpParser\Node\Expr\AssignOp\Div::class => [160, -1, -1], \PhpParser\Node\Expr\AssignOp\Concat::class => [160, -1, -1], \PhpParser\Node\Expr\AssignOp\Mod::class => [160, -1, -1], \PhpParser\Node\Expr\AssignOp\BitwiseAnd::class => [160, -1, -1], \PhpParser\Node\Expr\AssignOp\BitwiseOr::class => [160, -1, -1], \PhpParser\Node\Expr\AssignOp\BitwiseXor::class => [160, -1, -1], \PhpParser\Node\Expr\AssignOp\ShiftLeft::class => [160, -1, -1], \PhpParser\Node\Expr\AssignOp\ShiftRight::class => [160, -1, -1], \PhpParser\Node\Expr\AssignOp\Pow::class => [160, -1, -1], \PhpParser\Node\Expr\AssignOp\Coalesce::class => [160, -1, -1], \PhpParser\Node\Expr\YieldFrom::class => [170, -1, -1], \PhpParser\Node\Expr\Yield_::class => [175, -1, -1], \PhpParser\Node\Expr\Print_::class => [180, -1, -1], \PhpParser\Node\Expr\BinaryOp\LogicalAnd::class => [190, 191, 190], \PhpParser\Node\Expr\BinaryOp\LogicalXor::class => [200, 201, 200], \PhpParser\Node\Expr\BinaryOp\LogicalOr::class => [210, 211, 210], \PhpParser\Node\Expr\Include_::class => [220, -1, -1], \PhpParser\Node\Expr\ArrowFunction::class => [230, -1, -1], \PhpParser\Node\Expr\Throw_::class => [240, -1, -1], ]

$removalMap

protected array<string, array{left?: int|string, right?: int|string}> $removalMap

Map from "{$node->getType()}->{$subNode}" to ['left' => $l, 'right' => $r], where $l and $r specify the token type that needs to be stripped when removing this node.

$shortArraySyntax

protected bool $shortArraySyntax

Whether to use short array syntax if the node specifies no preference

Methods

__construct()

Creates a pretty printer instance using the given options.

public __construct([PhpVersion, newline?: string, shortArraySyntax?: bool} $options = [] ]) : mixed

Supported options:

  • PhpVersion $phpVersion: The PHP version to target (default to PHP 7.4). This option controls compatibility of the generated code with older PHP versions in cases where a simple stylistic choice exists (e.g. array() vs []). It is safe to pretty-print an AST for a newer PHP version while specifying an older target (but the result will of course not be compatible with the older version in that case).
  • string $newline: The newline style to use. Should be "\n" (default) or "\r\n".
  • bool $shortArraySyntax: Whether to use [] instead of array() as the default array syntax, if the node does not specify a format. Defaults to whether the phpVersion support short array syntax.
Parameters
$options : PhpVersion, newline?: string, shortArraySyntax?: bool} = []

Dictionary of formatting options

prettyPrint()

Pretty prints an array of statements.

public prettyPrint(array<string|int, Node$stmts) : string
Parameters
$stmts : array<string|int, Node>

Array of statements

Return values
string

Pretty printed statements

prettyPrintExpr()

Pretty prints an expression.

public prettyPrintExpr(Expr $node) : string
Parameters
$node : Expr

Expression node

Return values
string

Pretty printed node

prettyPrintFile()

Pretty prints a file of statements (includes the opening <?php tag if it is required).

public prettyPrintFile(array<string|int, Node$stmts) : string
Parameters
$stmts : array<string|int, Node>

Array of statements

Return values
string

Pretty printed statements

printFormatPreserving()

Perform a format-preserving pretty print of an AST.

public printFormatPreserving(array<string|int, Node$stmts, array<string|int, Node$origStmts, array<string|int, Token$origTokens) : string

The format preservation is best effort. For some changes to the AST the formatting will not be preserved (at least not locally).

In order to use this method a number of prerequisites must be satisfied:

  • The startTokenPos and endTokenPos attributes in the lexer must be enabled.
  • The CloningVisitor must be run on the AST prior to modification.
  • The original tokens must be provided, using the getTokens() method on the lexer.
Parameters
$stmts : array<string|int, Node>

Modified AST with links to original AST

$origStmts : array<string|int, Node>

Original AST with token offset information

$origTokens : array<string|int, Token>

Tokens of the original code

Return values
string

callLhsRequiresParens()

Determines whether the LHS of a call must be wrapped in parenthesis.

protected callLhsRequiresParens(Node $node) : bool
Parameters
$node : Node

LHS of a call

Return values
bool

Whether parentheses are required

dereferenceLhsRequiresParens()

Determines whether the LHS of an array/object operation must be wrapped in parentheses.

protected dereferenceLhsRequiresParens(Node $node) : bool
Parameters
$node : Node

LHS of dereferencing operation

Return values
bool

Whether parentheses are required

handleMagicTokens()

Handles (and removes) doc-string-end tokens.

protected handleMagicTokens(string $str) : string
Parameters
$str : string
Return values
string

initializeFixupMap()

Lazily initializes fixup map.

protected initializeFixupMap() : void

The fixup map is used to determine whether a certain subnode of a certain node may require some kind of "fixup" operation, e.g. the addition of parenthesis or braces.

initializeLabelCharMap()

Lazily initializes label char map.

protected initializeLabelCharMap() : void

The label char map determines whether a certain character may occur in a label.

initializeNodeListDiffer()

Lazily initializes node list differ.

protected initializeNodeListDiffer() : void

The node list differ is used to determine differences between two array subnodes.

initializeRemovalMap()

Lazily initializes the removal map.

protected initializeRemovalMap() : void

The removal map is used to determine which additional tokens should be removed when a certain node is replaced by null.

isMultiline()

Determine whether a list of nodes uses multiline formatting.

protected isMultiline(array<string|int, Node|null> $nodes) : bool
Parameters
$nodes : array<string|int, Node|null>

Node list

Return values
bool

Whether multiline formatting is used

newOperandRequiresParens()

Determines whether an expression used in "new" or "instanceof" requires parentheses.

protected newOperandRequiresParens(Node $node) : bool
Parameters
$node : Node

New or instanceof operand

Return values
bool

Whether parentheses are required

p()

Pretty prints a node.

protected p(Node $node[, int $precedence = self::MAX_PRECEDENCE ][, int $lhsPrecedence = self::MAX_PRECEDENCE ][, bool $parentFormatPreserved = false ]) : string

This method also handles formatting preservation for nodes.

Parameters
$node : Node

Node to be pretty printed

$precedence : int = self::MAX_PRECEDENCE

Precedence of parent operator

$lhsPrecedence : int = self::MAX_PRECEDENCE

Precedence for unary operator on LHS of binary operator

$parentFormatPreserved : bool = false

Whether parent node has preserved formatting

Return values
string

Pretty printed node

pArray()

Perform a format-preserving pretty print of an array.

protected pArray(array<string|int, Node$nodes, array<string|int, Node$origNodes, int &$pos, int $indentAdjustment, string $parentNodeClass, string $subNodeName, null|int $fixup) : null|string
Parameters
$nodes : array<string|int, Node>

New nodes

$origNodes : array<string|int, Node>

Original nodes

$pos : int

Current token position (updated by reference)

$indentAdjustment : int

Adjustment for indentation

$parentNodeClass : string

Class of the containing node.

$subNodeName : string

Name of array subnode.

$fixup : null|int

Fixup information for array item nodes

Return values
null|string

Result of pretty print or null if cannot preserve formatting

pCommaSeparated()

Pretty prints an array of nodes and implodes the printed values with commas.

protected pCommaSeparated(array<string|int, Node$nodes) : string
Parameters
$nodes : array<string|int, Node>

Array of Nodes to be printed

Return values
string

Comma separated pretty printed nodes

pCommaSeparatedMultiline()

Pretty prints a comma-separated list of nodes in multiline style, including comments.

protected pCommaSeparatedMultiline(array<string|int, Node$nodes, bool $trailingComma) : string

The result includes a leading newline and one level of indentation (same as pStmts).

Parameters
$nodes : array<string|int, Node>

Array of Nodes to be printed

$trailingComma : bool

Whether to use a trailing comma

Return values
string

Comma separated pretty printed nodes in multiline style

pComments()

Prints reformatted text of the passed comments.

protected pComments(array<string|int, Comment$comments) : string
Parameters
$comments : array<string|int, Comment>

List of comments

Return values
string

Reformatted text of comments

pFallback()

protected pFallback(Node $node, int $precedence, int $lhsPrecedence) : string
Parameters
$node : Node
$precedence : int
$lhsPrecedence : int
Return values
string

pFixup()

Print node with fixups.

protected pFixup(int $fixup, Node $subNode, string|null $parentClass, int $subStartPos, int $subEndPos) : string

Fixups here refer to the addition of extra parentheses, braces or other characters, that are required to preserve program semantics in a certain context (e.g. to maintain precedence or because only certain expressions are allowed in certain places).

Parameters
$fixup : int

Fixup type

$subNode : Node

Subnode to print

$parentClass : string|null

Class of parent node

$subStartPos : int

Original start pos of subnode

$subEndPos : int

Original end pos of subnode

Return values
string

Result of fixed-up print of subnode

pImplode()

Pretty prints an array of nodes and implodes the printed values.

protected pImplode(array<string|int, Node$nodes[, string $glue = '' ]) : string
Parameters
$nodes : array<string|int, Node>

Array of Nodes to be printed

$glue : string = ''

Character to implode with

Return values
string

Imploded pretty printed nodes> $pre

pInfixOp()

Pretty-print an infix operation while taking precedence into account.

protected pInfixOp(string $class, Node $leftNode, string $operatorString, Node $rightNode, int $precedence, int $lhsPrecedence) : string
Parameters
$class : string

Node class of operator

$leftNode : Node

Left-hand side node

$operatorString : string

String representation of the operator

$rightNode : Node

Right-hand side node

$precedence : int

Precedence of parent operator

$lhsPrecedence : int

Precedence for unary operator on LHS of binary operator

Return values
string

Pretty printed infix operation

pModifiers()

Print modifiers, including trailing whitespace.

protected pModifiers(int $modifiers) : string
Parameters
$modifiers : int

Modifier mask to print

Return values
string

Printed modifiers

pPostfixOp()

Pretty-print a postfix operation while taking precedence into account.

protected pPostfixOp(string $class, Node $node, string $operatorString, int $precedence, int $lhsPrecedence) : string
Parameters
$class : string

Node class of operator

$node : Node

Node

$operatorString : string

String representation of the operator

$precedence : int

Precedence of parent operator

$lhsPrecedence : int

Precedence for unary operator on LHS of binary operator

Return values
string

Pretty printed postfix operation

pPrefixOp()

Pretty-print a prefix operation while taking precedence into account.

protected pPrefixOp(string $class, string $operatorString, Node $node, int $precedence, int $lhsPrecedence) : string
Parameters
$class : string

Node class of operator

$operatorString : string

String representation of the operator

$node : Node

Node

$precedence : int

Precedence of parent operator

$lhsPrecedence : int

Precedence for unary operator on LHS of binary operator

Return values
string

Pretty printed prefix operation

preprocessNodes()

Preprocesses the top-level nodes to initialize pretty printer state.

protected preprocessNodes(array<string|int, Node$nodes) : void
Parameters
$nodes : array<string|int, Node>

Array of nodes

pStatic()

protected pStatic(bool $static) : string
Parameters
$static : bool
Return values
string

pStmts()

Pretty prints an array of nodes (statements) and indents them optionally.

protected pStmts(array<string|int, Node$nodes[, bool $indent = true ]) : string
Parameters
$nodes : array<string|int, Node>

Array of nodes

$indent : bool = true

Whether to indent the printed nodes

Return values
string

Pretty printed statements

safeAppend()

Appends to a string, ensuring whitespace between label characters.

protected safeAppend(string &$str, string $append) : void

Example: "echo" and "$x" result in "echo$x", but "echo" and "x" result in "echo x". Without safeAppend the result would be "echox", which does not preserve semantics.

Parameters
$str : string
$append : string

setIndentLevel()

Set indentation level

protected setIndentLevel(int $level) : void
Parameters
$level : int

Level in number of spaces

staticDereferenceLhsRequiresParens()

Determines whether the LHS of a static operation must be wrapped in parentheses.

protected staticDereferenceLhsRequiresParens(Node $node) : bool
Parameters
$node : Node

LHS of dereferencing operation

Return values
bool

Whether parentheses are required


        
On this page

Search results