Skip to content

Instantly share code, notes, and snippets.

@nikic
Forked from cmb69/gist:7561b2a07c5f1fba76c7
Last active August 29, 2015 14:07
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 nikic/04fce01e69ae5b7b44f8 to your computer and use it in GitHub Desktop.
Save nikic/04fce01e69ae5b7b44f8 to your computer and use it in GitHub Desktop.
<?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