diff --git a/components/expression_language.rst b/components/expression_language.rst index ad7f3f924f6..dd3b0ff57f4 100644 --- a/components/expression_language.rst +++ b/components/expression_language.rst @@ -112,6 +112,12 @@ Caching The component provides some different caching strategies, read more about them in :doc:`/components/expression_language/caching`. +AST Dumping and Editing +----------------------- + +The AST (*Abstract Syntax Tree*) of expressions can be dumped and manipulated +as explained in :doc:`/components/expression_language/ast`. + Learn More ---------- diff --git a/components/expression_language/ast.rst b/components/expression_language/ast.rst new file mode 100644 index 00000000000..02bd0be8c4b --- /dev/null +++ b/components/expression_language/ast.rst @@ -0,0 +1,49 @@ +.. index:: + single: AST; ExpressionLanguage + single: AST; Abstract Syntax Tree + +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 :method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::getNodes` +method after parsing any expression to get its AST:: + + 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 :method:`Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage::toArray` +method to turn the AST into an array:: + + // ... + + $astAsArray = (new ExpressionLanguage()) + ->parse('1 + 2') + ->getNodes() + ->toArray() + ; + +.. _`AST`: https://en.wikipedia.org/wiki/Abstract_syntax_tree