Completed
Push — master ( 8a1c86...8ae873 )
by Sebastian
03:50
created

ComponentFinder::resolveNamespaceFromAlias()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
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