File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change @@ -112,6 +112,12 @@ Caching
112112The component provides some different caching strategies, read more about them
113113in :doc: `/components/expression_language/caching `.
114114
115+ AST Dumping and Editing
116+ -----------------------
117+
118+ The AST (*Abstract Syntax Tree *) of expressions can be dumped and manipulated
119+ as explained in :doc: `/components/expression_language/ast `.
120+
115121Learn More
116122----------
117123
Original file line number Diff line number Diff line change 1+ .. index ::
2+ single: AST; ExpressionLanguage
3+ single: AST; Abstract Syntax Tree
4+
5+ Dumping and Manipulating the AST of Expressions
6+ ===============================================
7+
8+ Manipulating or inspecting the expressions created with the ExpressionLanguage
9+ component is difficult because they are plain strings. A better approach is to
10+ turn those expressions into an AST. In computer science, `AST `_ (*Abstract
11+ Syntax Tree *) is *"a tree representation of the structure of source code written
12+ in a programming language" *. In Symfony, a ExpressionLanguage AST is a set of
13+ nodes that contain PHP classes representing the given expression.
14+
15+ Dumping the AST
16+ ---------------
17+
18+ Call the :method: `Symfony\\ Component\\ ExpressionLanguage\\ ExpressionLanguage::getNodes `
19+ method after parsing any expression to get its AST::
20+
21+ use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
22+
23+ $ast = (new ExpressionLanguage())
24+ ->parse('1 + 2')
25+ ->getNodes()
26+ ;
27+
28+ // dump the AST nodes for inspection
29+ var_dump($ast);
30+
31+ // dump the AST nodes as a string representation
32+ $astAsString = $ast->dump();
33+
34+ Manipulating the AST
35+ --------------------
36+
37+ The nodes of the AST can also be dumped into a PHP array of nodes to allow
38+ manipulating them. Call the :method: `Symfony\\ Component\\ ExpressionLanguage\\ ExpressionLanguage::toArray `
39+ method to turn the AST into an array::
40+
41+ // ...
42+
43+ $astAsArray = (new ExpressionLanguage())
44+ ->parse('1 + 2')
45+ ->getNodes()
46+ ->toArray()
47+ ;
48+
49+ .. _`AST` : https://en.wikipedia.org/wiki/Abstract_syntax_tree
You can’t perform that action at this time.
0 commit comments