Skip to content

Instantly share code, notes, and snippets.

@komtaki
Last active June 28, 2020 04:56
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 komtaki/514f13fa07f4e8bdd9bd0d4fa61e0719 to your computer and use it in GitHub Desktop.
Save komtaki/514f13fa07f4e8bdd9bd0d4fa61e0719 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php';
use PhpParser\Error;
use PhpParser\Node;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitorAbstract;
use PhpParser\ParserFactory;
class VarDumpConvertPrintVisitor extends NodeVisitorAbstract
{
public function leaveNode(Node $node)
{
if ($node instanceof Node\Expr\FuncCall && $node->name->getLast() == 'var_dump') {
$node->name->parts = ['print'];
}
}
}
$code = <<<'CODE'
<?php
function test()
{
var_dump($foo);
}
CODE;
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
try {
$stmts = $parser->parse($code);
} catch (Error $error) {
echo "Parse error: {$error->getMessage()}\n";
return;
}
$traverser = new NodeTraverser;
$traverser->addVisitor(new VarDumpConvertPrintVisitor);
$stmts = $traverser->traverse($stmts);
$prettyPrinter = new PhpParser\PrettyPrinter\Standard();
$newCode = $prettyPrinter->prettyPrintFile($stmts);
var_dump($newCode);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment