/** * @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; }
/** * @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; }
public function walk($fileNodes) { array_walk($fileNodes, function (&$nodes) { $nodes = $this->traverser->traverse($nodes); }); return $fileNodes; }
/** * @param PhpFileInfo $phpFileInfo * * @return PhpFileInfo */ public function parseFile(PhpFileInfo $phpFileInfo) { foreach ($this->deprecationVisitors as $visitor) { $visitor->setPhpFileInfo($phpFileInfo); } $this->traverser->traverse($this->parse($phpFileInfo->getContents())); return $phpFileInfo; }
/** * @test */ public function itShouldAnalyseAllFiles() { $files = [fixture('MyClass.php')]; $nodes = [$this->node]; $parseRes = $this->parser->parse(Argument::type('string')); $this->parser->parse(Argument::type('string'))->shouldBeCalled()->willReturn($nodes); $this->nodeTraverser->traverse($nodes)->shouldBeCalled(); $this->analyser->analyse($files); }
/** * @param string $code * @param int $lineNumber * @return Node */ public function parse($code, $lineNumber) { $stmts = $this->parser->parse($code); $this->nodeVisitor->setLine($lineNumber); $this->nodeTraverser->addVisitor($this->nodeVisitor); $this->nodeTraverser->traverse($stmts); $node = $this->nodeVisitor->getNode(); return $node; }
/** * @param PhpFileInfo $phpFileInfo * * @return PhpFileInfo */ public function parseFile(PhpFileInfo $phpFileInfo) { $nodes = $this->parse($phpFileInfo->getContents()); $nodes = $this->nameResolver->traverse($nodes); $nodes = $this->staticTraverser->traverse($nodes); foreach ($this->violationVisitors as $visitor) { $visitor->setPhpFileInfo($phpFileInfo); } $this->violationTraverser->traverse($nodes); return $phpFileInfo; }
/** * @param string $file */ public function scan($file) { // Set the current file used by the registry so that we can tell where the change was scanned. $this->registry->setCurrentFile($file); $code = file_get_contents($file); try { $statements = $this->parser->parse($code); $this->traverser->traverse($statements); } catch (Error $e) { throw new RuntimeException('Parse Error: ' . $e->getMessage() . ' in ' . $file); } }
/** * @param $code * @param $sourcePath * @return Model */ public function parse($code, $sourcePath) { try { $stmts = $this->parser->parse($code); $stmts = $this->traverser->traverse($stmts); if ($this->namespaceParser->match($stmts)) { $this->namespaceParser->parse($stmts, $sourcePath); } } catch (PhpParserError $e) { throw new ParseException('Parse Error: ' . $e->getMessage()); } return $this->model; }
/** * @param string $filePath * * @throws TombstoneExtractionException */ public function extractTombstones($filePath) { $this->visitor->setCurrentFile($filePath); if (!is_readable($filePath)) { throw new TombstoneExtractionException('File "' . $filePath . '" is not readable.'); } try { $code = file_get_contents($filePath); $stmts = $this->parser->parse($code); $this->traverser->traverse($stmts); } catch (Error $e) { throw new TombstoneExtractionException('PHP code in "' . $filePath . '" could not be parsed.', null, $e); } }
/** * @param array $classMap * @param bool $noComments */ public function minify(array $classMap, $noComments) { if ($noComments) { $this->printer->disableComments(); } file_put_contents($this->target, "<?php "); foreach ($classMap as $file) { if ($stmts = $this->parser->parse(file_get_contents($file))) { $stmts = $this->traverser->traverse($stmts); $code = $this->printer->prettyPrintFile($stmts); file_put_contents($this->target, $code, FILE_APPEND); } } }
/** * Parses a content of the file and returns a transformed one * * @param string $content Source code to parse * * @return string Transformed source code */ public static function parse($content) { $astNodes = self::$parser->parse($content); $astNodes = self::$traverser->traverse($astNodes); $content = self::$printer->prettyPrintFile($astNodes); return $content; }
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); }
/** * @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); }
/** * @param \SplFileInfo $file * @param MessageCatalogue $catalogue * @param array $ast */ public function visitPhpFile(\SplFileInfo $file, MessageCatalogue $catalogue, array $ast) { $this->file = $file; $this->namespace = ''; $this->catalogue = $catalogue; $this->traverser->traverse($ast); }
private function traverse(array $nodes, NodeTraverser $traverser) { foreach ($nodes as $file => $stmts) { $this->dispatcher->dispatch(new ChangeFile($file)); $traverser->traverse($stmts); } }
/** * @param array $nodes * @return \PhpParser\Node[] */ public function traverse(array $nodes) { NodeStateStack::getInstance()->pushVars(); $ret = parent::traverse($nodes); NodeStateStack::getInstance()->popVars(); return $ret; }
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(); } }
/** * 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; }
/** * @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; }
/** * @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); }
/** * @param \Iterator|SplFileInfo[] $files * @return array */ public function extractClassMapFrom(\Iterator $files) { foreach ($files as $file) { if ($stmts = $this->parser->parse($file->getContents())) { $this->traverser->traverse($stmts); $this->collector->reset(); } } $classMap = $this->collector->getClassMap(); $classMap = $this->removeUnloadableClassesFrom($classMap); $classMap = $this->sort($classMap); $classFileMap = array(); foreach ($classMap as $class) { $classFileMap[$class] = $this->classloader->findFile($class); } return $classFileMap; }
public function __construct(array $ast) { $this->ast = $ast; $this->visitor = new ExtractNames(); $traverser = new NodeTraverser(); $traverser->addVisitor($this->visitor); $traverser->traverse($this->ast); }
public function testMultiClass() { $source = <<<'PHP' <?php class Foo { var $uses = ["Foo", "Bar"]; } class Bar { } PHP; $tree = $this->parser->parse($source); $this->traverser->traverse($tree); $classes = $this->visitor->getClasses(); $this->assertSame(2, count($classes)); $this->assertSame('Foo', $classes[0]->name); $this->assertSame('Bar', $classes[1]->name); }
public function validate($code) { $traverser = new NodeTraverser(); $traverser->addVisitor($this->visitor); $code = "<?php\n" . $code; $ast = $this->parser->parse($code); $traverser->traverse($ast); }
private function getVariableAccesses(FunctionLike $function) : array { $traverser = new NodeTraverser(); $accessLocator = new VariableAccessLocatorVisitor(); $traverser->addVisitor(new FunctionScopeIsolatingVisitor($accessLocator)); $traverser->traverse([$function->getStmts()]); return $accessLocator->getFoundVariableAccesses(); }
/** * @param Project $project */ public function analyze(Project $project) { $traverser = new NodeTraverser(); $traverser->addVisitor(new PhpParserNameResolver()); foreach ($project->getFiles() as $file) { $traverser->traverse($file->getTree()); } }
/** * Index it! * * @return VariableIndex */ public function index() { $index = new VariableIndex(); $traverser = new NodeTraverser(); $visitor = new BasicVariableIndexerVisitor($this->file, $index); $traverser->addVisitor($visitor); $traverser->traverse($this->nodes->getArrayCopy()); return $index; }
/** * 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); }
/** * 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())); }