Lines 100.00% 9 / 9
Functions and Methods 100.00% 2 / 2
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
GeneratedNamespaceResolver 100.00% 9 / 9 100.00% 2 / 2 4 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 resolveNamespaceFor 100.00% 8 / 8 100.00% 1 / 1 3
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Config;
6
7use Stewart\Runtime\Exception\ConfigurationError;
8use Stewart\Runtime\Exception\ConfigurationException;
9
10final readonly class GeneratedNamespaceResolver
11{
12    // What a new project's composer.json maps; generate suggests it when nothing maps the directory yet.
13    private const string NAMESPACE_WITHOUT_MAPPING = 'Automations\\Generated';
14
15    public function __construct(
16        private Psr4Map $psr4Map,
17        private ProjectRoot $projectRoot,
18    ) {}
19
20    /** @throws ConfigurationException */
21    public function resolveNamespaceFor(ProjectDirectory $outputDir): ClassNamespace
22    {
23        $prefixes = $this->psr4Map->listPrefixesMappedTo($outputDir->resolveWithin($this->projectRoot->path));
24
25        if (\count($prefixes) > 1) {
26            throw ConfigurationException::createForReason(
27                ConfigurationError::GeneratedNamespaceAmbiguous,
28                namespaces: implode(', ', array_map(static fn(string $prefix): string => rtrim($prefix, '\\'), $prefixes)),
29                directory: $outputDir->value,
30            );
31        }
32
33        return new ClassNamespace(isset($prefixes[0]) ? rtrim($prefixes[0], '\\') : self::NAMESPACE_WITHOUT_MAPPING);
34    }
35}