1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Gacela\Console\Domain\AllAppModules; |
6
|
|
|
|
7
|
|
|
use Gacela\Framework\AbstractFacade; |
8
|
|
|
use OuterIterator; |
9
|
|
|
use ReflectionClass; |
10
|
|
|
use SplFileInfo; |
11
|
|
|
|
12
|
|
|
final class AllAppModulesFinder |
13
|
|
|
{ |
14
|
2 |
|
public function __construct( |
15
|
|
|
private OuterIterator $fileIterator, |
16
|
|
|
) { |
17
|
2 |
|
} |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @return list<AppModule> |
21
|
|
|
*/ |
22
|
2 |
|
public function findAllAppModules(): array |
23
|
|
|
{ |
24
|
2 |
|
$result = []; |
25
|
|
|
|
26
|
|
|
/** @var SplFileInfo $fileInfo */ |
27
|
2 |
|
foreach ($this->fileIterator as $fileInfo) { |
28
|
2 |
|
$appModule = $this->createAppModule($fileInfo); |
29
|
2 |
|
if ($appModule !== null && $this->isFacade($appModule)) { |
30
|
2 |
|
$result[] = $appModule; |
31
|
|
|
} |
32
|
|
|
} |
33
|
|
|
|
34
|
2 |
|
return $result; |
|
|
|
|
35
|
|
|
} |
36
|
|
|
|
37
|
2 |
|
private function isFacade(AppModule $appModule): bool |
38
|
|
|
{ |
39
|
2 |
|
$rc = new ReflectionClass($appModule->fullyQualifiedClassName()); |
40
|
2 |
|
$parentClass = $rc->getParentClass(); |
41
|
|
|
|
42
|
2 |
|
return $parentClass |
43
|
2 |
|
&& $parentClass->name === AbstractFacade::class; |
44
|
|
|
} |
45
|
|
|
|
46
|
2 |
|
private function buildClassName(SplFileInfo $fileInfo): string |
47
|
|
|
{ |
48
|
2 |
|
$pieces = explode(DIRECTORY_SEPARATOR, $fileInfo->getFilename()); |
49
|
2 |
|
$filename = end($pieces); |
50
|
|
|
|
51
|
2 |
|
return substr($filename, 0, strpos($filename, '.') ?: 1); |
52
|
|
|
} |
53
|
|
|
|
54
|
2 |
|
private function getNamespace(SplFileInfo $fileInfo): string |
55
|
|
|
{ |
56
|
2 |
|
$fileContent = (string)file_get_contents($fileInfo->getRealPath()); |
57
|
|
|
|
58
|
2 |
|
preg_match('#namespace (.*);#', $fileContent, $matches); |
59
|
|
|
|
60
|
2 |
|
return $matches[1] ?? ''; |
61
|
|
|
} |
62
|
|
|
|
63
|
2 |
|
private function createAppModule(SplFileInfo $fileInfo): ?AppModule |
64
|
|
|
{ |
65
|
2 |
|
if (!$fileInfo->isFile() |
66
|
2 |
|
|| $fileInfo->getExtension() !== 'php' |
67
|
2 |
|
|| str_contains($fileInfo->getRealPath(), 'vendor/') |
68
|
|
|
) { |
69
|
|
|
return null; |
70
|
|
|
} |
71
|
2 |
|
$namespace = $this->getNamespace($fileInfo); |
72
|
2 |
|
$className = $this->buildClassName($fileInfo); |
73
|
|
|
|
74
|
2 |
|
$fullyQualifiedClassName = sprintf( |
75
|
2 |
|
'%s\\%s', |
76
|
2 |
|
$namespace, |
77
|
2 |
|
$className, |
78
|
2 |
|
); |
79
|
|
|
|
80
|
2 |
|
if (!class_exists($fullyQualifiedClassName)) { |
81
|
|
|
return null; |
82
|
|
|
} |
83
|
|
|
|
84
|
2 |
|
return new AppModule($className, $namespace); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|