Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages showcasing Symfony with Docker, APIs, queues & async tasks, Webpack, SPAs, etc.


You are browsing the documentation for Symfony 3.4 which is not maintained anymore.

Consider upgrading your projects to Symfony 5.2.

Dumping and Manipulating the AST of Expressions

3.4 version

Dumping and Manipulating the AST of Expressions

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:

use Symfony\Component\ExpressionLanguage\ExpressionLanguage;

$ast = (new ExpressionLanguage())
    ->parse('1 + 2', [])

// dump the AST nodes for inspection

// 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:

// ...

$astAsArray = (new ExpressionLanguage())
    ->parse('1 + 2', [])

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.