Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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
You can’t perform that action at this time.