Dumping and Manipulating the AST of Expressions
Warning: You are browsing the documentation for Symfony 3.x, which is no longer maintained.
Read the updated version of this page for Symfony 7.2 (the current stable version).
Manipulating or inspecting the expressions created with the ExpressionLanguage component is difficult because they are plain strings. A better approach is to turn those expressions into an AST. In computer science, AST (Abstract Syntax Tree) is "a tree representation of the structure of source code written in a programming language". In Symfony, a ExpressionLanguage AST is a set of nodes that contain PHP classes representing the given expression.
Dumping the AST
Call the getNodes() method after parsing any expression to get its AST:
1 2 3 4 5 6 7 8 9 10 11 12
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
$ast = (new ExpressionLanguage())
->parse('1 + 2', [])
->getNodes()
;
// dump the AST nodes for inspection
var_dump($ast);
// dump the AST nodes as a string representation
$astAsString = $ast->dump();
Manipulating the AST
The nodes of the AST can also be dumped into a PHP array of nodes to allow manipulating them. Call the toArray() method to turn the AST into an array:
1 2 3 4 5 6 7
// ...
$astAsArray = (new ExpressionLanguage())
->parse('1 + 2', [])
->getNodes()
->toArray()
;