traverse() public method

Traverses an array of nodes using the registered visitors.
public traverse ( array $nodes ) : PHPParser_Node[]
$nodes array Array of nodes
return PHPParser_Node[] Traversed array of nodes
Esempio n. 1
0
 public static function parse($code)
 {
     $lexer = new \PHPParser_Lexer($code);
     $parser = new \PHPParser_Parser();
     $ast = $parser->parse($lexer);
     $traverser = new \PHPParser_NodeTraverser();
     $traverser->addVisitor(new NormalizingNodeVisitor());
     $traverser->addVisitor(new \PHPParser_NodeVisitor_NameResolver());
     $ast = $traverser->traverse($ast);
     switch (count($ast)) {
         case 0:
             $ast = new BlockNode(array());
             break;
         case 1:
             $ast = $ast[0];
             break;
         default:
             $ast = new BlockNode($ast);
     }
     // This is currently only available when using the schmittjoh/PHP-Parser fork.
     if (class_exists('PHPParser_NodeVisitor_NodeConnector')) {
         $traverser = new \PHPParser_NodeTraverser();
         $traverser->addVisitor(new \PHPParser_NodeVisitor_NodeConnector());
         $traverser->traverse(array($ast));
     }
     return $ast;
 }
Esempio n. 2
0
 private function splitStmtsAndProps($stmts_old)
 {
     $stmts = array();
     $props = array();
     $constructor = false;
     $this->prop_names = array();
     $traverser = new PHPParser_NodeTraverser();
     $traverser->addVisitor(new PHPParser_Node_Stmt_Class_Traverse($this));
     foreach ($stmts_old as $stmt) {
         if ($stmt instanceof PHPParser_Node_Expr_AssignClassProperty) {
             $stmts_traversed = $traverser->traverse(array($stmt));
             $stmt = $stmts_traversed[0];
             $props[] = $stmt;
             $this->prop_names[$stmt->var->name] = true;
         } elseif ($stmt instanceof PHPParser_Node_Stmt_ClassMethod && $stmt->name == '__construct') {
             if ($constructor !== false) {
                 throw new PHPParser_Error("Only one __construct method allow per class.");
             }
             $constructor = $stmt->stmts;
         } else {
             $stmts[] = $stmt;
         }
     }
     $this->prop_names = array();
     return array($stmts, $props, $constructor);
 }
Esempio n. 3
0
function snowscript_to_php($code, $debug = false, $return = false, $namespace = "Anonymous")
{
    $lexer = new Snowscript_Lexer($code . "\n");
    if ($debug) {
        debug_lexer($lexer);
    }
    $parser = new PHPParser_Parser();
    $prettyPrinter = new PHPParser_PrettyPrinter_Zend();
    $stmts = $parser->parse($lexer);
    $traverser = new PHPParser_NodeTraverser();
    $scope_traverser = new Snowscript_Visitors_Scope($namespace);
    $traverser->addVisitor($scope_traverser);
    $stmts = $traverser->traverse($stmts);
    $nodeDumper = new PHPParser_NodeDumper();
    if ($debug) {
        $nodeDumper = new PHPParser_NodeDumper();
        echo $nodeDumper->dump($stmts) . "\n";
    }
    $php = $prettyPrinter->prettyPrint($stmts) . "\n";
    if ($return) {
        return $php;
    } else {
        print "<?php\n" . $php;
    }
}
 /**
  * @dataProvider getTests
  */
 public function testIntegration($sourceFile)
 {
     $parser = new \PHPParser_Parser();
     $ast = $parser->parse(new \PHPParser_Lexer(file_get_contents($sourceFile)));
     $traverser = new \PHPParser_NodeTraverser();
     $traverser->addVisitor(new \PHPParser_NodeVisitor_NameResolver());
     $traverser->addVisitor(new NormalizingNodeVisitor());
     $ast = $traverser->traverse($ast);
     if (count($ast) > 1) {
         $ast = array(new BlockNode($ast));
     }
     $traverser = new \PHPParser_NodeTraverser();
     $traverser->addVisitor(new \PHPParser_NodeVisitor_NodeConnector());
     $traverser->traverse($ast);
     // do _NOT_ assign the ast here as it clones the nodes on traversal and leads to problems
     $cfa = new ControlFlowAnalysis();
     $cfa->process($ast[0]);
     $cfg = $cfa->getGraph();
     $serializer = new GraphvizSerializer();
     $dot = $serializer->serialize($cfg);
     $dotFile = substr($sourceFile, 0, -4) . '.dot';
     if (!is_file($dotFile)) {
         file_put_contents($dotFile . '.tmp', $dot);
         $this->fail(sprintf('Dotfile "%s" does not exist, wrote current output to "%s".', $dotFile, basename($dotFile . '.tmp')));
     }
     $this->assertSame($dot, file_get_contents($dotFile));
 }
 private function getCfg(\PHPParser_Node $ast)
 {
     $traverser = new \PHPParser_NodeTraverser();
     $traverser->addVisitor(new \PHPParser_NodeVisitor_NodeConnector());
     $traverser->traverse(array($ast));
     $cfa = new ControlFlowAnalysis();
     $cfa->process($ast);
     return $this->graph = $cfa->getGraph();
 }
 public function testWithTraverser()
 {
     $file = new \Trismegiste\Mondrian\Parser\PhpFile('/I/Am/Victory.php', array(new \PHPParser_Node_Stmt_Class('Victory', array(), array('comments' => array(new \PHPParser_Comment('@mondrian contractor SomeNewContract'))))));
     $traverser = new \PHPParser_NodeTraverser();
     $traverser->addVisitor($this->visitor);
     $this->assertFalse($file->isModified());
     $traverser->traverse(array($file));
     $this->assertTrue($file->isModified());
 }
 public function testVisitorFiltersByClassName()
 {
     $filePath = __DIR__ . '/../../Fixtures/PhpParser/classes_namespaced.php';
     $className = 'Bah';
     $traverser = new \PHPParser_NodeTraverser();
     $traverser->addVisitor(new ClassFilterVisitor($className));
     $nodes = $traverser->traverse($this->parse($filePath));
     $this->assertCount(1, $nodes);
     $this->assertEquals($className, $nodes[0]->name);
 }
 /**
  * @test
  */
 public function givenAssignmentAndReadOfSameVariable_WhenClassification_ThenFindBoth()
 {
     $classifier = new LocalVariableClassifier();
     $assign = new \PHPParser_Node_Expr_Assign(new \PHPParser_Node_Expr_Variable("foo"), new \PHPParser_Node_Expr_Variable("foo"));
     $traverser = new \PHPParser_NodeTraverser();
     $traverser->addVisitor($classifier);
     $traverser->traverse(array($assign));
     $this->assertEquals(array('foo' => array(-1)), $classifier->getAssignments());
     $this->assertEquals(array('foo' => array(-1)), $classifier->getLocalVariables());
 }
Esempio n. 9
0
function transform_with_visitors($code, array $visitors)
{
    return transform_code($code, function ($ast) use($code, $visitors) {
        $traverser = new \PHPParser_NodeTraverser();
        foreach ($visitors as $visitor) {
            $traverser->addVisitor($visitor);
        }
        return $traverser->traverse($ast);
    });
}
Esempio n. 10
0
 /**
  * Parses given file and returns found gettext phrases
  *
  * @param string $file
  * @return array
  */
 public function extract($file)
 {
     $this->data = array();
     $parser = new PHPParser_Parser(new PHPParser_Lexer());
     $stmts = $parser->parse(file_get_contents($file));
     $traverser = new PHPParser_NodeTraverser();
     $traverser->addVisitor($this);
     $traverser->traverse($stmts);
     $data = $this->data;
     $this->data = null;
     return $data;
 }
Esempio n. 11
0
 public function configParser()
 {
     if (file_exists($this->getConfigPath(false))) {
         $parser = new \PHPParser_Parser(new \PHPParser_Lexer());
         $traverser = new \PHPParser_NodeTraverser();
         $traverser->addVisitor(new ConfigVisitor());
         $statements = $parser->parse(file_get_contents($this->getConfigPath(false)));
         $traverser->traverse($statements);
         return ConfigVisitor::getConfigValues();
     }
     return array();
 }
 public function searchForHooksInFile($filename, $phpFile)
 {
     $code = file_get_contents($phpFile);
     if (false === strpos($code, 'postEvent')) {
         return array();
     }
     $stmts = $this->parser->parse($code);
     $traverser = new \PHPParser_NodeTraverser();
     $traverser->addVisitor(new MyConstantVisitor());
     $traverser->addVisitor(new MyHookVisitor($filename));
     $hooks = $traverser->traverse($stmts);
     return $hooks;
 }
Esempio n. 13
0
 public function testWithTraverser()
 {
     $this->context->expects($this->once())->method('hasNewContract')->with('Pull\\Me\\Under')->will($this->returnValue(true));
     $this->context->expects($this->once())->method('getNewContract')->with('Pull\\Me\\Under')->will($this->returnValue('Awake'));
     $classNode = new \PHPParser_Node_Stmt_Class('Victory', array('stmts' => array(new \PHPParser_Node_Stmt_ClassMethod('holy', array('params' => array(new \PHPParser_Node_Param('war', null, new \PHPParser_Node_Name('Pull\\Me\\Under'))))))), array('comments' => array(new \PHPParser_Comment('@mondrian contractor SomeNewContract'))));
     $file = new \Trismegiste\Mondrian\Parser\PhpFile('/I/Am/Victory.php', array($classNode));
     $traverser = new \PHPParser_NodeTraverser();
     $traverser->addVisitor($this->visitor);
     $this->assertFalse($file->isModified());
     $traverser->traverse(array($file));
     $this->assertTrue($file->isModified());
     $this->assertEquals('Awake', (string) $classNode->stmts[0]->params[0]->type);
 }
Esempio n. 14
0
 public function traverse($contents)
 {
     $parser = new \PHPParser_Parser(new \PHPParser_Lexer());
     $node_traverser = new \PHPParser_NodeTraverser();
     $node_traverser->addVisitor(new \PHPParser_NodeVisitor_NameResolver());
     $node_traverser->addVisitor($this->visitor);
     try {
         $stmts = $parser->parse($contents);
         $node_traverser->traverse($stmts);
     } catch (\PHPParser_Error $e) {
         echo 'Parse Error: ', $e->getMessage();
     }
 }
 /**
  * Processes this test, when one of its tokens is encountered.
  *
  * @param PHP_CodeSniffer_File $phpcsFile All the tokens found in the document.
  * @param int                  $stackPtr  The position of the current token in
  *                                        the stack passed in $tokens.
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     $parser = new PHPParser_Parser(new PHPParser_Lexer());
     $visitor = new Symfony2_Sniffs_ObjectCalisthenics_SmallClassSniff_NodeVisitor();
     $visitor->setPHPCodeSnifferFile($phpcsFile);
     $traverser = new PHPParser_NodeTraverser();
     $traverser->addVisitor($visitor);
     try {
         $code = file_get_contents($phpcsFile->getFilename());
         $tree = $parser->parse($code);
         $tree = $traverser->traverse($tree);
     } catch (PHPParser_Error $e) {
     }
 }
 protected function analyzeAst($fixtureName)
 {
     if (!is_file($path = __DIR__ . '/Fixture/' . $fixtureName)) {
         throw new \InvalidArgumentException(sprintf('The fixture file "%s" does not exist.', $path));
     }
     $parser = new \PHPParser_Parser();
     $ast = $parser->parse(new \PHPParser_Lexer(file_get_contents($path)));
     $traverser = new \PHPParser_NodeTraverser();
     $traverser->addVisitor(new \PHPParser_NodeVisitor_NameResolver());
     foreach ($this->getVisitors() as $visitor) {
         $traverser->addVisitor($visitor);
     }
     return $traverser->traverse($ast);
 }
 public function testWithTraverser()
 {
     $classNode = new \PHPParser_Node_Stmt_Class('Victory', array('stmts' => array(new \PHPParser_Node_Stmt_ClassMethod('holy', array('stmts' => array(new \PHPParser_Node_Expr_New(new \PHPParser_Node_Name('Holy\\War')), new \PHPParser_Node_Expr_New(new \PHPParser_Node_Name('\\Hangar18'))))))));
     $file = new \Trismegiste\Mondrian\Parser\PhpFile('/I/Am/Victory.php', array($classNode));
     $traverser = new \PHPParser_NodeTraverser();
     $traverser->addVisitor($this->visitor);
     $this->assertFalse($file->isModified());
     $traverser->traverse(array($file));
     $this->assertTrue($file->isModified());
     $this->assertCount(3, $classNode->stmts);
     $pp = new \PHPParser_PrettyPrinter_Default();
     $flat = $pp->prettyPrint(iterator_to_array($file->getIterator()));
     eval($flat);
 }
 private function createScope($src)
 {
     $lexer = new \PHPParser_Lexer('<?php class Foo { public function foo($param1, $param2) { ' . $src . ' } }');
     $parser = new \PHPParser_Parser();
     $ast = $parser->parse($lexer);
     $traverser = new \PHPParser_NodeTraverser();
     $traverser->addVisitor(new \PHPParser_NodeVisitor_NameResolver());
     $traverser->addVisitor(new NormalizingNodeVisitor());
     $ast = $traverser->traverse($ast);
     $traverser = new \PHPParser_NodeTraverser();
     $traverser->addVisitor(new \PHPParser_NodeVisitor_NodeConnector());
     $traverser->traverse($ast);
     $rootNode = $ast[0];
     $scopeRoot = $ast[0]->stmts[0];
     $sc = new SyntacticScopeCreator();
     return $sc->createScope($scopeRoot, new Scope($rootNode));
 }
Esempio n. 19
0
File: Php.php Progetto: layla/cody
 public function getFullyQualifiedClassName($file)
 {
     // use the emulative lexer here, as we are running PHP 5.2 but want to parse PHP 5.3
     $parser = new \PHPParser_Parser(new \PHPParser_Lexer());
     $traverser = new \PHPParser_NodeTraverser();
     $prettyPrinter = new \PHPParser_PrettyPrinter_Default();
     $nameSaver = new NamespaceConverter();
     $traverser->addVisitor(new \PHPParser_NodeVisitor_NameResolver());
     // we will need resolved names
     $traverser->addVisitor($nameSaver);
     try {
         // read the file that should be converted
         $code = file_get_contents($file);
         // parse
         $stmts = $parser->parse($code);
         // traverse
         $stmts = $traverser->traverse($stmts);
         return $nameSaver->name;
     } catch (PHPParser_Error $e) {
         return false;
     }
 }
Esempio n. 20
0
 public function enterNode(\PHPParser_Node $node)
 {
     if ($node instanceof \PHPParser_Node_Stmt_Class) {
         foreach ($node->stmts as $statement) {
             if ($statement instanceof \PHPParser_Node_Stmt_TraitUse) {
                 $stmts = [$node->stmts];
                 foreach ($statement->traits as $traitName) {
                     if ($this->traitsCollector->hasTrait((string) $traitName)) {
                         $trait = $this->traitsCollector->getTrait((string) $traitName);
                         $traverser = new \PHPParser_NodeTraverser();
                         $traverser->addVisitor(new Traits_ConflictResolver($node, $trait, $statement));
                         $stmts[] = $traverser->traverse($trait->stmts);
                     } else {
                         throw new \Exception(sprintf('Could not find referenced trait "%s"', $traitName));
                     }
                 }
                 $node->stmts = call_user_func_array('array_merge', $stmts);
             }
         }
         return $node;
     }
 }
Esempio n. 21
0
 public function cache()
 {
     $parser = new \PHPParser_Parser(new \PHPParser_Lexer());
     $prettyPrinter = new \PHPParser_PrettyPrinter_Default();
     try {
         $searched_function[] = "validate_username";
         $traverser_safety = new \PHPParser_NodeTraverser();
         $traverser_safety->addVisitor(new SafeFunction($searched_function));
         // parse
         $raw = file_get_contents($this->path_to_wp . '/wp-includes/user.' . $this->phpEx);
         $stmts = $parser->parse($raw);
         // traverse
         $stmts = $traverser_safety->traverse($stmts);
         // pretty print
         $code = $prettyPrinter->prettyPrint($stmts);
         file_put_contents($this->phpbb_root_path . 'cache/phpbbwpunicorn_user.' . $this->phpEx, '<?php ' . $code . ' ?>');
     } catch (PHPParser\Error $e) {
         echo 'Parse Error: ', $e->getMessage();
     }
     $parser = new \PHPParser_Parser(new \PHPParser_Lexer());
     $prettyPrinter = new \PHPParser_PrettyPrinter_Default();
     try {
         $searched_function[] = "make_clickable";
         $traverser_safety = new \PHPParser_NodeTraverser();
         $traverser_safety->addVisitor(new SafeFunction($searched_function));
         // parse
         $raw = file_get_contents($this->path_to_wp . '/wp-includes/formatting.' . $this->phpEx);
         $stmts = $parser->parse($raw);
         // traverse
         $stmts = $traverser_safety->traverse($stmts);
         // pretty print
         $code = $prettyPrinter->prettyPrint($stmts);
         file_put_contents($this->phpbb_root_path . 'cache/phpbbwpunicorn_formatting.' . $this->phpEx, '<?php ' . $code . ' ?>');
     } catch (PHPParser\Error $e) {
         echo 'Parse Error: ', $e->getMessage();
     }
 }
 public function visitPhpFile(\SplFileInfo $file, MessageCatalogue $catalogue, array $ast)
 {
     $this->catalogue = $catalogue;
     // Traverse document to assemble class name
     $traverser = new \PHPParser_NodeTraverser();
     $traverser->addVisitor($this);
     $traverser->traverse($ast);
     if ($this->annotated) {
         // Get annotations for the class
         $annotationDriver = new Annotation(new DoctrineAnnotationReader());
         $manager = new Manager();
         $manager->addDriver($annotationDriver, -1);
         $metadata = $manager->getMetadata($this->parsedClassName);
         // Save messages for title
         foreach ($metadata->getFields() as $field) {
             $mappedField = $metadata->getFieldMapping($field);
             if ((!isset($mappedField['visible']) || $mappedField['visible']) && isset($mappedField['title'])) {
                 $message = new Message($mappedField['title']);
                 $message->addSource(new FileSource((string) $file));
                 $catalogue->add($message);
             }
         }
     }
 }
Esempio n. 23
0
 /**
  * @expectedException        PHPParser_Error
  * @expectedExceptionMessage Cannot use "C" as "B" because the name is already in use on line 2
  */
 public function testAlreadyInUseError()
 {
     $stmts = array(new PHPParser_Node_Stmt_Use(array(new PHPParser_Node_Stmt_UseUse(new PHPParser_Node_Name('A\\B'), 'B', array('startLine' => 1)), new PHPParser_Node_Stmt_UseUse(new PHPParser_Node_Name('C'), 'B', array('startLine' => 2)))));
     $traverser = new PHPParser_NodeTraverser();
     $traverser->addVisitor(new PHPParser_NodeVisitor_NameResolver());
     $traverser->traverse($stmts);
 }
    public function testClassNameIsCaseInsensitive()
    {
        $source = <<<EOC
<?php
namespace Foo;
use Bar\\Baz;
\$test = new baz();
EOC;
        $parser = new PHPParser_Parser(new PHPParser_Lexer_Emulative());
        $stmts = $parser->parse($source);
        $traverser = new PHPParser_NodeTraverser();
        $traverser->addVisitor(new PHPParser_NodeVisitor_NameResolver());
        $stmts = $traverser->traverse($stmts);
        $stmt = $stmts[0];
        $this->assertEquals(array('Bar', 'Baz'), $stmt->stmts[1]->expr->class->parts);
    }
Esempio n. 25
0
            } else {
                if ($stmt instanceof PHPParser_Node_Name) {
                    $output[$k] = 'NAME       ' . $type;
                } else {
                    $output[$k] = 'UNKNOWN    ' . $type;
                }
            }
        }
    }
    return $output;
}
class MyNodeVisitor extends PHPParser_NodeVisitorAbstract
{
    public function leaveNode(PHPParser_Node $node)
    {
        if ($node instanceof PHPParser_Node_Scalar_String) {
            $node->value = 'foo';
        }
        print_r($node);
    }
}
try {
    $stmts = $parser->parse(file_get_contents(__FILE__));
    // print_r(parse_stmts($stmts));
    $traverser = new PHPParser_NodeTraverser();
    $traverser->addVisitor(new MyNodeVisitor());
    $stmts = $traverser->traverse($stmts);
    // print_r($stmts);
} catch (PHPParser_Error $e) {
    echo 'Parser error: ', $e->getMessage();
}
Esempio n. 26
0
 public function visitPhpFile(\SplFileInfo $file, MessageCatalogue $catalogue, array $ast)
 {
     $this->file = $file;
     $this->catalogue = $catalogue;
     $this->traverser->traverse($ast);
 }
 public function testDeepArray()
 {
     $strNode = new PHPParser_Node_Scalar_String('Foo');
     $stmts = array(array(array($strNode)));
     $visitor = $this->getMock('PHPParser_NodeVisitor');
     $visitor->expects($this->at(1))->method('enterNode')->with($strNode);
     $traverser = new PHPParser_NodeTraverser();
     $traverser->addVisitor($visitor);
     $this->assertEquals($stmts, $traverser->traverse($stmts));
 }
 private function assertAnnotatedAst(array $ast)
 {
     $traverser = new \PHPParser_NodeTraverser();
     $traverser->addVisitor($visitor = new AssertingVisitor($this));
     $traverser->traverse($ast);
 }
Esempio n. 29
0
 /** Validate passed callable for execution
  *
  * @example $sandbox->validate('<?php echo "Hello World!"; ?>');
  *
  * @param   callable|string $code      The callable or string of code to validate
  *
  * @return  PHPSandbox      Returns the PHPSandbox instance for chainability
  */
 public function validate($code)
 {
     $this->preparsed_code = $this->disassemble($code);
     $parser = new \PHPParser_Parser(new \PHPParser_Lexer_Emulative());
     try {
         $this->parsed_ast = $parser->parse($this->preparsed_code);
     } catch (\PHPParser_Error $error) {
         $this->validation_error("Could not parse sandboxed code!", Error::PARSER_ERROR, null, $this->preparsed_code, $error);
     }
     $prettyPrinter = new \PHPParser_PrettyPrinter_Default();
     if ($this->allow_functions && $this->auto_whitelist_functions || $this->allow_constants && $this->auto_whitelist_constants || $this->allow_classes && $this->auto_whitelist_classes || $this->allow_interfaces && $this->auto_whitelist_interfaces || $this->allow_traits && $this->auto_whitelist_traits || $this->allow_globals && $this->auto_whitelist_globals) {
         $traverser = new \PHPParser_NodeTraverser();
         $whitelister = new SandboxWhitelistVisitor($this);
         $traverser->addVisitor($whitelister);
         $traverser->traverse($this->parsed_ast);
     }
     $traverser = new \PHPParser_NodeTraverser();
     $validator = new ValidatorVisitor($this);
     $traverser->addVisitor($validator);
     $this->prepared_ast = $traverser->traverse($this->parsed_ast);
     $this->prepared_code = $prettyPrinter->prettyPrint($this->prepared_ast);
     return $this;
 }
Esempio n. 30
0
 private function processVars(array &$vars)
 {
     $traverser = new PHPParser_NodeTraverser();
     $traverser->addVisitor(new Snow_AssignList_Visitor());
     return $traverser->traverse($vars);
 }