1<?php declare(strict_types=1);
2
3namespace PhpParser;
4
5use PhpParser\Node\Expr;
6
7class NodeFinderTest extends \PHPUnit\Framework\TestCase {
8    private function getStmtsAndVars() {
9        $assign = new Expr\Assign(new Expr\Variable('a'), new Expr\BinaryOp\Concat(
10            new Expr\Variable('b'), new Expr\Variable('c')
11        ));
12        $stmts = [new Node\Stmt\Expression($assign)];
13        $vars = [$assign->var, $assign->expr->left, $assign->expr->right];
14        return [$stmts, $vars];
15    }
16
17    public function testFind(): void {
18        $finder = new NodeFinder();
19        list($stmts, $vars) = $this->getStmtsAndVars();
20        $varFilter = function (Node $node) {
21            return $node instanceof Expr\Variable;
22        };
23        $this->assertSame($vars, $finder->find($stmts, $varFilter));
24        $this->assertSame($vars, $finder->find($stmts[0], $varFilter));
25
26        $noneFilter = function () {
27            return false;
28        };
29        $this->assertSame([], $finder->find($stmts, $noneFilter));
30    }
31
32    public function testFindInstanceOf(): void {
33        $finder = new NodeFinder();
34        list($stmts, $vars) = $this->getStmtsAndVars();
35        $this->assertSame($vars, $finder->findInstanceOf($stmts, Expr\Variable::class));
36        $this->assertSame($vars, $finder->findInstanceOf($stmts[0], Expr\Variable::class));
37        $this->assertSame([], $finder->findInstanceOf($stmts, Expr\BinaryOp\Mul::class));
38    }
39
40    public function testFindFirst(): void {
41        $finder = new NodeFinder();
42        list($stmts, $vars) = $this->getStmtsAndVars();
43        $varFilter = function (Node $node) {
44            return $node instanceof Expr\Variable;
45        };
46        $this->assertSame($vars[0], $finder->findFirst($stmts, $varFilter));
47        $this->assertSame($vars[0], $finder->findFirst($stmts[0], $varFilter));
48
49        $noneFilter = function () {
50            return false;
51        };
52        $this->assertNull($finder->findFirst($stmts, $noneFilter));
53    }
54
55    public function testFindFirstInstanceOf(): void {
56        $finder = new NodeFinder();
57        list($stmts, $vars) = $this->getStmtsAndVars();
58        $this->assertSame($vars[0], $finder->findFirstInstanceOf($stmts, Expr\Variable::class));
59        $this->assertSame($vars[0], $finder->findFirstInstanceOf($stmts[0], Expr\Variable::class));
60        $this->assertNull($finder->findFirstInstanceOf($stmts, Expr\BinaryOp\Mul::class));
61    }
62}
63