Repository navigation
Expand file tree
/
Copy pathNodeFinder.php
More file actions
78 lines (65 loc) · 1.82 KB
/
Copy pathNodeFinder.php
File metadata and controls
78 lines (65 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
declare(strict_types=1);
/*
* This file is part of the PHPRegex package.
*
* (c) Younes ENNAJI <younes.ennaji.pro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPRegex\Parser;
use PHPRegex\Parser\Node\NodeInterface;
/**
* Finds the nodes of a tree that pass a test, in the order they stand in the
* pattern.
*
* @phpstan-type NodeFilter \Closure(NodeInterface): bool
*/
final class NodeFinder
{
/**
* @param NodeFilter $filter
*
* @return list<NodeInterface>
*/
public static function find(NodeInterface $root, \Closure $filter): array
{
$found = [];
NodeWalker::walk($root, static function (NodeInterface $node) use ($filter, &$found): ?TraversalAction {
if ($filter($node)) {
$found[] = $node;
}
return null;
});
return $found;
}
/**
* @template T of \PHPRegex\Parser\Node\NodeInterface
*
* @param class-string<T> $class
*
* @return list<T>
*/
public static function findInstanceOf(NodeInterface $root, string $class): array
{
/** @var list<T> $found */
$found = self::find($root, static fn (NodeInterface $node): bool => $node instanceof $class);
return $found;
}
/**
* @param NodeFilter $filter
*/
public static function findFirst(NodeInterface $root, \Closure $filter): ?NodeInterface
{
$first = null;
NodeWalker::walk($root, static function (NodeInterface $node) use ($filter, &$first): ?TraversalAction {
if (!$filter($node)) {
return null;
}
$first = $node;
return TraversalAction::Stop;
});
return $first;
}
}