Completed
Push — master ( b4d615...44d46c )
by Zach
02:15
created

NamespaceResolver::guessNamespace()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 3
eloc 13
c 2
b 1
f 0
nc 3
nop 1
dl 0
loc 24
rs 8.9713
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 dir path.
36
     *
37
     * @param string $dir
38
     *
39
     * @return string|null
40
     */
41
    public static function guessNamespace($dir)
42
    {
43
        if (!defined('APP_PATH')) {
44
            return;
45
        }
46
47
        $config = Config::getInstance();
48
49
        $method = 'get'.ucfirst($dir).'Directory';
50
51
        $path = Config::getInstance()->$method();
52
53
        $appPathArray = explode('/', APP_PATH);
54
55
        $relativePath = array_diff(explode('/', $path), $appPathArray);
56
57
        if (($root = $config->get(['namespaces', 'root'])) !== null) {
58
            array_unshift($relativePath, $root);
59
        } else {
60
            array_unshift($relativePath, array_pop($appPathArray));
61
        }
62
63
        return implode('\\', array_map('ucfirst', $relativePath));
64
    }
65
}
66