作者:slde-rorschac
项目:deprecation-detecto
/**
* @param Node\Stmt\Class_ $node
*
* @return Node\Stmt\Class_
*/
public function resolveConstructor(Node\Stmt\Class_ $node)
{
foreach ($node->stmts as $key => $stmt) {
if ($stmt instanceof Node\Stmt\ClassMethod && $stmt->name === '__construct') {
// this will make problems we need an layer above which chains the variable resolvers
// because we need may need more than this resolver
// skip constructor if is abstract
if ($stmt->isAbstract()) {
return $node;
}
// change recursivly the nodes
$subTraverser = new NodeTraverser();
foreach ($this->visitors as $visitor) {
$subTraverser->addVisitor($visitor);
}
// the table switches to a method scope
// $x = ... will be treated normal
// $this->x = ... will be stored in the above class scope and is available afterwards
$this->table->enterScope(new TableScope(TableScope::CLASS_METHOD_SCOPE));
$subTraverser->traverse($stmt->params);
$nodes = $subTraverser->traverse($stmt->stmts);
$this->table->leaveScope();
//override the old statement
$stmt->stmts = $nodes;
// override the classmethod statement in class
$node->stmts[$key] = $stmt;
// return the changed node to override it
return $node;
}
}
// no constructor defined
return $node;
}
作者:koktu
项目:hexlet-psr-linte
/**
* @param $rulesPath
* @return array
*/
public function loadRules($rulesPath)
{
$parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
$targetFiles = getTargetFiles($rulesPath);
foreach ($targetFiles as $file) {
$code = file_get_contents($file);
$stmts = $parser->parse($code);
$traverser = new NodeTraverser();
$visitor = new RulesLoadVisitor();
$traverser->addVisitor($visitor);
$traverser->traverse($stmts);
$namespace = $visitor->getNamespace();
$className = $visitor->getClassName();
if (!is_null($namespace) && !is_null($className)) {
include $file;
$fullClassName = $namespace . '\\' . $className;
if (class_exists($fullClassName)) {
$implements = class_implements($fullClassName);
if (in_array(RuleBaseInterfase::class, $implements)) {
$this->rules[] = $fullClassName;
$this->addRecord(Logger::LOGLEVEL_OK, "Loaded rules: {$fullClassName} - " . $fullClassName::getDescription(), $file);
} else {
$this->addRecord(Logger::LOGLEVEL_ERROR, "Class {$fullClassName} must implements RulesBaseInterface", $file);
}
} else {
$this->addRecord(Logger::LOGLEVEL_ERROR, "Class {$fullClassName} doesn't exists in {$file}", $file);
}
} else {
$this->addRecord(Logger::LOGLEVEL_ERROR, 'File doesn\'t contains correct class defenition', $file);
}
}
return $this->rules;
}
作者:trismegist
项目:phpunit-assert-soli
protected function setUp()
{
$this->parser = new \PhpParser\Parser(new \PhpParser\Lexer());
$this->traverser = new \PhpParser\NodeTraverser();
$this->sut = $this->createVisitor();
$this->traverser->addVisitor($this->sut);
}
作者:jdgrime
项目:wp-plugin-uninstall-scanne
public function test()
{
$class = get_class($this);
$class = substr($class, 41);
$file_name = $class . '.inc';
$parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
$traverser = new NodeTraverser();
// add your visitor
$collector = new Collector();
$traverser->addVisitor(new NodeVisitor($collector, new Config()));
try {
$code = file_get_contents(__DIR__ . '/../tests/' . $file_name);
// parse
$stmts = $parser->parse($code);
// traverse
$traverser->traverse($stmts);
$found = $collector->get();
foreach ($found as &$item) {
unset($item['node']);
}
$this->assertEquals($this->expectations(), $found);
} catch (Error $e) {
echo 'Parse Error: ', $e->getMessage();
}
}
作者:jorisstey
项目:phptag
/**
* Parse a file and return found tags.
*
* @param string $filePath Full path to filename.
* @return array
*/
public function getTags($filePath)
{
// Create a PHP-Parser instance.
$parser = new PhpParser(new Lexer(array('usedAttributes' => array('startLine', 'endLine', 'startFilePos', 'endFilePos'))));
// Parse the source code into a list of statements.
$source = $this->getContents($filePath);
$statements = $parser->parse($source);
$traverser = new NodeTraverser();
// Make sure all names are resolved as fully qualified.
$traverser->addVisitor(new NameResolver());
// Create visitors that turn statements into tags.
$visitors = array(new Visitor\ClassDefinition(), new Visitor\ClassReference(), new Visitor\ConstantDefinition(), new Visitor\FunctionDefinition(), new Visitor\GlobalVariableDefinition(), new Visitor\InterfaceDefinition(), new Visitor\TraitDefinition());
foreach ($visitors as $visitor) {
$traverser->addVisitor($visitor);
}
$traverser->traverse($statements);
// Extract tags from the visitors.
$tags = array();
foreach ($visitors as $visitor) {
$tags = array_merge($tags, array_map(function (Tag $tag) use($source) {
$comment = substr($source, $tag->getStartFilePos(), $tag->getEndFilePos() - $tag->getStartFilePos() + 1);
if (($bracePos = strpos($comment, '{')) !== false) {
$comment = substr($comment, 0, $bracePos) . ' {}';
}
return $tag->setComment(preg_replace('/\\s+/', ' ', $comment));
}, $visitor->getTags()));
}
return $tags;
}
作者:jacmo
项目:php-worksho
/**
* @param ExerciseInterface $exercise
* @param string $fileName
* @return ResultInterface
*/
public function check(ExerciseInterface $exercise, $fileName)
{
if (!$exercise instanceof FunctionRequirementsExerciseCheck) {
throw new \InvalidArgumentException();
}
$requiredFunctions = $exercise->getRequiredFunctions();
$bannedFunctions = $exercise->getBannedFunctions();
$code = file_get_contents($fileName);
try {
$ast = $this->parser->parse($code);
} catch (Error $e) {
return Failure::fromCheckAndCodeParseFailure($this, $e, $fileName);
}
$visitor = new FunctionVisitor($requiredFunctions, $bannedFunctions);
$traverser = new NodeTraverser();
$traverser->addVisitor($visitor);
$traverser->traverse($ast);
$bannedFunctions = [];
if ($visitor->hasUsedBannedFunctions()) {
$bannedFunctions = array_map(function (FuncCall $node) {
return ['function' => $node->name->__toString(), 'line' => $node->getLine()];
}, $visitor->getBannedUsages());
}
$missingFunctions = [];
if (!$visitor->hasMetFunctionRequirements()) {
$missingFunctions = $visitor->getMissingRequirements();
}
if (!empty($bannedFunctions) || !empty($missingFunctions)) {
return new FunctionRequirementsFailure($this, $bannedFunctions, $missingFunctions);
}
return Success::fromCheck($this);
}
作者:niktu
项目:solidifie
private function traverse(array $nodes, NodeTraverser $traverser)
{
foreach ($nodes as $file => $stmts) {
$this->dispatcher->dispatch(new ChangeFile($file));
$traverser->traverse($stmts);
}
}
作者:mf
项目:cakephp2-magic-propertie
protected function setUp()
{
$this->traverser = new NodeTraverser();
$this->visitor = new ClassVisitor();
$this->traverser->addVisitor($this->visitor);
$this->parser = new Parser(new Lexer());
}
作者:rskuiper
项目:php-assumption
/**
* @param array $args
*/
public function handle(array $args)
{
$this->cli->out(sprintf('PHPAssumptions analyser v%s by @rskuipers', Cli::VERSION))->br();
try {
$this->cli->arguments->parse($args);
} catch (\Exception $e) {
$this->cli->usage($args);
return;
}
switch ($this->cli->arguments->get('format')) {
case 'xml':
$output = new XmlOutput($this->cli, $this->cli->arguments->get('output'));
break;
default:
$output = new PrettyOutput($this->cli);
break;
}
$nodeTraverser = new NodeTraverser();
$analyser = new Analyser($this->parser, $nodeTraverser);
$nodeTraverser->addVisitor(new NodeVisitor($analyser, new Detector()));
$target = $this->cli->arguments->get('path');
$targets = [];
if (is_file($target)) {
$targets[] = $target;
} else {
$directory = new \RecursiveDirectoryIterator($target);
$iterator = new \RecursiveIteratorIterator($directory);
$regex = new \RegexIterator($iterator, '/^.+\\.php$/i', \RecursiveRegexIterator::GET_MATCH);
foreach ($regex as $file) {
$targets[] = $file[0];
}
}
$result = $analyser->analyse($targets);
$output->output($result);
}
作者:killer10
项目:PhpGeneric
public function implement($class)
{
$parts = $orig_parts = explode("\\", ltrim($class, "\\"));
$real_class_parts = [];
while ($part = array_shift($parts)) {
if (strpos($part, self::CLASS_TOKEN) !== false) {
break;
}
$real_class_parts[] = $part;
}
array_unshift($parts, $part);
$types = [];
foreach ($parts as $part) {
$types[] = str_replace([self::CLASS_TOKEN, self::NS_TOKEN], ["", "\\"], $part);
}
$real_class = implode("\\", $real_class_parts);
if (!class_exists($real_class)) {
throw new \RuntimeException("Attempting to use generics on unknown class {$real_class}");
}
if (!($ast = $this->compiler->getClass($real_class))) {
throw new \RuntimeException("Attempting to use generics with non-generic class");
}
$generator = new Generator($ast->getAttribute("generics"), $types);
$traverser = new NodeTraverser();
$traverser->addVisitor($generator);
$ast = $traverser->traverse([$ast]);
$ast[0]->name = array_pop($orig_parts);
$ast[0]->extends = new Node\Name\FullyQualified($real_class_parts);
array_unshift($ast, new Node\Stmt\Namespace_(new Node\Name($orig_parts)));
return $this->prettyPrinter->prettyPrint($ast);
}
作者:koktu
项目:hexlet-psr-linte
/**
* @param $code
* @param bool $autoFix - In case of true - pretty code will be generated (avaiable by getPrettyCode method)
* @return Logger
*/
public function lint($code, $autoFix = false)
{
$this->autoFix = $autoFix;
$this->prettyCode = '';
$this->logger = new Logger();
try {
$stmts = $this->parser->parse($code);
} catch (Error $e) {
$this->logger->addRecord(new LogRecord('', '', Logger::LOGLEVEL_ERROR, $e->getMessage(), ''));
return $this->logger;
}
$traverser = new NodeTraverser();
$rulesVisitor = new RulesVisitor($this->rules, $this->autoFix);
$traverser->addVisitor($rulesVisitor);
$traverser->traverse($stmts);
$messages = $rulesVisitor->getLog();
foreach ($messages as $message) {
$this->logger->addRecord(new LogRecord($message['line'], $message['column'], $message['level'], $message['message'], $message['name']));
}
if ($autoFix) {
$prettyPrinter = new PrettyPrinter\Standard();
$this->prettyCode = $prettyPrinter->prettyPrint($stmts);
}
$sideEffectVisitor = new SideEffectsVisitor();
$traverser->addVisitor($sideEffectVisitor);
$traverser->traverse($stmts);
if ($sideEffectVisitor->isMixed()) {
$this->logger->addRecord(new LogRecord('', '', Logger::LOGLEVEL_ERROR, 'A file SHOULD declare new symbols (classes, functions, constants, etc.) and cause no other side' . 'effects, or it SHOULD execute logic with side effects, but SHOULD NOT do both.', ''));
}
return $this->logger;
}
作者:magento-ec
项目:magento-finde
/**
* @param $mageClassPath
* @return string
*/
public function getMagentoVersion($mageClassPath)
{
$parser = new PhpParser\Parser(new PhpParser\Lexer\Emulative());
$traverser = new PhpParser\NodeTraverser();
$this->xml = new SimpleXMLElement($traverser->traverse($parser->parse(file_get_contents($mageClassPath))));
$version = array($this->getVersionPart('major'), $this->getVersionPart('minor'), $this->getVersionPart('revision'), $this->getVersionPart('patch'));
return implode('.', $version);
}
作者:knuthellan
项目:phpimport
public function __construct(array $ast)
{
$this->ast = $ast;
$this->visitor = new ExtractNames();
$traverser = new NodeTraverser();
$traverser->addVisitor($this->visitor);
$traverser->traverse($this->ast);
}
作者:mf
项目:php-analyze
/**
* @param Project $project
*/
public function analyze(Project $project)
{
$traverser = new NodeTraverser();
$traverser->addVisitor(new PhpParserNameResolver());
foreach ($project->getFiles() as $file) {
$traverser->traverse($file->getTree());
}
}
作者:paslanda
项目:php-sandbo
public function validate($code)
{
$traverser = new NodeTraverser();
$traverser->addVisitor($this->visitor);
$code = "<?php\n" . $code;
$ast = $this->parser->parse($code);
$traverser->traverse($ast);
}
作者:Ocramiu
项目:PhpCodeInline
private function getVariableAccesses(FunctionLike $function) : array
{
$traverser = new NodeTraverser();
$accessLocator = new VariableAccessLocatorVisitor();
$traverser->addVisitor(new FunctionScopeIsolatingVisitor($accessLocator));
$traverser->traverse([$function->getStmts()]);
return $accessLocator->getFoundVariableAccesses();
}
作者:royop
项目:php-cf
/** @dataProvider provideTestParseAndDump */
public function testParseAndDump($code, $expectedDump)
{
$astTraverser = new PhpParser\NodeTraverser();
$astTraverser->addVisitor(new PhpParser\NodeVisitor\NameResolver());
$parser = new Parser(new PhpParser\Parser(new PhpParser\Lexer()), $astTraverser);
$dumper = new Dumper();
$block = $parser->parse($code, 'foo.php');
$this->assertEquals($this->canonicalize($expectedDump), $this->canonicalize($dumper->dump($block)));
}
作者:AltThre
项目:TestBenc
/**
* Get the fullyqualified imports and typehints.
*
* @param string $path
*
* @return string[]
*/
public function analyze($path)
{
$traverser = new NodeTraverser();
$traverser->addVisitor(new NameResolver());
$traverser->addVisitor($imports = new ImportVisitor());
$traverser->addVisitor($names = new NameVisitor());
$traverser->traverse($this->parser->parse(file_get_contents($path)));
return array_unique(array_merge($imports->getImports(), $names->getNames()));
}
作者:phpdocumento
项目:reflectio
/**
* Creates a new traverser object and adds visitors.
*
* @return NodeTraverser
*/
protected function createTraverser()
{
$node_traverser = new NodeTraverser();
$node_traverser->addVisitor(new NameResolver());
foreach ($this->visitors as $visitor) {
$node_traverser->addVisitor($visitor);
}
return $node_traverser;
}
作者:deviseph
项目:cm
/**
* Get the modified AST
*
* @param string $view
* @return array
*/
protected function modified($view)
{
$ast = $this->parser->parse($view);
$traverser = new NodeTraverser();
$traverser->addVisitor(new Modifiers\RegisterDeviseTags($this->parser));
$traverser->addVisitor(new Modifiers\AddPlaceHolderTags($this->parser));
$traverser->addVisitor(new Modifiers\EchoDeviseMagic($this->parser));
return $traverser->traverse($ast);
}