Created
June 28, 2020 04:56
-
-
Save komtaki/7e2163a958440e99b630bbbe1512d368 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
require_once __DIR__ . '/../vendor/autoload.php'; | |
use PhpParser\Error; | |
use PhpParser\Lexer; | |
use PhpParser\Node; | |
use PhpParser\NodeTraverser; | |
use PhpParser\NodeVisitorAbstract; | |
use PhpParser\NodeVisitor; | |
use PhpParser\Parser; | |
use PhpParser\PrettyPrinter; | |
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; | |
$lexer = new Lexer\Emulative([ | |
'usedAttributes' => [ | |
'comments', | |
'startLine', 'endLine', | |
'startTokenPos', 'endTokenPos', | |
], | |
]); | |
$parser = new Parser\Php7($lexer); | |
$traverser = new NodeTraverser(); | |
$traverser->addVisitor(new NodeVisitor\CloningVisitor()); | |
$printer = new PrettyPrinter\Standard(); | |
try { | |
$oldStmts = $parser->parse($code); | |
} catch (Error $error) { | |
echo "Parse error: {$error->getMessage()}\n"; | |
return; | |
} | |
$oldTokens = $lexer->getTokens(); | |
$newStmts = $traverser->traverse($oldStmts); | |
$traverser = new NodeTraverser; | |
$traverser->addVisitor(new VarDumpConvertPrintVisitor); | |
$stmts = $traverser->traverse($newStmts); | |
$newCode = $printer->printFormatPreserving($newStmts, $oldStmts, $oldTokens); | |
var_dump($newCode); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment