Chris@0: Code generation Chris@0: =============== Chris@0: Chris@0: It is also possible to generate code using the parser, by first creating an Abstract Syntax Tree and then using the Chris@0: pretty printer to convert it to PHP code. To simplify code generation, the project comes with builders which allow Chris@0: creating node trees using a fluid interface, instead of instantiating all nodes manually. Builders are available for Chris@0: the following syntactic elements: Chris@0: Chris@0: * namespaces and use statements Chris@0: * classes, interfaces and traits Chris@0: * methods, functions and parameters Chris@0: * properties Chris@0: Chris@0: Here is an example: Chris@0: Chris@0: ```php Chris@0: use PhpParser\BuilderFactory; Chris@0: use PhpParser\PrettyPrinter; Chris@0: use PhpParser\Node; Chris@0: Chris@0: $factory = new BuilderFactory; Chris@0: $node = $factory->namespace('Name\Space') Chris@0: ->addStmt($factory->use('Some\Other\Thingy')->as('SomeOtherClass')) Chris@0: ->addStmt($factory->class('SomeClass') Chris@0: ->extend('SomeOtherClass') Chris@0: ->implement('A\Few', '\Interfaces') Chris@0: ->makeAbstract() // ->makeFinal() Chris@0: Chris@0: ->addStmt($factory->method('someMethod') Chris@0: ->makePublic() Chris@0: ->makeAbstract() // ->makeFinal() Chris@0: ->setReturnType('bool') Chris@0: ->addParam($factory->param('someParam')->setTypeHint('SomeClass')) Chris@0: ->setDocComment('/** Chris@0: * This method does something. Chris@0: * Chris@0: * @param SomeClass And takes a parameter Chris@0: */') Chris@0: ) Chris@0: Chris@0: ->addStmt($factory->method('anotherMethod') Chris@0: ->makeProtected() // ->makePublic() [default], ->makePrivate() Chris@0: ->addParam($factory->param('someParam')->setDefault('test')) Chris@0: // it is possible to add manually created nodes Chris@0: ->addStmt(new Node\Expr\Print_(new Node\Expr\Variable('someParam'))) Chris@0: ) Chris@0: Chris@0: // properties will be correctly reordered above the methods Chris@0: ->addStmt($factory->property('someProperty')->makeProtected()) Chris@0: ->addStmt($factory->property('anotherProperty')->makePrivate()->setDefault(array(1, 2, 3))) Chris@0: ) Chris@0: Chris@0: ->getNode() Chris@0: ; Chris@0: Chris@0: $stmts = array($node); Chris@0: $prettyPrinter = new PrettyPrinter\Standard(); Chris@0: echo $prettyPrinter->prettyPrintFile($stmts); Chris@0: ``` Chris@0: Chris@0: This will produce the following output with the standard pretty printer: Chris@0: Chris@0: ```php Chris@0: