1
|
|
|
<?php |
2
|
|
|
namespace Germania\PathPrefixer; |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* Adds a prefix to a given path string or array. |
6
|
|
|
* |
7
|
|
|
* Usage: |
8
|
|
|
* |
9
|
|
|
* <?php |
10
|
|
|
* use Germania\PathPrefixer\PathPrefixer; |
11
|
|
|
* |
12
|
|
|
* // Root will default to getcwd() |
13
|
|
|
* $prefixer = new PathPrefixer( '/path/to/root' ); |
14
|
|
|
* |
15
|
|
|
* echo $prefixer('templates'); |
16
|
|
|
* // Result: "/path/to/root/templates" |
17
|
|
|
* |
18
|
|
|
* |
19
|
|
|
* // Try on array: |
20
|
|
|
* $result = $prefixer([ |
21
|
|
|
* 'foo' => 'includes', |
22
|
|
|
* 'bar' => 'templates' |
23
|
|
|
* ]); |
24
|
|
|
* // Result: |
25
|
|
|
* // 'foo' => '/path/to/root/includes', |
26
|
|
|
* // 'bar' => '/path/to/root/templates' |
27
|
|
|
* |
28
|
|
|
*/ |
29
|
|
|
class PathPrefixer |
30
|
|
|
{ |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @var string |
34
|
|
|
*/ |
35
|
|
|
public $root_path; |
36
|
|
|
|
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @var string |
40
|
|
|
*/ |
41
|
|
|
public $separator; |
42
|
|
|
|
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param string $root_path Path to root directory; default: null (or getcwd(), respectively) |
46
|
|
|
* @param string $separator String separator for prefix and path. |
47
|
|
|
* When not set, DIRECTORY_SEPARATOR will be used. |
48
|
|
|
*/ |
49
|
65 |
|
public function __construct( $root_path = null, $separator = \DIRECTORY_SEPARATOR) |
50
|
|
|
{ |
51
|
65 |
|
$this->root_path = $root_path ?: getcwd(); |
52
|
65 |
|
$this->separator = $separator; |
53
|
65 |
|
} |
54
|
|
|
|
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Prepends a path prefix to the path given. |
58
|
|
|
* |
59
|
|
|
* @param mixed $path Path string ar array |
60
|
|
|
* @return mixed Path string ar array with root path prepended |
61
|
|
|
*/ |
62
|
65 |
|
public function __invoke( $path ) |
63
|
|
|
{ |
64
|
65 |
|
if (is_string( $path )): |
65
|
60 |
|
$result = join( $this->separator, [ $this->root_path, $path ] ); |
66
|
|
|
|
67
|
49 |
|
elseif (is_array($path)): |
68
|
20 |
|
$result = array_map($this, $path); |
69
|
|
|
|
70
|
29 |
|
elseif (is_object($path)): |
71
|
|
|
|
72
|
20 |
|
$result = new \StdClass; |
73
|
20 |
|
foreach($path as $key => $p): |
74
|
20 |
|
$result->{$key} = $this->__invoke($p); |
75
|
4 |
|
endforeach; |
76
|
|
|
|
77
|
4 |
|
else: |
78
|
5 |
|
throw new \InvalidArgumentException("String or String array expected."); |
79
|
|
|
endif; |
80
|
|
|
|
81
|
60 |
|
return $result; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|