Lines 100.00% 41 / 41
Functions and Methods 100.00% 9 / 9
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
AppScaffold 100.00% 41 / 41 100.00% 9 / 9 13 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 scaffoldApp 100.00% 25 / 25 100.00% 1 / 1 2
 deriveAppId 100.00% 1 / 1 100.00% 1 / 1 1
 findAppsRoot 100.00% 3 / 3 100.00% 1 / 1 2
 findTestsDirectory 100.00% 1 / 1 100.00% 1 / 1 1
 refuseExistingFile 100.00% 2 / 2 100.00% 1 / 1 2
 refuseTakenId 100.00% 3 / 3 100.00% 1 / 1 2
 listTakenIds 100.00% 4 / 4 100.00% 1 / 1 1
 renderStub 100.00% 1 / 1 100.00% 1 / 1 1
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Console\Scaffold;
6
7use Stewart\Contracts\App\AppId;
8use Stewart\Contracts\App\Collection\AppIdCollection;
9use Stewart\Contracts\Exception\IdentifierException;
10use Stewart\Runtime\App\AppDiscovery;
11use Stewart\Runtime\Config\AppOverride;
12use Stewart\Runtime\Config\AutoloadRoot;
13use Stewart\Runtime\Config\ConfigLoader;
14use Stewart\Runtime\Config\ProjectRoot;
15use Stewart\Runtime\Config\Psr4Map;
16use Stewart\Runtime\Exception\AppError;
17use Stewart\Runtime\Exception\AppException;
18use Stewart\Runtime\Exception\ConfigurationException;
19use Stewart\Runtime\Exception\ScaffoldError;
20use Stewart\Runtime\Exception\ScaffoldException;
21use Symfony\Component\Filesystem\Filesystem;
22use Symfony\Component\Filesystem\Path;
23
24final readonly class AppScaffold
25{
26    private const string STUB_DIRECTORY = __DIR__ . '/../../../resources/scaffold';
27
28    private const string CLASS_NAME_PATTERN = '/\A[A-Z][A-Za-z0-9]*\z/';
29
30    private const string CAMEL_CASE_WORD_BOUNDARY = '/(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/';
31
32    private const string TESTS_NAMESPACE = 'Tests\\';
33
34    private const string TESTS_DIRECTORY = 'tests';
35
36    public function __construct(
37        private Psr4Map $psr4Map,
38        private ProjectRoot $projectRoot,
39        private AppDiscovery $discovery,
40        private ConfigLoader $configs,
41        private Filesystem $filesystem,
42        private string $appsDirectory,
43    ) {}
44
45    /** @throws AppException|ConfigurationException|IdentifierException|ScaffoldException */
46    public function scaffoldApp(string $className, ?string $appId = null, AppScaffoldKind $kind = AppScaffoldKind::Automation): ScaffoldedApp
47    {
48        if (preg_match(self::CLASS_NAME_PATTERN, $className) !== 1) {
49            throw ScaffoldException::createForReason(ScaffoldError::ClassNameInvalid, name: $className);
50        }
51
52        $id = new AppId($appId ?? $this->deriveAppId($className));
53        $appsRoot = $this->findAppsRoot();
54        $testsNamespace = $appsRoot->namespacePrefix . self::TESTS_NAMESPACE;
55        $appFile = Path::join($appsRoot->directory, $className . '.php');
56        $testFile = Path::join($this->findTestsDirectory($testsNamespace), $className . 'Test.php');
57
58        $this->refuseExistingFile($appFile);
59        $this->refuseExistingFile($testFile);
60        $this->refuseTakenId($id);
61
62        $placeholders = [
63            '{{namespace}}' => rtrim($appsRoot->namespacePrefix, '\\'),
64            '{{testNamespace}}' => rtrim($testsNamespace, '\\'),
65            '{{class}}' => $className,
66            '{{id}}' => $id->value,
67        ];
68        $this->filesystem->dumpFile($appFile, $this->renderStub($kind->getAppStub(), $placeholders));
69        $this->filesystem->dumpFile($testFile, $this->renderStub($kind->getTestStub(), $placeholders));
70
71        return new ScaffoldedApp(
72            $id,
73            $appsRoot->namespacePrefix . $className,
74            $kind,
75            Path::makeRelative($appFile, $this->projectRoot->path),
76            Path::makeRelative($testFile, $this->projectRoot->path),
77        );
78    }
79
80    private function deriveAppId(string $className): string
81    {
82        return strtolower(preg_replace(self::CAMEL_CASE_WORD_BOUNDARY, '-', $className) ?? $className);
83    }
84
85    /** @throws AppException */
86    private function findAppsRoot(): AutoloadRoot
87    {
88        $directory = realpath($this->appsDirectory);
89
90        return ($directory === false ? null : $this->psr4Map->findAutoloadRootContaining($directory))
91            ?? throw AppException::createForReason(AppError::DirectoryNotAutoloadable, directory: $this->appsDirectory);
92    }
93
94    private function findTestsDirectory(string $testsNamespace): string
95    {
96        return $this->psr4Map->listDirectoriesFor($testsNamespace)[0] ?? $this->projectRoot->resolvePath(self::TESTS_DIRECTORY);
97    }
98
99    /** @throws ScaffoldException */
100    private function refuseExistingFile(string $file): void
101    {
102        if ($this->filesystem->exists($file)) {
103            throw ScaffoldException::createForReason(ScaffoldError::FileExists, path: Path::makeRelative($file, $this->projectRoot->path));
104        }
105    }
106
107    /** @throws AppException|ConfigurationException|ScaffoldException */
108    private function refuseTakenId(AppId $id): void
109    {
110        $taken = $this->listTakenIds()->findFirstWhere(static fn(AppId $known): bool => $known->collidesWith($id));
111
112        if ($taken !== null) {
113            throw ScaffoldException::createForReason(ScaffoldError::IdTaken, appId: $taken->value);
114        }
115    }
116
117    /** @throws AppException|ConfigurationException */
118    private function listTakenIds(): AppIdCollection
119    {
120        $configured = $this->configs->loadConfig(null)->apps
121            ->filter(static fn(AppOverride $override): bool => $override->class !== null)
122            ->mapToList(static fn(AppOverride $override): AppId => $override->id);
123
124        return AppIdCollection::fromList([...$this->discovery->discover()->apps->listAppIds()->listValues(), ...$configured]);
125    }
126
127    /** @param array<string, string> $placeholders */
128    private function renderStub(string $stub, array $placeholders): string
129    {
130        return strtr($this->filesystem->readFile(Path::join(self::STUB_DIRECTORY, $stub)), $placeholders);
131    }
132}