/
UsedViewInAnotherViewCollector.php
62 lines (49 loc) · 1.65 KB
/
UsedViewInAnotherViewCollector.php
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
<?php
namespace NunoMaduro\Larastan\Collectors;
use NunoMaduro\Larastan\Support\ViewFileHelper;
use PhpParser\Node;
use PHPStan\Parser\Parser;
use PHPStan\Parser\ParserErrorsException;
final class UsedViewInAnotherViewCollector
{
/** @see https://regex101.com/r/OyHHCY/1 */
private const VIEW_NAME_REGEX = '/@(extends|include(If|Unless|When|First)?)(\(.*?([\'"])(.*?)([\'"])([),]))/m';
public function __construct(private Parser $parser, private ViewFileHelper $viewFileHelper)
{
}
/** @return list<string> */
public function getUsedViews(): array
{
$usedViews = [];
foreach ($this->viewFileHelper->getAllViewFilePaths() as $viewFile) {
try {
$parserNodes = $this->parser->parseFile($viewFile);
$usedViews = array_merge($usedViews, $this->processNodes($parserNodes));
} catch (ParserErrorsException $e) {
continue;
}
}
return $usedViews;
}
/**
* @param Node\Stmt[] $nodes
* @return list<string>
*/
private function processNodes(array $nodes): array
{
$nodes = array_filter($nodes, function (Node $node) {
return $node instanceof Node\Stmt\InlineHTML;
});
if (count($nodes) === 0) {
return [];
}
$usedViews = [];
foreach ($nodes as $node) {
preg_match_all(self::VIEW_NAME_REGEX, $node->value, $matches, PREG_SET_ORDER, 0);
$usedViews = array_merge($usedViews, array_map(function ($match) {
return $match[5];
}, $matches));
}
return $usedViews;
}
}