当前位置: 首页>>代码示例>>PHP>>正文


PHP PhpParser\NodeTraverser类代码示例

本文整理汇总了PHP中PhpParser\NodeTraverser的典型用法代码示例。如果您正苦于以下问题:PHP NodeTraverser类的具体用法?PHP NodeTraverser怎么用?PHP NodeTraverser使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了NodeTraverser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: resolveConstructor

 /**
  * @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;
 }
开发者ID:slde-rorschach,项目名称:deprecation-detector,代码行数:38,代码来源:ConstructorResolver.php

示例2: loadRules

 /**
  * @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;
 }
开发者ID:koktut,项目名称:hexlet-psr-linter,代码行数:37,代码来源:RulesLoader.php

示例3: setUp

 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);
 }
开发者ID:trismegiste,项目名称:phpunit-assert-solid,代码行数:7,代码来源:VisitorTestCase.php

示例4: test

 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();
     }
 }
开发者ID:jdgrimes,项目名称:wp-plugin-uninstall-scanner,代码行数:25,代码来源:TestCase.php

示例5: getTags

 /**
  * 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;
 }
开发者ID:jorissteyn,项目名称:phptags,代码行数:35,代码来源:Parser.php

示例6: check

 /**
  * @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);
 }
开发者ID:jacmoe,项目名称:php-workshop,代码行数:37,代码来源:FunctionRequirementsCheck.php

示例7: traverse

 private function traverse(array $nodes, NodeTraverser $traverser)
 {
     foreach ($nodes as $file => $stmts) {
         $this->dispatcher->dispatch(new ChangeFile($file));
         $traverser->traverse($stmts);
     }
 }
开发者ID:niktux,项目名称:solidifier,代码行数:7,代码来源:Analyzer.php

示例8: setUp

 protected function setUp()
 {
     $this->traverser = new NodeTraverser();
     $this->visitor = new ClassVisitor();
     $this->traverser->addVisitor($this->visitor);
     $this->parser = new Parser(new Lexer());
 }
开发者ID:mfn,项目名称:cakephp2-magic-properties,代码行数:7,代码来源:ClassVisitorTest.php

示例9: handle

 /**
  * @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);
 }
开发者ID:rskuipers,项目名称:php-assumptions,代码行数:38,代码来源:Cli.php

示例10: implement

 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);
 }
开发者ID:killer100,项目名称:PhpGenerics,代码行数:31,代码来源:Engine.php

示例11: lint

 /**
  * @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;
 }
开发者ID:koktut,项目名称:hexlet-psr-linter,代码行数:36,代码来源:PsrLinter.php

示例12: getMagentoVersion

 /**
  * @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);
 }
开发者ID:magento-ecg,项目名称:magento-finder,代码行数:12,代码来源:Helper.php

示例13: __construct

 public function __construct(array $ast)
 {
     $this->ast = $ast;
     $this->visitor = new ExtractNames();
     $traverser = new NodeTraverser();
     $traverser->addVisitor($this->visitor);
     $traverser->traverse($this->ast);
 }
开发者ID:knuthelland,项目名称:phpimports,代码行数:8,代码来源:ScopeAnalyzer.php

示例14: 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());
     }
 }
开发者ID:mfn,项目名称:php-analyzer,代码行数:11,代码来源:NameResolver.php

示例15: validate

 public function validate($code)
 {
     $traverser = new NodeTraverser();
     $traverser->addVisitor($this->visitor);
     $code = "<?php\n" . $code;
     $ast = $this->parser->parse($code);
     $traverser->traverse($ast);
 }
开发者ID:paslandau,项目名称:php-sandbox,代码行数:8,代码来源:Sandbox.php


注:本文中的PhpParser\NodeTraverser类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。