Completed
Pull Request — master (#12)
by Ben
07:48
created

PathBuilder::resolve()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 1
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
     * @param string        $path      [description]
25
     * @param Psr4Namespace $namespace [description]
26
     */
27
    public function __construct(string $path, Psr4Namespace $namespace)
28
    {
29
        if (!is_dir($path)) {
30
            throw new Exception('Invalid path');
31
        }
32
        $this->namespace = $namespace;
33
        $this->path = $path;
34
    }
35
36
    /**
37
     * Get the absolute directory of the provided namespace, relative to the initial
38
     * path/namespace
39
     * 
40
     * @param Psr4Namespace $namespace The namespace you want the directory for
41
     * @return string the absolute directory path, empty if it does not exist!
42
     */
43
    public function resolve(Psr4Namespace $namespace): string
44
    {
45
        if (!$namespace->startsWith($this->namespace)) {
46
            throw new Exception($namespace->getValue() . ' is not from the same base as ' . $this->namespace->getValue());
47
        }
48
        $relFqn = substr($namespace->getValue(), strlen($this->namespace->getValue()));
49
        $relPath = $this->nsToPath($relFqn);
50
51
        $absPath = realpath($this->path . DIRECTORY_SEPARATOR . $relPath);
52
53
        return $absPath ?: '';
54
    }
55
56
    /**
57
     * Convert a namespace to a path equivilent.
58
     * 
59
     * @param string $namespace
60
     * @return string
61
     */
62
    private function nsToPath(string $namespace): string
63
    {
64
        return trim(strtr($namespace, [
65
            '\\' => DIRECTORY_SEPARATOR,
66
            '//' => DIRECTORY_SEPARATOR
67
        ]), '\\/');
68
    }
69
}
70