Lines 62.50% 15 / 24
Methods 60.00% 3 / 5
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 listDirectoriesFor 0.00% 0 / 1 0.00% 0 / 1 2
 findAutoloadRootContaining 0.00% 0 / 8 0.00% 0 / 1 72
 listPrefixesMappedTo 100.00% 7 / 7 100.00% 1 / 1 4
 normalizePath 100.00% 7 / 7 100.00% 1 / 1 5
7final readonly class Psr4Map
8{
9    /** @param array<string, array<int, string>> $directoriesByNamespace */
10    public function __construct(private array $directoriesByNamespace) {}
11
12    /** @return list<string> */
13    public function listDirectoriesFor(string $namespacePrefix): array
14    {
15        return array_values($this->directoriesByNamespace[$namespacePrefix] ?? []);
16    }
17
18    // The deepest mapped directory wins, as Composer resolves the most specific prefix.
19    public function findAutoloadRootContaining(string $directory): ?AutoloadRoot
20    {
21        $found = null;
22
23        foreach ($this->directoriesByNamespace as $namespacePrefix => $directories) {
24            foreach ($directories as $mapped) {
25                $candidate = realpath($mapped);
26
27                if ($candidate === false || ($candidate !== $directory && !str_starts_with($directory, $candidate . \DIRECTORY_SEPARATOR))) {
28                    continue;
29                }
30
31                if ($found === null || \strlen($candidate) > \strlen($found->directory)) {
32                    $found = new AutoloadRoot($namespacePrefix, $candidate);
33                }
34            }
35        }
36
37        return $found;
38    }
39
40    /** @return list<string> */
41    public function listPrefixesMappedTo(string $directory): array
42    {
43        $wanted = self::normalizePath($directory);
44        $prefixes = [];
45
46        foreach ($this->directoriesByNamespace as $namespacePrefix => $directories) {
47            foreach ($directories as $mapped) {
48                if (self::normalizePath($mapped) === $wanted) {
49                    $prefixes[] = $namespacePrefix;
50
51                    break;
52                }
53            }
54        }
55
56        return $prefixes;
57    }
58
59    // Composer's base directory contains `..`, and realpath fails before the first run.
60    private static function normalizePath(string $path): string
61    {
62        $segments = [];
63
64        foreach (explode('/', str_replace('\\', '/', $path)) as $segment) {
65            match ($segment) {
66                '', '.' => null,
67                '..' => array_pop($segments),
68                default => $segments[] = $segment,
69            };
70        }
71
72        return '/' . implode('/', $segments);
73    }
74}