Completed
Push — master ( c960e1...9b6ac4 )
by Daniel
02:39
created

Locator::resolvePath()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 4
nop 1
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
        $resolved = null;
0 ignored issues
show
Unused Code introduced by
$resolved is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
46
        foreach ($this->map as $namespace => $path) {
47
            if ($namespace === $classFqn) {
48
                continue;
49
            }
50
51
            if (0 === strpos($classFqn, $namespace)) {
52
                return [$namespace, $path];
53
            }
54
        }
55
56
        throw new \InvalidArgumentException(sprintf(
57
            'Could not resolve path for class "%s" in namespaces: "%s"',
58
            $classFqn, implode('", "', array_keys($this->map))
59
        ));
60
    }
61
}
62