Passed
Push — master ( c83cff...0054a6 )
by 世昌
02:30
created

Resource::getResource()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
namespace suda\application;
3
4
use function in_array;
5
use function is_array;
6
use suda\framework\loader\Path;
7
use suda\framework\config\PathResolver;
8
use suda\framework\filesystem\FileSystem;
9
10
/**
11
 * 资源管理器
12
 */
13
class Resource
14
{
15
    /**
16
     * 资源路径
17
     *
18
     * @var array
19
     */
20
    protected $resource;
21
22
    /**
23
     * 资源路径
24
     *
25
     * @param array|string $resource
26
     */
27
    public function __construct($resource = [])
28
    {
29
        $this->resource = is_array($resource)?$resource:[$resource];
30
    }
31
32
    /**
33
     * 获取相对的路径
34
     *
35
     * @param string $source
36
     * @param string $relative
37
     * @return string
38
     */
39
    public static function getPathByRelativePath(string $source, string $relative):string
40
    {
41
        $path = $source;
42
        if (Path::isRelativePath($source)) {
43
            $path = $relative.'/'.$path;
44
        }
45
        return Path::toAbsolutePath($path);
46
    }
47
48
    /**
49
     * 添加资源目录
50
     *
51
     * @param string $path
52
     * @return void
53
     */
54
    public function addResourcePath(string $path)
55
    {
56
        $path = Path::toAbsolutePath($path);
57
        if (!in_array($path, $this->resource)) {
58
            array_unshift($this->resource, $path);
59
        }
60
    }
61
62
    /**
63
     * 获取资源文件路径
64
     *
65
     * @param string $path
66
     * @param string $limitPath 父级溢出
67
     * @return string|null
68
     */
69
    public function getResourcePath(string $path, string $limitPath = null):?string
70
    {
71
        foreach ($this->resource as $root) {
72
            $target = $root.'/'.$path;
73
            $templateLimitPath = $limitPath ? $root.'/'.$limitPath : $root;
74
            if (FileSystem::exist($target) && FileSystem::isOverflowPath($templateLimitPath, $target) === false) {
75
                return $target;
76
            }
77
        }
78
        return null;
79
    }
80
81
    /**
82
     * 获取配置资源文件路径
83
     *
84
     * @param string $path
85
     * @return string|null
86
     */
87
    public function getConfigResourcePath(string $path):?string
88
    {
89
        foreach ($this->resource as $root) {
90
            if ($target = PathResolver::resolve($root.'/'.$path)) {
91
                return $target;
92
            }
93
        }
94
        return null;
95
    }
96
97
    /**
98
     * @return array
99
     */
100
    public function getResource(): array
101
    {
102
        return $this->resource;
103
    }
104
}
105