1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Psi\Bundle\ObjectRender\Template; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Determine a file path from a given class reflection class. |
9
|
|
|
* |
10
|
|
|
* An *ordered* map of namespaces => paths must be provided. It should be |
11
|
|
|
* ordered by namespace length (longest to shortest). |
12
|
|
|
*/ |
13
|
|
|
class Locator |
14
|
|
|
{ |
15
|
|
|
private $extension; |
16
|
|
|
private $map; |
17
|
|
|
|
18
|
|
|
public function __construct(array $map, string $extension) |
19
|
|
|
{ |
20
|
|
|
$this->extension = $extension; |
21
|
|
|
$this->map = $map; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function locate(\ReflectionClass $class, string $variant = null): string |
25
|
|
|
{ |
26
|
|
|
list($resolvedNs, $basePath) = $this->resolvePath($class->getName()); |
|
|
|
|
27
|
|
|
|
28
|
|
|
$fname = str_replace('\\', '.', substr($class->getName(), strlen($resolvedNs))); |
|
|
|
|
29
|
|
|
if (0 === strpos($fname, '.')) { |
30
|
|
|
$fname = substr($fname, 1); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
$fpath = $this->getTemplatePath($basePath, $fname, $variant); |
34
|
|
|
|
35
|
|
|
return $fpath; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
private function getTemplatePath(string $basePath, string $fname, string $variant = null) |
39
|
|
|
{ |
40
|
|
|
$extension = ($this->extension ? $this->extension : ''); |
41
|
|
|
|
42
|
|
|
if (null === $variant) { |
43
|
|
|
return sprintf( |
44
|
|
|
'%s/%s.%s', |
45
|
|
|
$basePath, |
46
|
|
|
$fname, |
47
|
|
|
$extension |
48
|
|
|
); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return sprintf( |
52
|
|
|
'%s/%s/%s.%s', |
53
|
|
|
$basePath, |
54
|
|
|
$fname, |
55
|
|
|
$variant, |
56
|
|
|
$extension |
57
|
|
|
); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
private function resolvePath($classFqn): array |
61
|
|
|
{ |
62
|
|
|
foreach ($this->map as $namespace => $path) { |
63
|
|
|
if ($namespace === $classFqn) { |
64
|
|
|
continue; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
if (0 === strpos($classFqn, $namespace)) { |
68
|
|
|
return [$namespace, $path]; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
throw new \InvalidArgumentException(sprintf( |
73
|
|
|
'Could not resolve path for class "%s" in namespaces: "%s"', |
74
|
|
|
$classFqn, implode('", "', array_keys($this->map)) |
75
|
|
|
)); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|