Locator   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 0
dl 0
loc 48
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A locate() 0 18 3
A resolvePath() 0 17 4
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
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 = sprintf(
34
            '%s/%s.%s',
35
            $basePath,
36
            $fname,
37
            ($this->extension ? $this->extension : '')
38
        );
39
40
        return $fpath;
41
    }
42
43
    private function resolvePath($classFqn): array
44
    {
45
        foreach ($this->map as $namespace => $path) {
46
            if ($namespace === $classFqn) {
47
                continue;
48
            }
49
50
            if (0 === strpos($classFqn, $namespace)) {
51
                return [$namespace, $path];
52
            }
53
        }
54
55
        throw new \InvalidArgumentException(sprintf(
56
            'Could not resolve path for class "%s" in namespaces: "%s"',
57
            $classFqn, implode('", "', array_keys($this->map))
58
        ));
59
    }
60
}
61