Completed
Pull Request — master (#1)
by Daniel
02:11
created

Locator::getTemplatePath()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
cc 3
eloc 14
nc 4
nop 3
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());
0 ignored issues
show
Bug introduced by
Consider using $class->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
27
28
        $fname = str_replace('\\', '.', substr($class->getName(), strlen($resolvedNs)));
0 ignored issues
show
Bug introduced by
Consider using $class->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
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