Нема описа

NodeFinder.php 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php declare(strict_types=1);
  2. namespace PhpParser;
  3. use PhpParser\NodeVisitor\FindingVisitor;
  4. use PhpParser\NodeVisitor\FirstFindingVisitor;
  5. class NodeFinder
  6. {
  7. /**
  8. * Find all nodes satisfying a filter callback.
  9. *
  10. * @param Node|Node[] $nodes Single node or array of nodes to search in
  11. * @param callable $filter Filter callback: function(Node $node) : bool
  12. *
  13. * @return Node[] Found nodes satisfying the filter callback
  14. */
  15. public function find($nodes, callable $filter) : array {
  16. if (!is_array($nodes)) {
  17. $nodes = [$nodes];
  18. }
  19. $visitor = new FindingVisitor($filter);
  20. $traverser = new NodeTraverser;
  21. $traverser->addVisitor($visitor);
  22. $traverser->traverse($nodes);
  23. return $visitor->getFoundNodes();
  24. }
  25. /**
  26. * Find all nodes that are instances of a certain class.
  27. *
  28. * @param Node|Node[] $nodes Single node or array of nodes to search in
  29. * @param string $class Class name
  30. *
  31. * @return Node[] Found nodes (all instances of $class)
  32. */
  33. public function findInstanceOf($nodes, string $class) : array {
  34. return $this->find($nodes, function ($node) use ($class) {
  35. return $node instanceof $class;
  36. });
  37. }
  38. /**
  39. * Find first node satisfying a filter callback.
  40. *
  41. * @param Node|Node[] $nodes Single node or array of nodes to search in
  42. * @param callable $filter Filter callback: function(Node $node) : bool
  43. *
  44. * @return null|Node Found node (or null if none found)
  45. */
  46. public function findFirst($nodes, callable $filter) {
  47. if (!is_array($nodes)) {
  48. $nodes = [$nodes];
  49. }
  50. $visitor = new FirstFindingVisitor($filter);
  51. $traverser = new NodeTraverser;
  52. $traverser->addVisitor($visitor);
  53. $traverser->traverse($nodes);
  54. return $visitor->getFoundNode();
  55. }
  56. /**
  57. * Find first node that is an instance of a certain class.
  58. *
  59. * @param Node|Node[] $nodes Single node or array of nodes to search in
  60. * @param string $class Class name
  61. *
  62. * @return null|Node Found node, which is an instance of $class (or null if none found)
  63. */
  64. public function findFirstInstanceOf($nodes, string $class) {
  65. return $this->findFirst($nodes, function ($node) use ($class) {
  66. return $node instanceof $class;
  67. });
  68. }
  69. }