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\Iterator\FileIteratorInterface; |
||
10 | use Mediact\DependencyGuard\Php\Filter\SymbolFilterInterface; |
||
11 | use PhpParser\Error; |
||
12 | use PhpParser\NodeTraverser; |
||
13 | use PhpParser\Parser; |
||
14 | use PhpParser\ParserFactory; |
||
15 | |||
16 | class SymbolExtractor implements SymbolExtractorInterface |
||
17 | { |
||
18 | /** @var Parser */ |
||
19 | private $parser; |
||
20 | |||
21 | /** |
||
22 | * Constructor. |
||
23 | * |
||
24 | * @param Parser|null $parser |
||
25 | */ |
||
26 | 1 | public function __construct(Parser $parser = null) |
|
27 | { |
||
28 | 1 | if ($parser === null) { |
|
29 | 1 | $factory = new ParserFactory(); |
|
30 | 1 | $parser = $factory->create(ParserFactory::PREFER_PHP7); |
|
31 | } |
||
32 | |||
33 | 1 | $this->parser = $parser; |
|
34 | 1 | } |
|
35 | |||
36 | /** |
||
37 | * Extract the PHP symbols from the given files. |
||
38 | * |
||
39 | * @param FileIteratorInterface $files |
||
40 | * @param SymbolFilterInterface $filter |
||
41 | * |
||
42 | * @return SymbolIteratorInterface |
||
43 | */ |
||
44 | 4 | public function extract( |
|
45 | FileIteratorInterface $files, |
||
46 | SymbolFilterInterface $filter |
||
47 | ): SymbolIteratorInterface { |
||
48 | 4 | $symbols = []; |
|
49 | |||
50 | 4 | foreach ($files as $file) { |
|
51 | 3 | $parser = clone $this->parser; |
|
52 | |||
53 | try { |
||
54 | 3 | $size = $file->getSize(); |
|
55 | 3 | $handle = $file->openFile('rb'); |
|
56 | 3 | $contents = $size > 0 ? $handle->fread($size) : ''; |
|
57 | |||
58 | 3 | if (empty($contents)) { |
|
59 | 1 | continue; |
|
60 | } |
||
61 | |||
62 | 2 | $statements = $parser->parse($contents); |
|
63 | 1 | } catch (Error $e) { |
|
64 | // Either not a file, file is not readable, not a PHP file or |
||
65 | // the broken file should be detected by other tooling entirely. |
||
66 | 1 | continue; |
|
67 | } |
||
68 | |||
69 | 1 | $tracker = new SymbolTracker($filter); |
|
70 | 1 | $traverser = new NodeTraverser(); |
|
71 | 1 | $traverser->addVisitor($tracker); |
|
72 | 1 | $traverser->traverse($statements); |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
73 | |||
74 | 1 | foreach ($tracker->getSymbols() as $node) { |
|
75 | 1 | $symbols[] = new Symbol($file, $node); |
|
76 | } |
||
77 | } |
||
78 | |||
79 | 4 | return new SymbolIterator(...$symbols); |
|
80 | } |
||
81 | } |
||
82 |