NodeFinderTest.php 2.3 KB

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