1 | <?php |
||
2 | /** |
||
3 | * Copyright MediaCT. All rights reserved. |
||
4 | * https://www.mediact.nl |
||
5 | */ |
||
6 | |||
7 | namespace Mediact\DependencyGuard\Php; |
||
8 | |||
9 | use Mediact\DependencyGuard\Php\Filter\SymbolFilterInterface; |
||
10 | use PhpParser\Node; |
||
11 | use PhpParser\Node\Name; |
||
12 | use PhpParser\NodeVisitorAbstract; |
||
13 | |||
14 | class SymbolTracker extends NodeVisitorAbstract implements |
||
15 | SymbolTrackerInterface |
||
16 | { |
||
17 | /** @var bool[]|Name[][] */ |
||
18 | private $symbols = []; |
||
19 | |||
20 | /** @var SymbolFilterInterface */ |
||
21 | private $filter; |
||
22 | |||
23 | /** |
||
24 | * Constructor. |
||
25 | * |
||
26 | * @param SymbolFilterInterface $filter |
||
27 | */ |
||
28 | 6 | public function __construct(SymbolFilterInterface $filter) |
|
29 | { |
||
30 | 6 | $this->filter = $filter; |
|
31 | 6 | } |
|
32 | |||
33 | /** |
||
34 | * Track the given node. |
||
35 | * |
||
36 | * @param Node $node |
||
37 | * |
||
38 | * @return void |
||
39 | */ |
||
40 | 4 | public function enterNode(Node $node): void |
|
41 | { |
||
42 | 4 | $name = null; |
|
43 | |||
44 | 4 | if ($node instanceof Name) { |
|
45 | 4 | $name = $node->toString(); |
|
46 | } |
||
47 | |||
48 | 4 | if ($name === null |
|
49 | 4 | || (array_key_exists($name, $this->symbols) |
|
50 | 2 | && $this->symbols[$name] === false |
|
51 | ) |
||
52 | ) { |
||
53 | 1 | return; |
|
54 | } |
||
55 | |||
56 | 4 | if (!$this->filter->__invoke($name)) { |
|
57 | 2 | $this->symbols[$name] = false; |
|
58 | 2 | return; |
|
59 | } |
||
60 | |||
61 | 2 | if (!array_key_exists($name, $this->symbols)) { |
|
62 | 2 | $this->symbols[$name] = []; |
|
63 | } |
||
64 | |||
65 | 2 | $this->symbols[$name][] = $node; |
|
66 | 2 | } |
|
67 | |||
68 | /** |
||
69 | * Get the symbols that are present in the tracker. |
||
70 | * |
||
71 | * @return iterable|Name[][] |
||
72 | */ |
||
73 | 6 | public function getSymbols(): iterable |
|
74 | { |
||
75 | 6 | return new \CallbackFilterIterator( |
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
76 | 6 | new \RecursiveIteratorIterator( |
|
77 | 6 | new \RecursiveArrayIterator($this->symbols, \RecursiveArrayIterator::CHILD_ARRAYS_ONLY) |
|
78 | ), |
||
79 | function ($each): bool { |
||
80 | 4 | return $each !== false; |
|
81 | 6 | } |
|
82 | ); |
||
83 | } |
||
84 | } |
||
85 |