forked from SugiPHP/Config
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileLocator.php
More file actions
132 lines (119 loc) · 2.13 KB
/
FileLocator.php
File metadata and controls
132 lines (119 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
<?php
/**
* @package SugiPHP
* @subpackage Config
* @author Plamen Popov <tzappa@gmail.com>
* @license http://opensource.org/licenses/mit-license.php (MIT License)
*/
namespace SugiPHP\Config;
/**
* File Locator searches for a file in registered search paths.
*/
class FileLocator implements LocatorInterface
{
/**
* Search for a file in one or more directories.
* @var array
*/
protected $paths;
/**
* File Locator creator.
*
* @param array|string $paths
*/
public function __construct($paths)
{
$this->addPath($paths);
}
/**
* @inheritdoc
*/
public function locate($resource)
{
// empty string
if (empty($resource)) {
return ;
}
if ($this->isFullPath($resource)) {
if (is_file($resource)) {
return $resource;
}
} else {
foreach ($this->paths as $path) {
$file = "{$path}{$resource}";
if (is_file($file)) {
return $file;
}
}
}
}
/**
* Adds a search paths.
*
* @param string|array $path or several paths
*/
public function addPath($path)
{
$paths = (array) $path;
foreach ($paths as $path) {
$this->paths[] = rtrim($path, "\\/") . DIRECTORY_SEPARATOR;
}
}
/**
* Remove last search path.
*/
public function popPath()
{
array_pop($this->paths);
}
/**
* Prepend one path to the beginning of the search paths.
*
* @param string $path
*/
public function prependPath($path)
{
array_unshift($this->paths, rtrim($path, "\\/") . DIRECTORY_SEPARATOR);
}
/**
* Alias of prepend() method
*/
public function unshiftPath($path)
{
return $this->prependPath($path);
}
/**
* Remove first path from the search paths.
*/
public function shiftPath()
{
array_shift($this->paths);
}
/**
* Returns all registered search paths.
*
* @return array
*/
public function getPaths()
{
return $this->paths;
}
/**
* Check if the file/path is given with absolute path.
*
* @param string $path
* @return bool
*/
protected function isFullPath($path)
{
// *nix style
if ($path[0] == "/") {
return true;
}
// windows style
if (preg_match("#[A-Z]:\\.+#U", $path)) {
return true;
}
return false;
}
}