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

NamespaceResolver   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 59
rs 10
wmc 7
lcom 0
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A resolve() 0 16 4
B guessNamespace() 0 24 3
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