Completed
Pull Request — master (#1)
by Daniel
04:19 queued 02:20
created

Locator   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

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

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A locate() 0 13 2
A getTemplatePath() 0 21 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 $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