Skip to content

Instantly share code, notes, and snippets.

@zonuexe
Created March 22, 2017 04:38
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 zonuexe/882269ae5dcf0411701ed98d0f4315f8 to your computer and use it in GitHub Desktop.
Save zonuexe/882269ae5dcf0411701ed98d0f4315f8 to your computer and use it in GitHub Desktop.
get_var_name.php
<?php
include_once getenv('HOME') . '/.composer/vendor/autoload.php';
use PhpParser\Node;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitorAbstract;
use PhpParser\ParserFactory;
use PhpParser\PrettyPrinter;
/**
* @return string[]
*/
function get_var_name(...$args)
{
$trace = debug_backtrace(0, 1);
$recent = array_shift($trace);
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
if (!file_exists($recent['file'])) {
return [];
}
$code = file_get_contents($recent['file']);
$visitor = new class($recent['line'], count($args)) extends \PhpParser\NodeVisitorAbstract {
public $result = [];
private $line;
private $args_num;
public function __construct($line, $args_num)
{
$this->line = $line;
$this->args_num = $args_num;
}
public function leaveNode(Node $node)
{
if (
$node instanceof Node\Expr\FuncCall
&& $node->name->parts[0] === 'get_var_name'
&& count($node->args) === $this->args_num
) {
$attr = $node->getAttributes();
$d = intdiv($attr['startLine'] + $attr['endLine'], 2);
//var_dump([$this->line => $d]);
$fline = ($attr['startLine'] == $attr['endLine'])
? $attr['startLine']
: $d + (($attr['endLine'] - $attr['startLine']) % 2);
if ($this->line !== $fline) {
return;
}
$arg_names = [];
foreach ($node->args as $a) {
if ($a->value instanceof Node\Expr\Variable) {
$arg_names[] = '$'.$a->value->name;
} else {
$arg_names[] = '[value]';
}
}
$this->result = $arg_names;
}
}
};
$traverser = new NodeTraverser;
$traverser->addVisitor($visitor);
$traverser->traverse($parser->parse($code));
return $visitor->result;
}
$a = 1;
$b = 2;
$hoge = $fuga = $piyo = null;
var_dump(get_var_name($a,
$b));
var_dump(get_var_name($GLOBALS, $b));
var_dump(get_var_name(
$hoge,
$fuga,
1,
$piyo));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment