Completed
Pull Request — master (#12)
by Ben
08:31
created

PathBuilder::resolve()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
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(
47
                $namespace->getValue() . ' is not from the same base as ' .
48
                $this->namespace->getValue()
49
            );
50
        }
51
        $relFqn = substr($namespace->getValue(), strlen($this->namespace->getValue()));
52
        $relPath = $this->nsToPath($relFqn);
53
54
        $absPath = realpath($this->path . DIRECTORY_SEPARATOR . $relPath);
55
56
        return $absPath ?: '';
57
    }
58
59
    /**
60
     * Convert a namespace to a path equivilent.
61
     *
62
     * @param string $namespace
63
     * @return string
64
     */
65
    private function nsToPath(string $namespace): string
66
    {
67
        return trim(strtr($namespace, [
68
            '\\' => DIRECTORY_SEPARATOR,
69
            '//' => DIRECTORY_SEPARATOR
70
        ]), '\\/');
71
    }
72
}
73