addVisitor() public méthode

Adds a visitor.
public addVisitor ( PHPParser_NodeVisitor $visitor )
$visitor PHPParser_NodeVisitor Visitor to add
 /**
  * Creates a new traverser object and adds visitors.
  *
  * @return \PHPParser_NodeTraverser
  */
 protected function createTraverser()
 {
     $node_traverser = new \PHPParser_NodeTraverser();
     $node_traverser->addVisitor(new \PHPParser_NodeVisitor_NameResolver());
     foreach ($this->visitors as $visitor) {
         $node_traverser->addVisitor($visitor);
     }
     return $node_traverser;
 }
Exemple #2
0
    /**
     * Gets a NodeTraverser instance with all converters registered in the right order.
     *
     * @return PHPParser_NodeTraverser
     */
    public function getTraverser() {
        $traverser = new PHPParser_NodeTraverser;
        $traverser->addVisitor(new PHPBackporter_Converter_Dir);
        $traverser->addVisitor(new PHPBackporter_Converter_Const);
        $traverser->addVisitor(new PHPBackporter_Converter_Lambda);
        $traverser->addVisitor(new PHPBackporter_Converter_Closure);
        $traverser->addVisitor(new PHPBackporter_Converter_Namespace);

        return $traverser;
    }
 public function __construct(DocParser $docParser, KernelInterface $kernel)
 {
     $this->docParser = $docParser;
     $bundles = $kernel->getBundles();
     foreach ($bundles as $bundle) {
         $this->bundles[$bundle->getNamespace()] = $bundle->getName();
     }
     $this->traverser = new \PHPParser_NodeTraverser();
     $this->traverser->addVisitor($this);
 }
 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;
 }
 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();
     }
 }
 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);
 }
 /**
  * @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));
 }
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;
    }
}
 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;
 }
Exemple #10
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);
 }
 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());
 }
 /**
  * @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());
 }
 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);
 }
Exemple #15
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);
    });
}
 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();
 }
Exemple #17
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;
 }
 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);
 }
Exemple #19
0
 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;
     }
 }
 /**
  * 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) {
     }
 }
 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);
 }
 /**
  * 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)
 {
     return;
     $parser = new PHPParser_Parser(new PHPParser_Lexer());
     $visitor = new Symfony2_Sniffs_ObjectCalisthenics_UseAccessorsSniff_NodeVisitor();
     $visitor->setPHPCodeSnifferFile($phpcsFile);
     $traverser = new PHPParser_NodeTraverser();
     $traverser->addVisitor($visitor);
     try {
         $code = file_get_contents($phpcsFile->getFilename());
         $tree = $parser->parse($code);
         //$tree[0]->setAttribute('visited', true);
         var_dump($tree);
     } catch (PHPParser_Error $e) {
     }
     die;
 }
 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));
 }
Exemple #24
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;
     }
 }
Exemple #25
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);
             }
         }
     }
 }
Exemple #27
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);
    }
Exemple #29
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();
}
 public function testRemovingVisitor()
 {
     $visitor1 = $this->getMock('PHPParser_NodeVisitor');
     $visitor2 = $this->getMock('PHPParser_NodeVisitor');
     $visitor3 = $this->getMock('PHPParser_NodeVisitor');
     $traverser = new PHPParser_NodeTraverser();
     $traverser->addVisitor($visitor1);
     $traverser->addVisitor($visitor2);
     $traverser->addVisitor($visitor3);
     $preExpected = array($visitor1, $visitor2, $visitor3);
     $this->assertAttributeSame($preExpected, 'visitors', $traverser, 'The appropriate visitors have not been added');
     $traverser->removeVisitor($visitor2);
     $postExpected = array(0 => $visitor1, 2 => $visitor3);
     $this->assertAttributeSame($postExpected, 'visitors', $traverser, 'The appropriate visitors are not present after removal');
 }