Skip to content

Commit 8afbce0

Browse files
committed
fix(discovery): support psr-4 namespaces with multiple paths
1 parent 45feded commit 8afbce0

1 file changed

Lines changed: 16 additions & 18 deletions

File tree

packages/discovery/src/Composer.php

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,10 @@ public function load(): self
3636
{
3737
$this->composerPath = Path\normalize($this->root, 'composer.json');
3838
$this->composer = $this->loadComposerFile($this->composerPath);
39-
$this->namespaces = arr($this->composer)
40-
->get('autoload.psr-4', default: arr())
41-
->map(fn (string $path, string $namespace) => new Psr4Namespace($namespace, $path))
42-
->sortByCallback(fn (Psr4Namespace $ns1, Psr4Namespace $ns2) => strlen($ns1->path) <=> strlen($ns2->path))
43-
->values()
44-
->toArray();
39+
$this->namespaces = $this->resolvePsr4Namespaces('autoload.psr-4');
4540

4641
foreach ($this->namespaces as $namespace) {
47-
if (! Str\starts_with(Str\ensure_ends_with($namespace->path, '/'), ['app/', 'src/', 'source/', 'lib/'])) {
42+
if (! Str\starts_with(Str\ensure_ends_with($namespace->path, '/'), needles: ['app/', 'src/', 'source/', 'lib/'])) {
4843
continue;
4944
}
5045

@@ -57,20 +52,12 @@ public function load(): self
5752
$this->mainNamespace = $this->namespaces[0];
5853
}
5954

60-
$this->namespaces = arr([
61-
$this->mainNamespace,
62-
...$this->namespaces,
63-
])
55+
$this->namespaces = new Arr\ImmutableArray([$this->mainNamespace, ...$this->namespaces])
6456
->filter()
65-
->unique(fn (Psr4Namespace $ns) => $ns->namespace)
57+
->unique(fn (Psr4Namespace $ns) => "{$ns->namespace}:{$ns->path}")
6658
->toArray();
6759

68-
$this->devNamespaces = arr($this->composer)
69-
->get('autoload-dev.psr-4', default: arr())
70-
->map(fn (string $path, string $namespace) => new Psr4Namespace($namespace, $path))
71-
->sortByCallback(fn (Psr4Namespace $ns1, Psr4Namespace $ns2) => strlen($ns1->path) <=> strlen($ns2->path))
72-
->values()
73-
->toArray();
60+
$this->devNamespaces = $this->resolvePsr4Namespaces('autoload-dev.psr-4');
7461

7562
return $this;
7663
}
@@ -131,4 +118,15 @@ private function loadComposerFile(string $path): array
131118

132119
return Filesystem\read_json($path);
133120
}
121+
122+
/** @return array<Psr4Namespace> */
123+
private function resolvePsr4Namespaces(string $path): array
124+
{
125+
return new Arr\ImmutableArray($this->composer)
126+
->get($path, default: new Arr\ImmutableArray())
127+
->flatMap(fn (string|iterable $paths, string $namespace) => Arr\map(Arr\wrap($paths), fn (string $path) => new Psr4Namespace($namespace, $path)))
128+
->sortByCallback(fn (Psr4Namespace $ns1, Psr4Namespace $ns2) => strlen($ns1->path) <=> strlen($ns2->path))
129+
->values()
130+
->toArray();
131+
}
134132
}

0 commit comments

Comments
 (0)