File: vendor/nikic/php-parser/doc/4_Code_generation.markdown

Recommend this page to a friend!
  Classes of Renato De Oliveira Lucena  >  PHP Pokemon Script  >  vendor/nikic/php-parser/doc/4_Code_generation.markdown  >  Download  
File: vendor/nikic/php-parser/doc/4_Code_generation.markdown
Role: Class source
Content type: text/markdown
Description: Class source
Class: PHP Pokemon Script
Provides an API to manage a database of Pokemons
Author: By
Last change:
Date: 2 years ago
Size: 2,749 bytes


Class file image Download

Code generation

It is also possible to generate code using the parser, by first creating an Abstract Syntax Tree and then using the 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

Here is an example:

use PhpParser\BuilderFactory;
use PhpParser\PrettyPrinter;
use PhpParser\Node;

$factory = new BuilderFactory;
$node = $factory->namespace('Name\Space')
        ->implement('A\Few', '\Interfaces')
        ->makeAbstract() // ->makeFinal()

            ->makeAbstract() // ->makeFinal()
                              * This method does something.
                              * @param SomeClass And takes a parameter

            ->makeProtected() // ->makePublic() [default], ->makePrivate()
            // it is possible to add manually created nodes
            ->addStmt(new Node\Expr\Print_(new Node\Expr\Variable('someParam')))

        // properties will be correctly reordered above the methods
        ->addStmt($factory->property('anotherProperty')->makePrivate()->setDefault(array(1, 2, 3)))


$stmts = array($node);
$prettyPrinter = new PrettyPrinter\Standard();
echo $prettyPrinter->prettyPrintFile($stmts);

This will produce the following output with the standard pretty printer:


namespace Name\Space;

use Some\Other\Thingy as SomeClass;
abstract class SomeClass extends SomeOtherClass implements A\Few, \Interfaces
    protected $someProperty;
    private $anotherProperty = array(1, 2, 3);
     * This method does something.
     * @param SomeClass And takes a parameter
    public abstract function someMethod(SomeClass $someParam) : bool;
    protected function anotherMethod($someParam = 'test')
        print $someParam;

For more information send a message to info at phpclasses dot org.