comparison vendor/nikic/php-parser/doc/4_Code_generation.markdown @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 Code generation
2 ===============
3
4 It is also possible to generate code using the parser, by first creating an Abstract Syntax Tree and then using the
5 pretty printer to convert it to PHP code. To simplify code generation, the project comes with builders which allow
6 creating node trees using a fluid interface, instead of instantiating all nodes manually. Builders are available for
7 the following syntactic elements:
8
9 * namespaces and use statements
10 * classes, interfaces and traits
11 * methods, functions and parameters
12 * properties
13
14 Here is an example:
15
16 ```php
17 use PhpParser\BuilderFactory;
18 use PhpParser\PrettyPrinter;
19 use PhpParser\Node;
20
21 $factory = new BuilderFactory;
22 $node = $factory->namespace('Name\Space')
23 ->addStmt($factory->use('Some\Other\Thingy')->as('SomeOtherClass'))
24 ->addStmt($factory->class('SomeClass')
25 ->extend('SomeOtherClass')
26 ->implement('A\Few', '\Interfaces')
27 ->makeAbstract() // ->makeFinal()
28
29 ->addStmt($factory->method('someMethod')
30 ->makePublic()
31 ->makeAbstract() // ->makeFinal()
32 ->setReturnType('bool')
33 ->addParam($factory->param('someParam')->setTypeHint('SomeClass'))
34 ->setDocComment('/**
35 * This method does something.
36 *
37 * @param SomeClass And takes a parameter
38 */')
39 )
40
41 ->addStmt($factory->method('anotherMethod')
42 ->makeProtected() // ->makePublic() [default], ->makePrivate()
43 ->addParam($factory->param('someParam')->setDefault('test'))
44 // it is possible to add manually created nodes
45 ->addStmt(new Node\Expr\Print_(new Node\Expr\Variable('someParam')))
46 )
47
48 // properties will be correctly reordered above the methods
49 ->addStmt($factory->property('someProperty')->makeProtected())
50 ->addStmt($factory->property('anotherProperty')->makePrivate()->setDefault(array(1, 2, 3)))
51 )
52
53 ->getNode()
54 ;
55
56 $stmts = array($node);
57 $prettyPrinter = new PrettyPrinter\Standard();
58 echo $prettyPrinter->prettyPrintFile($stmts);
59 ```
60
61 This will produce the following output with the standard pretty printer:
62
63 ```php
64 <?php
65
66 namespace Name\Space;
67
68 use Some\Other\Thingy as SomeClass;
69 abstract class SomeClass extends SomeOtherClass implements A\Few, \Interfaces
70 {
71 protected $someProperty;
72 private $anotherProperty = array(1, 2, 3);
73 /**
74 * This method does something.
75 *
76 * @param SomeClass And takes a parameter
77 */
78 public abstract function someMethod(SomeClass $someParam) : bool;
79 protected function anotherMethod($someParam = 'test')
80 {
81 print $someParam;
82 }
83 }
84 ```