Skip to content

Instantly share code, notes, and snippets.

@gong023
Created March 12, 2017 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gong023/951c6dccad33dacd884aa6cd054d94e3 to your computer and use it in GitHub Desktop.
Save gong023/951c6dccad33dacd884aa6cd054d94e3 to your computer and use it in GitHub Desktop.
<?php
require __DIR__ . '/../vendor/autoload.php';
use PhpParser\Node;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitorAbstract;
use PhpParser\ParserFactory;
class MyNodeVisitor extends NodeVisitorAbstract
{
public function leaveNode(Node $node) {
if ($node instanceof Node\Scalar\String_) {
$node->value = 'hello';
}
}
}
$code = <<<CODE
<?php
echo 'hi';
CODE;
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
$stmts = $parser->parse($code);
$traverser = new NodeTraverser;
$traverser->addVisitor(new MyNodeVisitor);
$stmts = $traverser->traverse($stmts);
$prettyPrinter = new PhpParser\PrettyPrinter\Standard();
echo $prettyPrinter->prettyPrintFile($stmts);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment