-
-
Save nikic/04fce01e69ae5b7b44f8 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 | |
require './vendor/autoload.php'; | |
// The code samples to parse. | |
// => bool(false) | |
$code = '<?php class Foo {public $bar;}'; | |
// => bool(true) | |
$code = '<?php class Foo {var $bar;}'; | |
function isImplicitlyPublicProperty(array $tokens, PhpParser\Node\Stmt\Property $prop) { | |
$i = $prop->getAttribute('startOffset'); | |
return isset($tokens[$i]) && $tokens[$i][0] == T_VAR; | |
} | |
class MyNodeVisitor extends PhpParser\NodeVisitorAbstract | |
{ | |
private $tokens; | |
public function setTokens(array $tokens) { | |
$this->tokens = $tokens; | |
} | |
public function leaveNode(PhpParser\Node $node) { | |
if ($node instanceof PhpParser\Node\Stmt\Property) { | |
var_dump(isImplicitlyPublicProperty($this->tokens, $node)); | |
} | |
} | |
} | |
// We need this special lexer | |
class LexerWithTokenOffsets extends PhpParser\Lexer { | |
public function getNextToken(&$value = null, &$startAttributes = null, &$endAttributes = null) { | |
$tokenId = parent::getNextToken($value, $startAttributes, $endAttributes); | |
$startAttributes['startOffset'] = $endAttributes['endOffset'] = $this->pos; | |
return $tokenId; | |
} | |
public function getTokens() { | |
return $this->tokens; | |
} | |
} | |
$lexer = new LexerWithTokenOffsets(); | |
$parser = new PhpParser\Parser($lexer); | |
$visitor = new MyNodeVisitor(); | |
$traverser = new PhpParser\NodeTraverser(); | |
$traverser->addVisitor($visitor); | |
try { | |
$stmts = $parser->parse($code); | |
$visitor->setTokens($lexer->getTokens()); | |
$stmts = $traverser->traverse($stmts); | |
} catch (PhpParser\Error $e) { | |
echo 'Parse Error: ', $e->getMessage(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment