xref: /PHP-Parser/README.md (revision 23c79fbb)
1PHP Parser
2==========
3
4[![Coverage Status](https://coveralls.io/repos/github/nikic/PHP-Parser/badge.svg?branch=master)](https://coveralls.io/github/nikic/PHP-Parser?branch=master)
5
6This is a PHP parser written in PHP. Its purpose is to simplify static code analysis and
7manipulation.
8
9[**Documentation for version 5.x**][doc_master] (current; for running on PHP >= 7.4; for parsing PHP 7.0 to PHP 8.4, with limited support for parsing PHP 5.x).
10
11[Documentation for version 4.x][doc_4_x] (supported; for running on PHP >= 7.0; for parsing PHP 5.2 to PHP 8.3).
12
13Features
14--------
15
16The main features provided by this library are:
17
18 * Parsing PHP 7, and PHP 8 code into an abstract syntax tree (AST).
19   * Invalid code can be parsed into a partial AST.
20   * The AST contains accurate location information.
21 * Dumping the AST in human-readable form.
22 * Converting an AST back to PHP code.
23   * Formatting can be preserved for partially changed ASTs.
24 * Infrastructure to traverse and modify ASTs.
25 * Resolution of namespaced names.
26 * Evaluation of constant expressions.
27 * Builders to simplify AST construction for code generation.
28 * Converting an AST into JSON and back.
29
30Quick Start
31-----------
32
33Install the library using [composer](https://getcomposer.org):
34
35    php composer.phar require nikic/php-parser
36
37Parse some PHP code into an AST and dump the result in human-readable form:
38
39```php
40<?php
41use PhpParser\Error;
42use PhpParser\NodeDumper;
43use PhpParser\ParserFactory;
44
45$code = <<<'CODE'
46<?php
47
48function test($foo)
49{
50    var_dump($foo);
51}
52CODE;
53
54$parser = (new ParserFactory())->createForNewestSupportedVersion();
55try {
56    $ast = $parser->parse($code);
57} catch (Error $error) {
58    echo "Parse error: {$error->getMessage()}\n";
59    return;
60}
61
62$dumper = new NodeDumper;
63echo $dumper->dump($ast) . "\n";
64```
65
66This dumps an AST looking something like this:
67
68```
69array(
70    0: Stmt_Function(
71        attrGroups: array(
72        )
73        byRef: false
74        name: Identifier(
75            name: test
76        )
77        params: array(
78            0: Param(
79                attrGroups: array(
80                )
81                flags: 0
82                type: null
83                byRef: false
84                variadic: false
85                var: Expr_Variable(
86                    name: foo
87                )
88                default: null
89            )
90        )
91        returnType: null
92        stmts: array(
93            0: Stmt_Expression(
94                expr: Expr_FuncCall(
95                    name: Name(
96                        name: var_dump
97                    )
98                    args: array(
99                        0: Arg(
100                            name: null
101                            value: Expr_Variable(
102                                name: foo
103                            )
104                            byRef: false
105                            unpack: false
106                        )
107                    )
108                )
109            )
110        )
111    )
112)
113```
114
115Let's traverse the AST and perform some kind of modification. For example, drop all function bodies:
116
117```php
118use PhpParser\Node;
119use PhpParser\Node\Stmt\Function_;
120use PhpParser\NodeTraverser;
121use PhpParser\NodeVisitorAbstract;
122
123$traverser = new NodeTraverser();
124$traverser->addVisitor(new class extends NodeVisitorAbstract {
125    public function enterNode(Node $node) {
126        if ($node instanceof Function_) {
127            // Clean out the function body
128            $node->stmts = [];
129        }
130    }
131});
132
133$ast = $traverser->traverse($ast);
134echo $dumper->dump($ast) . "\n";
135```
136
137This gives us an AST where the `Function_::$stmts` are empty:
138
139```
140array(
141    0: Stmt_Function(
142        attrGroups: array(
143        )
144        byRef: false
145        name: Identifier(
146            name: test
147        )
148        params: array(
149            0: Param(
150                attrGroups: array(
151                )
152                type: null
153                byRef: false
154                variadic: false
155                var: Expr_Variable(
156                    name: foo
157                )
158                default: null
159            )
160        )
161        returnType: null
162        stmts: array(
163        )
164    )
165)
166```
167
168Finally, we can convert the new AST back to PHP code:
169
170```php
171use PhpParser\PrettyPrinter;
172
173$prettyPrinter = new PrettyPrinter\Standard;
174echo $prettyPrinter->prettyPrintFile($ast);
175```
176
177This gives us our original code, minus the `var_dump()` call inside the function:
178
179```php
180<?php
181
182function test($foo)
183{
184}
185```
186
187For a more comprehensive introduction, see the documentation.
188
189Documentation
190-------------
191
192 1. [Introduction](doc/0_Introduction.markdown)
193 2. [Usage of basic components](doc/2_Usage_of_basic_components.markdown)
194
195Component documentation:
196
197 * [Walking the AST](doc/component/Walking_the_AST.markdown)
198   * Node visitors
199   * Modifying the AST from a visitor
200   * Short-circuiting traversals
201   * Interleaved visitors
202   * Simple node finding API
203   * Parent and sibling references
204 * [Name resolution](doc/component/Name_resolution.markdown)
205   * Name resolver options
206   * Name resolution context
207 * [Pretty printing](doc/component/Pretty_printing.markdown)
208   * Converting AST back to PHP code
209   * Customizing formatting
210   * Formatting-preserving code transformations
211 * [AST builders](doc/component/AST_builders.markdown)
212   * Fluent builders for AST nodes
213 * [Lexer](doc/component/Lexer.markdown)
214   * Emulation
215   * Tokens, positions and attributes
216 * [Error handling](doc/component/Error_handling.markdown)
217   * Column information for errors
218   * Error recovery (parsing of syntactically incorrect code)
219 * [Constant expression evaluation](doc/component/Constant_expression_evaluation.markdown)
220   * Evaluating constant/property/etc initializers
221   * Handling errors and unsupported expressions
222 * [JSON representation](doc/component/JSON_representation.markdown)
223   * JSON encoding and decoding of ASTs
224 * [Performance](doc/component/Performance.markdown)
225   * Disabling Xdebug
226   * Reusing objects
227   * Garbage collection impact
228 * [Frequently asked questions](doc/component/FAQ.markdown)
229   * Parent and sibling references
230
231 [doc_3_x]: https://github.com/nikic/PHP-Parser/tree/3.x/doc
232 [doc_4_x]: https://github.com/nikic/PHP-Parser/tree/4.x/doc
233 [doc_master]: https://github.com/nikic/PHP-Parser/tree/master/doc
234