php-parser/doc/4_Code_generation.markdown

81 lines
2.6 KiB
Markdown
Raw Normal View History

2012-03-11 09:23:32 +01:00
Code generation
===============
2012-04-23 13:37:12 +02:00
It is also possible to generate code using the parser, by first creating an Abstract Syntax Tree and then using the
2015-03-10 16:05:55 +01:00
pretty printer to convert it to PHP code. To simplify code generation, the project comes with builders which allow
creating node trees using a fluid interface, instead of instantiating all nodes manually. Builders are available for
the following syntactic elements:
* namespaces and use statements
* classes, interfaces and traits
* methods, functions and parameters
* properties
2012-03-11 09:23:32 +01:00
Here is an example:
```php
<?php
2014-02-06 20:50:01 +01:00
$factory = new PhpParser\BuilderFactory;
2014-12-19 18:35:19 +01:00
$node = $factory->namespace('Name\Space')
2015-03-10 16:05:55 +01:00
->addStmt($factory->use('Some\Other\Thingy')->as('SomeOtherClass'))
2014-12-19 18:35:19 +01:00
->addStmt($factory->class('SomeClass')
->extend('SomeOtherClass')
->implement('A\Few', '\Interfaces')
2012-03-11 09:23:32 +01:00
->makeAbstract() // ->makeFinal()
2014-12-19 18:35:19 +01:00
->addStmt($factory->method('someMethod')
->makePublic()
2014-12-19 18:35:19 +01:00
->makeAbstract() // ->makeFinal()
->addParam($factory->param('someParam')->setTypeHint('SomeClass'))
->setDocComment('/**
* This method does something.
*
* @param SomeClass And takes a parameter
*/')
)
2012-03-11 09:23:32 +01:00
2014-12-19 18:35:19 +01:00
->addStmt($factory->method('anotherMethod')
->makeProtected() // ->makePublic() [default], ->makePrivate()
->addParam($factory->param('someParam')->setDefault('test'))
// it is possible to add manually created nodes
->addStmt(new PhpParser\Node\Expr\Print_(new PhpParser\Node\Expr\Variable('someParam')))
)
// properties will be correctly reordered above the methods
->addStmt($factory->property('someProperty')->makeProtected())
->addStmt($factory->property('anotherProperty')->makePrivate()->setDefault(array(1, 2, 3)))
)
2012-03-11 09:23:32 +01:00
->getNode()
;
$stmts = array($node);
$prettyPrinter = new PhpParser\PrettyPrinter\Standard();
echo $prettyPrinter->prettyPrintFile($stmts);
2012-03-11 09:23:32 +01:00
```
This will produce the following output with the standard pretty printer:
2012-03-11 09:23:32 +01:00
```php
<?php
2014-12-19 18:35:19 +01:00
namespace Name\Space;
2015-03-10 16:05:55 +01:00
use Some\Other\Thingy as SomeClass;
abstract class SomeClass extends SomeOtherClass implements A\Few, \Interfaces
2012-03-11 09:23:32 +01:00
{
protected $someProperty;
private $anotherProperty = array(1, 2, 3);
/**
* This method does something.
*
* @param SomeClass And takes a parameter
*/
public abstract function someMethod(SomeClass $someParam);
2012-03-11 09:23:32 +01:00
protected function anotherMethod($someParam = 'test')
{
print $someParam;
}
}
2012-04-04 12:29:30 +02:00
```