Completed
Push — master ( 4deee6...b383ba )
by Zach
05:43 queued 03:44
created

NamespaceResolver::resolve()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 16
rs 9.2
1
<?php
2
3
namespace Yarak\Helpers;
4
5
use Yarak\Config\Config;
6
7
class NamespaceResolver
8
{
9
    /**
10
     * Resolve namespace for the given root path, add additional values.
11
     *
12
     * @param string $root
13
     * @param string $additional
14
     *
15
     * @return string|null
16
     */
17
    public static function resolve($root, $additional = '')
18
    {
19
        $config = Config::getInstance();
20
21
        if ($config->has(['namespaces', $root])) {
22
            $namespace = $config->get(['namespaces', $root]);
23
        } else {
24
            $namespace = self::guessNamespace($root);
25
        }
26
27
        if ($namespace !== null && $additional) {
28
            return Str::append($namespace, '\\').ucfirst($additional);
29
        }
30
31
        return $namespace;
32
    }
33
34
    /**
35
     * Guess the namespace for the given root path.
36
     *
37
     * @param string $root
38
     *
39
     * @return string|null
40
     */
41
    public static function guessNamespace($root)
42
    {
43
        if (!defined('APP_PATH')) {
44
            return;
45
        }
46
47
        $method = 'get'.ucfirst($root).'Directory';
48
49
        $path = Config::getInstance()->$method();
50
51
        $appPathArray = explode('/', APP_PATH);
52
53
        $relativePath = array_diff(explode('/', $path), $appPathArray);
54
55
        array_unshift($relativePath, array_pop($appPathArray));
56
57
        return implode('\\', array_map('ucfirst', $relativePath));
58
    }
59
}
60