1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\ViewComponents; |
4
|
|
|
|
5
|
|
|
use InvalidArgumentException; |
6
|
|
|
|
7
|
|
|
final class ComponentFinder |
8
|
|
|
{ |
9
|
|
|
/** @var string */ |
10
|
|
|
private $rootNamespace; |
11
|
|
|
|
12
|
|
|
/** @var array */ |
13
|
|
|
private $namespaces; |
14
|
|
|
|
15
|
|
|
public function __construct(string $rootNamespace, array $namespaces) |
16
|
|
|
{ |
17
|
|
|
$this->rootNamespace = $rootNamespace; |
18
|
|
|
$this->namespaces = $namespaces; |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
public function find(string $identifier): string |
22
|
|
|
{ |
23
|
|
|
$identifier = $this->sanitizeIdentifier($identifier); |
24
|
|
|
|
25
|
|
|
return class_exists($identifier) |
26
|
|
|
? $identifier |
27
|
|
|
: $this->expandComponentClassPath($identifier); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
private function expandComponentClassPath(string $path): string |
31
|
|
|
{ |
32
|
|
|
if (str_contains($path, '::')) { |
33
|
|
|
list($namespaceAlias, $path) = explode('::', $path, 2); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
$namespace = isset($namespaceAlias) |
37
|
|
|
? $this->resolveNamespaceFromAlias($namespaceAlias) |
38
|
|
|
: $this->rootNamespace; |
39
|
|
|
|
40
|
|
|
return collect(explode('.', $path)) |
41
|
|
|
->map(function (string $part) { |
42
|
|
|
return ucfirst($part); |
43
|
|
|
}) |
44
|
|
|
->prepend($namespace) |
45
|
|
|
->implode('\\'); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
private function resolveNamespaceFromAlias(string $alias): string |
49
|
|
|
{ |
50
|
|
|
$namespace = $this->namespaces[$alias] ?? null; |
51
|
|
|
|
52
|
|
|
if (! $namespace) { |
53
|
|
|
throw new InvalidArgumentException("View component namespace [$alias] doesn't exist."); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return $namespace; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
private function sanitizeIdentifier(string $identifier): string |
60
|
|
|
{ |
61
|
|
|
$identifier = trim($identifier, '\'" '); |
62
|
|
|
|
63
|
|
|
return str_replace('::class', '', $identifier); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|