PathBuilder::resolve()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Benrowe\Fqcn;
6
7
use Benrowe\Fqcn\Value\Psr4Namespace;
8
9
/**
10
 * PathBuilder
11
 *
12
 * Build a path based on a namespace and the directory it's mapped to
13
 *
14
 * @package Benrowe\Fqcn
15
 */
16
class PathBuilder
17
{
18
    private $namespace;
19
    private $path;
20
21
    /**
22
     * Constructor
23
     * Take in the path & the psr4 namespace it represents
24
     *
25
     * @param string        $path      absolute path
26
     * @param Psr4Namespace $namespace namespace that represents the provided
27
     * path
28
     */
29
    public function __construct(string $path, Psr4Namespace $namespace)
30
    {
31
        if (!is_dir($path)) {
32
            throw new Exception('Invalid path');
33
        }
34
        $this->namespace = $namespace;
35
        $this->path = $path;
36
    }
37
38
    /**
39
     * Get the absolute directory of the provided namespace, relative to the initial
40
     * path/namespace
41
     *
42
     * @param Psr4Namespace $namespace The namespace you want the directory for
43
     * @return string the absolute directory path, empty if it does not exist!
44
     */
45
    public function resolve(Psr4Namespace $namespace): string
46
    {
47
        if (!$namespace->startsWith($this->namespace)) {
48
            throw new Exception(
49
                $namespace->getValue() . ' is not from the same base as ' .
50
                $this->namespace->getValue()
51
            );
52
        }
53
        $relFqn = substr($namespace->getValue(), strlen($this->namespace->getValue()));
54
        $relPath = $this->nsToPath($relFqn);
55
56
        $absPath = realpath($this->path . DIRECTORY_SEPARATOR . $relPath);
57
58
        return $absPath ?: '';
59
    }
60
61
    /**
62
     * Convert a namespace to a path equivilent.
63
     *
64
     * @param string $namespace
65
     * @return string
66
     */
67
    private function nsToPath(string $namespace): string
68
    {
69
        return trim(strtr($namespace, [
70
            '\\' => DIRECTORY_SEPARATOR,
71
            '//' => DIRECTORY_SEPARATOR
72
        ]), '\\/');
73
    }
74
}
75