PHP code example of open-code-modeling / php-code-ast

1. Go to this page and download the library: Download open-code-modeling/php-code-ast library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

open-code-modeling / php-code-ast example snippets




$parser = (new PhpParser\ParserFactory())->create(PhpParser\ParserFactory::ONLY_PHP7);
$printer = new PhpParser\PrettyPrinter\Standard(['shortArraySyntax' => true]);

$ast = $parser->parse('');

$classBuilder = OpenCodeModeling\CodeAst\Builder\ClassBuilder::fromScratch('TestClass', 'My\\Awesome\\Service');
$classBuilder
    ->setFinal(true)
    ->setExtends('BaseClass')
    ->setNamespaceImports('Foo\\Bar')
    ->setImplements('\\Iterator', 'Bar');

$nodeTraverser = new PhpParser\NodeTraverser();

$classBuilder->injectVisitors($nodeTraverser, $parser);

print_r($printer->prettyPrintFile($nodeTraverser->traverse($ast)));



declare (strict_types=1);
namespace My\Awesome\Service;

use Foo\Bar;
final class TestClass extends BaseClass implements \Iterator, Bar
{
}



$method = new OpenCodeModeling\CodeAst\Code\MethodGenerator(
    'toInt',
    [],
    OpenCodeModeling\CodeAst\Code\MethodGenerator::FLAG_PUBLIC,
    new OpenCodeModeling\CodeAst\Code\BodyGenerator($this->parser, 'return $this->myValue;')
);
$method->setReturnType('int');

$nodeTraverser->addVisitor(new OpenCodeModeling\CodeAst\NodeVisitor\ClassMethod($method));

print_r($printer->prettyPrintFile($nodeTraverser->traverse($ast)));



declare (strict_types=1);
namespace My\Awesome\Service;

use Foo\Bar;
final class TestClass extends BaseClass implements \Iterator, Bar
{
    public function toInt() : int
    {
        return $this->myValue;
    }
}


$parser = (new PhpParser\ParserFactory())->create(PhpParser\ParserFactory::ONLY_PHP7);
$printer = new PhpParser\PrettyPrinter\Standard(['shortArraySyntax' => true]);

$expected = <<<'EOF'


declare (strict_types=1);
namespace My\Awesome\Service;

use Foo\Bar;
final class TestClass extends BaseClass implements \Iterator, Bar
{
    private const PRIV = 'private';
}
EOF;


$ast = $parser->parse($expected);

$classBuilder = OpenCodeModeling\CodeAst\Builder\ClassBuilder::fromNodes(...$ast);

$classBuilder->getName(); // TestClass
$classBuilder->getExtends(); // BaseClass
$classBuilder->isFinal(); // true
$classBuilder->isStrict(); // true
$classBuilder->isAbstract(); // false
bash
$ composer