Passed
Push — add-command-list-modules ( fd1ae6...c98401 )
by Chema
02:58
created

AllAppModulesFinder::getNamespace()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 1
rs 10
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->facadeClass()] = $appModule;
31
            }
32
        }
33 2
        uksort($result, static fn ($a, $b) => $a <=> $b);
34
35 2
        return array_values($result);
36
    }
37
38 2
    private function createAppModule(SplFileInfo $fileInfo): ?AppModule
39
    {
40 2
        if (!$fileInfo->isFile()
41 2
            || $fileInfo->getExtension() !== 'php'
42 2
            || str_contains($fileInfo->getRealPath(), 'vendor/')
43
        ) {
44 1
            return null;
45
        }
46 2
        $namespace = $this->getNamespace($fileInfo);
47 2
        $className = $this->buildClassName($fileInfo);
48
49 2
        $fullyQualifiedClassName = sprintf(
50 2
            '%s\\%s',
51 2
            $namespace,
52 2
            $className,
53 2
        );
54
55 2
        if (!class_exists($fullyQualifiedClassName)) {
56
            return null;
57
        }
58
59 2
        return AppModule::fromClass($fullyQualifiedClassName);
60
    }
61
62 2
    private function getNamespace(SplFileInfo $fileInfo): string
63
    {
64 2
        $fileContent = (string)file_get_contents($fileInfo->getRealPath());
65
66 2
        preg_match('#namespace (.*);#', $fileContent, $matches);
67
68 2
        return $matches[1] ?? '';
69
    }
70
71 2
    private function buildClassName(SplFileInfo $fileInfo): string
72
    {
73 2
        $pieces = explode(DIRECTORY_SEPARATOR, $fileInfo->getFilename());
74 2
        $filename = end($pieces);
75
76 2
        return substr($filename, 0, strpos($filename, '.') ?: 1);
77
    }
78
79 2
    private function isFacade(AppModule $appModule): bool
80
    {
81 2
        $rc = new ReflectionClass($appModule->facadeClass());
82 2
        $parentClass = $rc->getParentClass();
83
84 2
        return $parentClass
85 2
            && $parentClass->name === AbstractFacade::class;
86
    }
87
}
88