2011-11-10 11:40:11 +01:00
|
|
|
Usage of basic components
|
|
|
|
=========================
|
|
|
|
|
|
|
|
This document explains how to use the parser, the pretty printer and the node traverser.
|
|
|
|
|
|
|
|
Bootstrapping
|
|
|
|
-------------
|
|
|
|
|
2015-09-16 15:16:29 +02:00
|
|
|
To bootstrap the library, include the autoloader generated by composer:
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
```php
|
2014-09-12 13:51:17 +02:00
|
|
|
require 'path/to/vendor/autoload.php';
|
2011-11-12 19:28:53 +01:00
|
|
|
```
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2012-07-07 16:43:23 +02:00
|
|
|
Additionally you may want to set the `xdebug.max_nesting_level` ini option to a higher value:
|
|
|
|
|
|
|
|
```php
|
2015-02-13 15:04:00 +01:00
|
|
|
ini_set('xdebug.max_nesting_level', 3000);
|
2012-07-07 16:43:23 +02:00
|
|
|
```
|
|
|
|
|
2016-04-19 15:40:08 +02:00
|
|
|
This ensures that there will be no errors when traversing highly nested node trees. However, it is
|
|
|
|
preferable to disable XDebug completely, as it can easily make this library more than five times
|
|
|
|
slower.
|
2012-07-07 16:43:23 +02:00
|
|
|
|
2011-11-10 11:40:11 +01:00
|
|
|
Parsing
|
|
|
|
-------
|
|
|
|
|
2015-07-14 21:11:54 +02:00
|
|
|
In order to parse code, you first have to create a parser instance:
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
```php
|
2015-07-14 19:19:32 +02:00
|
|
|
use PhpParser\ParserFactory;
|
2015-07-14 21:11:54 +02:00
|
|
|
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
|
2014-09-12 00:20:22 +02:00
|
|
|
```
|
|
|
|
|
2015-07-14 19:19:32 +02:00
|
|
|
The factory accepts a kind argument, that determines how different PHP versions are treated:
|
|
|
|
|
|
|
|
Kind | Behavior
|
2015-07-14 20:13:26 +02:00
|
|
|
-----|---------
|
2015-07-14 19:19:32 +02:00
|
|
|
`ParserFactory::PREFER_PHP7` | Try to parse code as PHP 7. If this fails, try to parse it as PHP 5.
|
|
|
|
`ParserFactory::PREFER_PHP5` | Try to parse code as PHP 5. If this fails, try to parse it as PHP 7.
|
|
|
|
`ParserFactory::ONLY_PHP7` | Parse code as PHP 7.
|
|
|
|
`ParserFactory::ONLY_PHP5` | Parse code as PHP 5.
|
|
|
|
|
|
|
|
Unless you have strong reason to use something else, `PREFER_PHP7` is a reasonable default.
|
|
|
|
|
2015-07-14 21:11:54 +02:00
|
|
|
The `create()` method optionally accepts a `Lexer` instance as the second argument. Some use cases
|
|
|
|
that require customized lexers are discussed in the [lexer documentation](component/Lexer.markdown).
|
2014-09-12 00:20:22 +02:00
|
|
|
|
|
|
|
Subsequently you can pass PHP code (including the opening `<?php` tag) to the `parse` method in order to
|
|
|
|
create a syntax tree. If a syntax error is encountered, an `PhpParser\Error` exception will be thrown:
|
|
|
|
|
|
|
|
```php
|
2018-02-08 17:16:14 +01:00
|
|
|
<?php
|
2015-07-14 19:19:32 +02:00
|
|
|
use PhpParser\Error;
|
|
|
|
use PhpParser\ParserFactory;
|
2014-09-12 00:20:22 +02:00
|
|
|
|
2018-02-08 17:16:14 +01:00
|
|
|
$code = <<<'CODE'
|
|
|
|
<?php
|
|
|
|
function printLine($msg) {
|
|
|
|
echo $msg, "\n";
|
|
|
|
}
|
|
|
|
printLine('Hello World!!!');
|
|
|
|
CODE;
|
|
|
|
|
2015-07-14 21:11:54 +02:00
|
|
|
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
try {
|
2012-05-11 16:44:13 +02:00
|
|
|
$stmts = $parser->parse($code);
|
2014-09-12 00:20:22 +02:00
|
|
|
// $stmts is an array of statement nodes
|
2015-07-14 19:19:32 +02:00
|
|
|
} catch (Error $e) {
|
2011-11-12 19:28:53 +01:00
|
|
|
echo 'Parse Error: ', $e->getMessage();
|
|
|
|
}
|
|
|
|
```
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2014-09-12 00:20:22 +02:00
|
|
|
A parser instance can be reused to parse multiple files.
|
2012-02-21 19:02:04 +01:00
|
|
|
|
2018-02-08 17:16:14 +01:00
|
|
|
Node dumping
|
|
|
|
------------
|
|
|
|
|
|
|
|
To dump the abstact syntax tree in human readable form, a `NodeDumper` can be used:
|
|
|
|
|
|
|
|
```php
|
|
|
|
<?php
|
|
|
|
use PhpParser\NodeDumper;
|
|
|
|
|
|
|
|
$nodeDumper = new NodeDumper;
|
|
|
|
echo $nodeDumper->dump($stmts), "\n";
|
|
|
|
```
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2018-02-08 17:16:14 +01:00
|
|
|
For the sample code from the previous section, this will produce the following output:
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
```
|
|
|
|
array(
|
2018-02-08 17:16:14 +01:00
|
|
|
0: Stmt_Function(
|
|
|
|
byRef: false
|
|
|
|
name: Identifier(
|
|
|
|
name: printLine
|
|
|
|
)
|
|
|
|
params: array(
|
|
|
|
0: Param(
|
|
|
|
type: null
|
|
|
|
byRef: false
|
|
|
|
variadic: false
|
|
|
|
var: Expr_Variable(
|
|
|
|
name: msg
|
|
|
|
)
|
|
|
|
default: null
|
2011-11-12 19:28:53 +01:00
|
|
|
)
|
2018-02-08 17:16:14 +01:00
|
|
|
)
|
|
|
|
returnType: null
|
|
|
|
stmts: array(
|
|
|
|
0: Stmt_Echo(
|
|
|
|
exprs: array(
|
|
|
|
0: Expr_Variable(
|
|
|
|
name: msg
|
|
|
|
)
|
|
|
|
1: Scalar_String(
|
|
|
|
value:
|
|
|
|
|
2011-11-10 11:40:11 +01:00
|
|
|
)
|
|
|
|
)
|
2018-02-08 17:16:14 +01:00
|
|
|
)
|
|
|
|
)
|
|
|
|
)
|
|
|
|
1: Stmt_Expression(
|
|
|
|
expr: Expr_FuncCall(
|
|
|
|
name: Name(
|
|
|
|
parts: array(
|
|
|
|
0: printLine
|
|
|
|
)
|
|
|
|
)
|
|
|
|
args: array(
|
|
|
|
0: Arg(
|
|
|
|
value: Scalar_String(
|
|
|
|
value: Hello World!!!
|
|
|
|
)
|
|
|
|
byRef: false
|
|
|
|
unpack: false
|
2011-11-12 19:28:53 +01:00
|
|
|
)
|
2011-11-10 11:40:11 +01:00
|
|
|
)
|
|
|
|
)
|
|
|
|
)
|
2011-11-12 19:28:53 +01:00
|
|
|
)
|
|
|
|
```
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2018-02-08 17:16:14 +01:00
|
|
|
You can also use the `php-parse` script to obtain such a node dump by calling it either with a file
|
|
|
|
name or code string:
|
|
|
|
|
|
|
|
```sh
|
|
|
|
vendor/bin/php-parse file.php
|
|
|
|
vendor/bin/php-parse "<?php foo();"
|
|
|
|
```
|
|
|
|
|
|
|
|
This can be very helpful if you want to quickly check how certain syntax is represented in the AST.
|
|
|
|
|
|
|
|
Node tree structure
|
|
|
|
-------------------
|
|
|
|
|
|
|
|
Looking at the node dump above, you can see that `$stmts` for this example code is an array of two
|
|
|
|
nodes, a `Stmt_Function` and a `Stmt_Expression`. The corresponding class names are:
|
|
|
|
|
|
|
|
* `Stmt_Function -> PhpParser\Node\Stmt\Function_`
|
|
|
|
* `Stmt_Expression -> PhpParser\Node\Stmt\Expression`
|
|
|
|
|
|
|
|
The additional `_` at the end of the first class name is necessary, because `Function` is a
|
|
|
|
reserved keyword. Many node class names in this library have a trailing `_` to avoid clashing with
|
|
|
|
a keyword.
|
2011-11-10 11:40:11 +01:00
|
|
|
|
|
|
|
As PHP is a large language there are approximately 140 different nodes. In order to make work
|
|
|
|
with them easier they are grouped into three categories:
|
|
|
|
|
2014-02-06 20:50:01 +01:00
|
|
|
* `PhpParser\Node\Stmt`s are statement nodes, i.e. language constructs that do not return
|
2011-11-10 11:40:11 +01:00
|
|
|
a value and can not occur in an expression. For example a class definition is a statement.
|
|
|
|
It doesn't return a value and you can't write something like `func(class A {});`.
|
2014-02-06 20:50:01 +01:00
|
|
|
* `PhpParser\Node\Expr`s are expression nodes, i.e. language constructs that return a value
|
2011-11-10 11:40:11 +01:00
|
|
|
and thus can occur in other expressions. Examples of expressions are `$var`
|
2014-02-06 20:50:01 +01:00
|
|
|
(`PhpParser\Node\Expr\Variable`) and `func()` (`PhpParser\Node\Expr\FuncCall`).
|
|
|
|
* `PhpParser\Node\Scalar`s are nodes representing scalar values, like `'string'`
|
2015-03-21 18:54:52 +01:00
|
|
|
(`PhpParser\Node\Scalar\String_`), `0` (`PhpParser\Node\Scalar\LNumber`) or magic constants
|
2014-02-06 20:50:01 +01:00
|
|
|
like `__FILE__` (`PhpParser\Node\Scalar\MagicConst\File`). All `PhpParser\Node\Scalar`s extend
|
|
|
|
`PhpParser\Node\Expr`, as scalars are expressions, too.
|
|
|
|
* There are some nodes not in either of these groups, for example names (`PhpParser\Node\Name`)
|
|
|
|
and call arguments (`PhpParser\Node\Arg`).
|
|
|
|
|
2018-02-08 17:16:14 +01:00
|
|
|
The `Node\Stmt\Expression` node is somewhat confusing in that it contains both the terms "statement"
|
|
|
|
and "expression". This node distinguishes `expr`, which is a `Node\Expr`, from `expr;`, which is
|
|
|
|
an "expression statement" represented by `Node\Stmt\Expression` and containing `expr` as a sub-node.
|
2011-11-10 11:40:11 +01:00
|
|
|
|
|
|
|
Every node has a (possibly zero) number of subnodes. You can access subnodes by writing
|
2014-02-06 20:50:01 +01:00
|
|
|
`$node->subNodeName`. The `Stmt\Echo_` node has only one subnode `exprs`. So in order to access it
|
2014-09-12 00:20:22 +02:00
|
|
|
in the above example you would write `$stmts[0]->exprs`. If you wanted to access the name of the function
|
2011-11-10 11:40:11 +01:00
|
|
|
call, you would write `$stmts[0]->exprs[1]->name`.
|
|
|
|
|
2014-02-06 20:50:01 +01:00
|
|
|
All nodes also define a `getType()` method that returns the node type. The type is the class name
|
2014-02-12 17:47:34 +01:00
|
|
|
without the `PhpParser\Node\` prefix and `\` replaced with `_`. It also does not contain a trailing
|
2014-02-06 20:50:01 +01:00
|
|
|
`_` for reserved-keyword class names.
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2012-04-04 14:10:21 +02:00
|
|
|
It is possible to associate custom metadata with a node using the `setAttribute()` method. This data
|
|
|
|
can then be retrieved using `hasAttribute()`, `getAttribute()` and `getAttributes()`.
|
|
|
|
|
2012-05-11 16:44:13 +02:00
|
|
|
By default the lexer adds the `startLine`, `endLine` and `comments` attributes. `comments` is an array
|
2014-02-06 20:50:01 +01:00
|
|
|
of `PhpParser\Comment[\Doc]` instances.
|
2012-05-11 16:44:13 +02:00
|
|
|
|
|
|
|
The start line can also be accessed using `getLine()`/`setLine()` (instead of `getAttribute('startLine')`).
|
|
|
|
The last doc comment from the `comments` attribute can be obtained using `getDocComment()`.
|
|
|
|
|
2011-11-10 11:40:11 +01:00
|
|
|
Pretty printer
|
|
|
|
--------------
|
|
|
|
|
|
|
|
The pretty printer component compiles the AST back to PHP code. As the parser does not retain formatting
|
|
|
|
information the formatting is done using a specified scheme. Currently there is only one scheme available,
|
2014-02-06 20:50:01 +01:00
|
|
|
namely `PhpParser\PrettyPrinter\Standard`.
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
```php
|
2015-07-14 19:19:32 +02:00
|
|
|
use PhpParser\Error;
|
|
|
|
use PhpParser\ParserFactory;
|
|
|
|
use PhpParser\PrettyPrinter;
|
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
$code = "<?php echo 'Hi ', hi\\getTarget();";
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2015-07-14 19:19:32 +02:00
|
|
|
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
|
|
|
|
$prettyPrinter = new PrettyPrinter\Standard;
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
try {
|
|
|
|
// parse
|
2012-05-11 16:44:13 +02:00
|
|
|
$stmts = $parser->parse($code);
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
// change
|
|
|
|
$stmts[0] // the echo statement
|
|
|
|
->exprs // sub expressions
|
|
|
|
[0] // the first of them (the string node)
|
|
|
|
->value // it's value, i.e. 'Hi '
|
2014-09-12 00:20:22 +02:00
|
|
|
= 'Hello '; // change to 'Hello '
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
// pretty print
|
2014-09-12 00:20:22 +02:00
|
|
|
$code = $prettyPrinter->prettyPrint($stmts);
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
echo $code;
|
2015-07-14 19:19:32 +02:00
|
|
|
} catch (Error $e) {
|
2011-11-12 19:28:53 +01:00
|
|
|
echo 'Parse Error: ', $e->getMessage();
|
|
|
|
}
|
|
|
|
```
|
2011-11-10 11:40:11 +01:00
|
|
|
|
|
|
|
The above code will output:
|
|
|
|
|
2014-09-12 00:20:22 +02:00
|
|
|
<?php echo 'Hello ', hi\getTarget();
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2014-02-06 20:50:01 +01:00
|
|
|
As you can see the source code was first parsed using `PhpParser\Parser->parse()`, then changed and then
|
|
|
|
again converted to code using `PhpParser\PrettyPrinter\Standard->prettyPrint()`.
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2014-02-06 20:50:01 +01:00
|
|
|
The `prettyPrint()` method pretty prints a statements array. It is also possible to pretty print only a
|
|
|
|
single expression using `prettyPrintExpr()`.
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2014-09-12 00:20:22 +02:00
|
|
|
The `prettyPrintFile()` method can be used to print an entire file. This will include the opening `<?php` tag
|
|
|
|
and handle inline HTML as the first/last statement more gracefully.
|
2014-04-19 22:30:20 +02:00
|
|
|
|
2011-11-10 11:40:11 +01:00
|
|
|
Node traversation
|
|
|
|
-----------------
|
|
|
|
|
|
|
|
The above pretty printing example used the fact that the source code was known and thus it was easy to
|
|
|
|
write code that accesses a certain part of a node tree and changes it. Normally this is not the case.
|
|
|
|
Usually you want to change / analyze code in a generic way, where you don't know how the node tree is
|
|
|
|
going to look like.
|
|
|
|
|
|
|
|
For this purpose the parser provides a component for traversing and visiting the node tree. The basic
|
2014-02-06 20:50:01 +01:00
|
|
|
structure of a program using this `PhpParser\NodeTraverser` looks like this:
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
```php
|
2015-07-14 19:19:32 +02:00
|
|
|
use PhpParser\NodeTraverser;
|
|
|
|
use PhpParser\ParserFactory;
|
|
|
|
use PhpParser\PrettyPrinter;
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2015-07-14 19:19:32 +02:00
|
|
|
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
|
|
|
|
$traverser = new NodeTraverser;
|
|
|
|
$prettyPrinter = new PrettyPrinter\Standard;
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
// add your visitor
|
|
|
|
$traverser->addVisitor(new MyNodeVisitor);
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
try {
|
2014-09-12 00:20:22 +02:00
|
|
|
$code = file_get_contents($fileName);
|
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
// parse
|
2012-05-11 16:44:13 +02:00
|
|
|
$stmts = $parser->parse($code);
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
// traverse
|
|
|
|
$stmts = $traverser->traverse($stmts);
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
// pretty print
|
2014-09-12 00:20:22 +02:00
|
|
|
$code = $prettyPrinter->prettyPrintFile($stmts);
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
echo $code;
|
2014-02-06 20:50:01 +01:00
|
|
|
} catch (PhpParser\Error $e) {
|
2011-11-12 19:28:53 +01:00
|
|
|
echo 'Parse Error: ', $e->getMessage();
|
|
|
|
}
|
|
|
|
```
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2014-09-12 00:20:22 +02:00
|
|
|
The corresponding node visitor might look like this:
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
```php
|
2014-09-12 00:20:22 +02:00
|
|
|
use PhpParser\Node;
|
2015-07-14 19:19:32 +02:00
|
|
|
use PhpParser\NodeVisitorAbstract;
|
2014-09-12 00:20:22 +02:00
|
|
|
|
2015-07-14 19:19:32 +02:00
|
|
|
class MyNodeVisitor extends NodeVisitorAbstract
|
2011-11-12 19:28:53 +01:00
|
|
|
{
|
2014-09-12 00:20:22 +02:00
|
|
|
public function leaveNode(Node $node) {
|
2015-03-21 18:54:52 +01:00
|
|
|
if ($node instanceof Node\Scalar\String_) {
|
2011-11-12 19:28:53 +01:00
|
|
|
$node->value = 'foo';
|
2011-11-10 11:40:11 +01:00
|
|
|
}
|
|
|
|
}
|
2011-11-12 19:28:53 +01:00
|
|
|
}
|
|
|
|
```
|
2011-11-10 11:40:11 +01:00
|
|
|
|
|
|
|
The above node visitor would change all string literals in the program to `'foo'`.
|
|
|
|
|
2014-09-12 00:20:22 +02:00
|
|
|
All visitors must implement the `PhpParser\NodeVisitor` interface, which defines the following four
|
2011-11-10 11:40:11 +01:00
|
|
|
methods:
|
|
|
|
|
2015-07-14 19:19:32 +02:00
|
|
|
```php
|
|
|
|
public function beforeTraverse(array $nodes);
|
|
|
|
public function enterNode(\PhpParser\Node $node);
|
|
|
|
public function leaveNode(\PhpParser\Node $node);
|
|
|
|
public function afterTraverse(array $nodes);
|
|
|
|
```
|
2011-11-10 11:40:11 +01:00
|
|
|
|
2015-01-11 22:13:58 +01:00
|
|
|
The `beforeTraverse()` method is called once before the traversal begins and is passed the nodes the
|
2011-11-10 11:40:11 +01:00
|
|
|
traverser was called with. This method can be used for resetting values before traversation or
|
|
|
|
preparing the tree for traversal.
|
|
|
|
|
2015-01-11 22:13:58 +01:00
|
|
|
The `afterTraverse()` method is similar to the `beforeTraverse()` method, with the only difference that
|
2011-11-10 11:40:11 +01:00
|
|
|
it is called once after the traversal.
|
|
|
|
|
2015-01-11 22:13:58 +01:00
|
|
|
The `enterNode()` and `leaveNode()` methods are called on every node, the former when it is entered,
|
2011-11-10 11:40:11 +01:00
|
|
|
i.e. before its subnodes are traversed, the latter when it is left.
|
|
|
|
|
|
|
|
All four methods can either return the changed node or not return at all (i.e. `null`) in which
|
2015-01-11 22:13:58 +01:00
|
|
|
case the current node is not changed.
|
2014-09-12 00:20:22 +02:00
|
|
|
|
2015-01-11 22:13:58 +01:00
|
|
|
The `enterNode()` method can additionally return the value `NodeTraverser::DONT_TRAVERSE_CHILDREN`,
|
|
|
|
which instructs the traverser to skip all children of the current node.
|
|
|
|
|
|
|
|
The `leaveNode()` method can additionally return the value `NodeTraverser::REMOVE_NODE`, in which
|
2016-01-28 15:01:28 +01:00
|
|
|
case the current node will be removed from the parent array. Furthermore it is possible to return
|
2015-01-11 22:13:58 +01:00
|
|
|
an array of nodes, which will be merged into the parent array at the offset of the current node.
|
|
|
|
I.e. if in `array(A, B, C)` the node `B` should be replaced with `array(X, Y, Z)` the result will
|
|
|
|
be `array(A, X, Y, Z, C)`.
|
2011-11-10 11:40:11 +01:00
|
|
|
|
|
|
|
Instead of manually implementing the `NodeVisitor` interface you can also extend the `NodeVisitorAbstract`
|
|
|
|
class, which will define empty default implementations for all the above methods.
|
|
|
|
|
|
|
|
The NameResolver node visitor
|
|
|
|
-----------------------------
|
|
|
|
|
2014-02-06 20:50:01 +01:00
|
|
|
One visitor is already bundled with the package: `PhpParser\NodeVisitor\NameResolver`. This visitor
|
2011-11-10 11:40:11 +01:00
|
|
|
helps you work with namespaced code by trying to resolve most names to fully qualified ones.
|
|
|
|
|
|
|
|
For example, consider the following code:
|
|
|
|
|
|
|
|
use A as B;
|
|
|
|
new B\C();
|
|
|
|
|
|
|
|
In order to know that `B\C` really is `A\C` you would need to track aliases and namespaces yourself.
|
|
|
|
The `NameResolver` takes care of that and resolves names as far as possible.
|
|
|
|
|
|
|
|
After running it most names will be fully qualified. The only names that will stay unqualified are
|
|
|
|
unqualified function and constant names. These are resolved at runtime and thus the visitor can't
|
|
|
|
know which function they are referring to. In most cases this is a non-issue as the global functions
|
2011-11-12 18:29:50 +01:00
|
|
|
are meant.
|
|
|
|
|
|
|
|
Also the `NameResolver` adds a `namespacedName` subnode to class, function and constant declarations
|
|
|
|
that contains the namespaced name instead of only the shortname that is available via `name`.
|
|
|
|
|
|
|
|
Example: Converting namespaced code to pseudo namespaces
|
|
|
|
--------------------------------------------------------
|
|
|
|
|
|
|
|
A small example to understand the concept: We want to convert namespaced code to pseudo namespaces
|
2011-11-12 19:28:53 +01:00
|
|
|
so it works on 5.2, i.e. names like `A\\B` should be converted to `A_B`. Note that such conversions
|
2011-11-12 18:29:50 +01:00
|
|
|
are fairly complicated if you take PHP's dynamic features into account, so our conversion will
|
|
|
|
assume that no dynamic features are used.
|
|
|
|
|
|
|
|
We start off with the following base code:
|
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
```php
|
2015-07-14 19:19:32 +02:00
|
|
|
use PhpParser\ParserFactory;
|
|
|
|
use PhpParser\PrettyPrinter;
|
|
|
|
use PhpParser\NodeTraverser;
|
|
|
|
use PhpParser\NodeVisitor\NameResolver;
|
|
|
|
|
2014-09-12 00:20:22 +02:00
|
|
|
$inDir = '/some/path';
|
|
|
|
$outDir = '/some/other/path';
|
2011-11-12 19:28:53 +01:00
|
|
|
|
2015-07-14 19:19:32 +02:00
|
|
|
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
|
|
|
|
$traverser = new NodeTraverser;
|
|
|
|
$prettyPrinter = new PrettyPrinter\Standard;
|
2011-11-12 19:28:53 +01:00
|
|
|
|
2015-07-14 19:19:32 +02:00
|
|
|
$traverser->addVisitor(new NameResolver); // we will need resolved names
|
|
|
|
$traverser->addVisitor(new NamespaceConverter); // our own node visitor
|
2011-11-12 19:28:53 +01:00
|
|
|
|
2012-12-21 13:26:58 +01:00
|
|
|
// iterate over all .php files in the directory
|
2015-07-14 19:19:32 +02:00
|
|
|
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($inDir));
|
|
|
|
$files = new \RegexIterator($files, '/\.php$/');
|
2011-11-12 18:29:50 +01:00
|
|
|
|
2012-12-21 13:26:58 +01:00
|
|
|
foreach ($files as $file) {
|
2011-11-12 19:28:53 +01:00
|
|
|
try {
|
|
|
|
// read the file that should be converted
|
|
|
|
$code = file_get_contents($file);
|
2011-11-12 18:29:50 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
// parse
|
2012-05-11 16:44:13 +02:00
|
|
|
$stmts = $parser->parse($code);
|
2011-11-12 18:29:50 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
// traverse
|
|
|
|
$stmts = $traverser->traverse($stmts);
|
2011-11-12 18:29:50 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
// pretty print
|
2014-09-12 00:20:22 +02:00
|
|
|
$code = $prettyPrinter->prettyPrintFile($stmts);
|
2011-11-12 18:29:50 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
// write the converted file to the target directory
|
|
|
|
file_put_contents(
|
2014-09-12 00:20:22 +02:00
|
|
|
substr_replace($file->getPathname(), $outDir, 0, strlen($inDir)),
|
2011-11-12 19:28:53 +01:00
|
|
|
$code
|
|
|
|
);
|
2014-02-06 20:50:01 +01:00
|
|
|
} catch (PhpParser\Error $e) {
|
2011-11-12 19:28:53 +01:00
|
|
|
echo 'Parse Error: ', $e->getMessage();
|
2011-11-12 18:29:50 +01:00
|
|
|
}
|
2011-11-12 19:28:53 +01:00
|
|
|
}
|
|
|
|
```
|
2011-11-12 18:29:50 +01:00
|
|
|
|
2014-09-12 00:20:22 +02:00
|
|
|
Now lets start with the main code, the `NodeVisitor\NamespaceConverter`. One thing it needs to do
|
2011-11-12 18:29:50 +01:00
|
|
|
is convert `A\\B` style names to `A_B` style ones.
|
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
```php
|
2014-02-06 20:50:01 +01:00
|
|
|
use PhpParser\Node;
|
2015-07-14 19:19:32 +02:00
|
|
|
|
|
|
|
class NamespaceConverter extends \PhpParser\NodeVisitorAbstract
|
2011-11-12 19:28:53 +01:00
|
|
|
{
|
2014-02-06 20:50:01 +01:00
|
|
|
public function leaveNode(Node $node) {
|
|
|
|
if ($node instanceof Node\Name) {
|
2017-05-28 12:35:04 +02:00
|
|
|
return new Node\Name(str_replace('\\', '_', $node->toString()));
|
2011-11-12 18:29:50 +01:00
|
|
|
}
|
|
|
|
}
|
2011-11-12 19:28:53 +01:00
|
|
|
}
|
|
|
|
```
|
2011-11-12 18:29:50 +01:00
|
|
|
|
|
|
|
The above code profits from the fact that the `NameResolver` already resolved all names as far as
|
2014-09-12 00:20:22 +02:00
|
|
|
possible, so we don't need to do that. We only need to create a string with the name parts separated
|
2017-05-28 12:35:04 +02:00
|
|
|
by underscores instead of backslashes. This is what `str_replace('\\', '_', $node->toString())` does. (If you want to
|
2011-11-12 18:29:50 +01:00
|
|
|
create a name with backslashes either write `$node->toString()` or `(string) $node`.) Then we create
|
|
|
|
a new name from the string and return it. Returning a new node replaces the old node.
|
|
|
|
|
|
|
|
Another thing we need to do is change the class/function/const declarations. Currently they contain
|
2016-01-28 15:01:28 +01:00
|
|
|
only the shortname (i.e. the last part of the name), but they need to contain the complete name including
|
2014-09-12 00:20:22 +02:00
|
|
|
the namespace prefix:
|
2011-11-12 18:29:50 +01:00
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
```php
|
2014-02-06 20:50:01 +01:00
|
|
|
use PhpParser\Node;
|
|
|
|
use PhpParser\Node\Stmt;
|
2015-07-14 19:19:32 +02:00
|
|
|
|
|
|
|
class NodeVisitor_NamespaceConverter extends \PhpParser\NodeVisitorAbstract
|
2011-11-12 19:28:53 +01:00
|
|
|
{
|
2014-02-06 20:50:01 +01:00
|
|
|
public function leaveNode(Node $node) {
|
|
|
|
if ($node instanceof Node\Name) {
|
2017-05-28 12:35:04 +02:00
|
|
|
return new Node\Name(str_replace('\\', '_', $node->toString()));
|
2014-02-06 20:50:01 +01:00
|
|
|
} elseif ($node instanceof Stmt\Class_
|
|
|
|
|| $node instanceof Stmt\Interface_
|
|
|
|
|| $node instanceof Stmt\Function_) {
|
2017-05-28 12:35:04 +02:00
|
|
|
$node->name = str_replace('\\', '_', $node->namespacedName->toString());
|
2014-02-06 20:50:01 +01:00
|
|
|
} elseif ($node instanceof Stmt\Const_) {
|
2011-11-12 19:28:53 +01:00
|
|
|
foreach ($node->consts as $const) {
|
2017-05-28 12:35:04 +02:00
|
|
|
$const->name = str_replace('\\', '_', $const->namespacedName->toString());
|
2011-11-12 18:29:50 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2011-11-12 19:28:53 +01:00
|
|
|
}
|
|
|
|
```
|
2011-11-12 18:29:50 +01:00
|
|
|
|
|
|
|
There is not much more to it than converting the namespaced name to string with `_` as separator.
|
|
|
|
|
|
|
|
The last thing we need to do is remove the `namespace` and `use` statements:
|
|
|
|
|
2011-11-12 19:28:53 +01:00
|
|
|
```php
|
2014-02-06 20:50:01 +01:00
|
|
|
use PhpParser\Node;
|
|
|
|
use PhpParser\Node\Stmt;
|
2017-02-03 22:34:27 +01:00
|
|
|
use PhpParser\NodeTraverser;
|
2015-07-14 19:19:32 +02:00
|
|
|
|
|
|
|
class NodeVisitor_NamespaceConverter extends \PhpParser\NodeVisitorAbstract
|
2011-11-12 19:28:53 +01:00
|
|
|
{
|
2014-02-06 20:50:01 +01:00
|
|
|
public function leaveNode(Node $node) {
|
|
|
|
if ($node instanceof Node\Name) {
|
2017-05-28 12:35:04 +02:00
|
|
|
return new Node\Name(str_replace('\\', '_', $node->toString()));
|
2014-02-06 20:50:01 +01:00
|
|
|
} elseif ($node instanceof Stmt\Class_
|
|
|
|
|| $node instanceof Stmt\Interface_
|
|
|
|
|| $node instanceof Stmt\Function_) {
|
2017-05-28 12:35:04 +02:00
|
|
|
$node->name = str_replace('\\', '_', $node->namespacedName->toString();
|
2014-02-06 20:50:01 +01:00
|
|
|
} elseif ($node instanceof Stmt\Const_) {
|
2011-11-12 19:28:53 +01:00
|
|
|
foreach ($node->consts as $const) {
|
2017-05-28 12:35:04 +02:00
|
|
|
$const->name = str_replace('\\', '_', $const->namespacedName->toString());
|
2011-11-12 18:29:50 +01:00
|
|
|
}
|
2014-02-06 20:50:01 +01:00
|
|
|
} elseif ($node instanceof Stmt\Namespace_) {
|
2011-11-12 19:28:53 +01:00
|
|
|
// returning an array merges is into the parent array
|
|
|
|
return $node->stmts;
|
2014-02-06 20:50:01 +01:00
|
|
|
} elseif ($node instanceof Stmt\Use_) {
|
2017-10-22 13:50:47 +02:00
|
|
|
// remove use nodes altogether
|
2017-02-03 22:34:27 +01:00
|
|
|
return NodeTraverser::REMOVE_NODE;
|
2011-11-12 18:29:50 +01:00
|
|
|
}
|
|
|
|
}
|
2011-11-12 19:28:53 +01:00
|
|
|
}
|
|
|
|
```
|
2011-11-12 18:29:50 +01:00
|
|
|
|
2015-01-11 21:39:02 +01:00
|
|
|
That's all.
|