Completed
Push — master ( 1ba1ea...0e3150 )
by Auke
03:41
created

path::getSplitPath()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 4
Bugs 1 Features 1
Metric Value
c 4
b 1
f 1
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
cc 2
eloc 3
nc 1
nop 1
crap 2
1
<?php
2
3
/*
4
 * This file is part of the Ariadne Component Library.
5
 *
6
 * (c) Muze <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace arc;
13
14
/**
15
 *	Utility methods to handle common path related tasks, cleaning, changing relative to absolute, etc.
16
 */
17
class path
18
{
19
    protected static $collapseCache = array();
20
21
    /**
22
     *	This method returns all the parent paths for a given path, starting at the root and including the
23
     *	given path itself.
24
     *
25
     *	Usage:
26
     *		\arc\path::parents( '/foo/bar/doh/', '/foo/' ); // => [ '/foo/', '/foo/bar/', '/foo/bar/doh/' ]
27
     *
28
     *	@param string $path The path to derive all parent paths from.
29
     *	@param string $root The root or topmost parent to return. Defaults to '/'.
30
     *	@return array Array of all parent paths, starting at the root and ending with the given path.
31
     *		Note: It includes the given path!
32
     */
33 10
    public static function parents($path, $root = '/')
34
    {
35
        // returns all parents starting at the root, up to and including the path itself
36 10
        $prevpath = '/';
37
        $parents = self::reduce( $path, function ($result, $entry) use ($root, &$prevpath) {
38 10
            $prevpath .= $entry . '/';
39 10
            if (strpos( $prevpath, $root ) === 0 && $prevpath !== $root) {
40
                // Add only parents below the root
41 10
                $result[] = $prevpath;
42 5
            }
43
44 10
            return $result;
45 10
        }, array( $root ) );
46
47 10
        return $parents;
48
    }
49
50
    /**
51
     *	This method parses a path which may contain '..' or '.' or '//' entries and returns the resulting
52
     *	absolute path.
53
     *
54
     *	Usage:
55
     *		\arc\path::collapse( '../', '/foo/bar/' ); // => '/foo/'
56
     *		\arc\path::collapse( '\\foo\\.\\bar/doh/../' ); // => '/foo/bar/'
57
     *
58
     *	@param string $path The input path, which may be relative. If this path starts with a '/' it is
59
     *		considered to start in the root.
60
     *	@param string $cwd The current working directory. For relative paths this is the starting point.
61
     *	@return string The absolute path, without '..', '.' or '//' entries.
62
     */
63 10
    public static function collapse($path, $cwd = '/')
64
    {
65
        // removes '.', changes '//' to '/', changes '\\' to '/', calculates '..' up to '/'
66 10
        if (!isset($path[0])) {
67 2
            return $cwd;
68
        }
69 10
        if ($path[0] !== '/' && $path[0] !== '\\') {
70 2
            $path = $cwd . '/' . $path;
71 1
        }
72 10
        if (isset( self::$collapseCache[$path] )) { // cache hit - so return that
73
74 6
            return self::$collapseCache[$path];
75
        }
76 10
        $tempPath = str_replace('\\', '/', (string) $path);
77 10
        $collapsedPath = self::reduce(
78 5
            $tempPath,
79
            function ($result, $entry) {
80
                switch ($entry) {
81 10
                    case '..':
82 2
                        $result = dirname( $result );
83 2
                        if (isset($result[1])) { // fast check to see if there is a dirname
84 2
                            $result .= '/';
85 1
                        }
86 2
                        $result[0] = '/'; // php has a bug in dirname('/') -> returns a '\\' in windows
87 2
                        break;
88 10
                    case '.':
89
                        break;
90 5
                    default:
91 10
                        $result .= $entry .'/';
92 10
                        break;
93 5
                }
94
95 10
                return $result;
96 10
            },
97 5
            '/' // initial value, always start paths with a '/'
98 5
        );
99
        // store the collapsed path in the cache, improves performance by factor > 10.
100 10
        self::$collapseCache[$path] = $collapsedPath;
101
102 10
        return $collapsedPath;
103
    }
104
105
    /**
106
     *	This method cleans the input path with the given filter method. You can specify any of the
107
     *	sanitize methods valid for filter_var or you can use your own callback function. By default
108
     *	it url encodes each filename in the path.
109
     *
110
     *	Usage:
111
     *		\arc\path::clean( '/a path/to somewhere/' ); // => '/a%20path/to%20somewhere/'
112
     *
113
     *	@param string $path The path to clean.
114
     *	@param mixed $filter Either one of the sanitize filters for filter_var or a callback method as
115
     *		in \arc\path::map
116
     *	@param mixed $flags Optional list of flags for the sanitize filter.
117
     *	@return string The cleaned path.
118
     */
119 2
    public static function clean($path, $filter = null, $flags = null)
120
    {
121 2
        if (is_callable( $filter )) {
122 2
            $callback = $filter;
123 1
        } else {
124 2
            if (!isset( $filter )) {
125 2
                 $filter = FILTER_SANITIZE_ENCODED;
126 1
            }
127 2
            if (!isset($flags)) {
128 2
                $flags = FILTER_FLAG_ENCODE_LOW | FILTER_FLAG_ENCODE_HIGH;
129 1
            }
130
            $callback = function ($entry) use ($filter, $flags) {
131 2
                return filter_var( $entry, $filter, $flags);
132 2
            };
133
        }
134
135 2
        return self::map( $path, $callback );
136
    }
137
138
    /**
139
     *	Returns either the immediate parent path for the given path, or null if it is outside the
140
     *	root path. Differs with dirname() in that it will not return '/' as a parent of '/', but
141
     *	null instead.
142
         *
143
     *	Usage:
144
     *		\arc\path::parent( '/foo/bar/' ); // => '/foo/'
145
     *
146
     *	@param string $path The path from which to get the parent path.
147
     *	@param string $root Optional root path, defaults to '/'
148
     *	@return string|null The parent of the given path or null if the parent is outside the root path.
149
     */
150 4
    public static function parent($path, $root = '/')
151
    {
152 4
        if ($path == $root) {
153 2
            return null;
154
        }
155 4
        $parent = dirname( $path );
156 4
        if (isset($parent[1])) { // fast check to see if there is a dirname
157 4
            $parent .= '/';
158 2
        }
159 4
        $parent[0] = '/'; // dirname('/something/') returns '\' in windows.
160 4
        if (strpos( $parent, $root ) !== 0) { // parent is outside of the root
161
162 2
            return null;
163
        }
164
165 4
        return $parent;
166
    }
167
168
169
    /**
170
     *  Returns the root entry of the given path.
171
     *
172
     *  Usage:
173
     *    $rootEntry = \arc\path::head( '/root/of/a/path/' ); // => 'root'
174
     *
175
     *  @param string $path The path to get the root entry of.
176
     *  @return string The root entry of the given path, without slashes.
177
     */
178
    public static function head($path)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
179
    {
180
        if (!\arc\path::isAbsolute($path)) {
181
            $path = '/' . $path;
182
        }
183
184
        return substr( $path, 1, strpos( $path, '/', 1) - 1 );
185
    }
186
187
    /**
188
     *  Returns the path without its root entry.
189
     *
190
     *  Usage:
191
     *    $remainder = \arc\path::tail( '/root/of/a/path/' ); // => '/of/a/path/'
192
     *
193
     *  @param string $path The path to get the tail of.
194
     *  @return string The path without its root entry.
195
     */
196
    public static function tail($path)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
197
    {
198
        if (!\arc\path::isAbsolute($path)) {
199
            $path = '/' . $path;
200
        }
201
202
        return substr( $path, strpos( $path, '/', 1) );
203
    }
204
205
    /**
206
     *  Returns the difference between sourcePath and targetPath as a relative path in
207
     *  such a way that if you append the relative path to the source path and collapse
208
     *  that, the result is the targetPath.
209
     *  @param string $targetPath The target path to map to.
210
     *  @param string $sourcePath The source path to start with.
211
     *  @return string The relative path from source to target.
212
     */
213 6
    public static function diff($sourcePath, $targetPath)
214
    {
215 6
        $diff = '';
216 6
        $targetPath = \arc\path::collapse( $targetPath );
217 6
        $sourcePath = \arc\path::collapse( $sourcePath );
218
        $commonParent = \arc\path::search( $sourcePath, function ($path) use ($targetPath, &$diff) {
219 6
            if (!\arc\path::isChild( $targetPath, $path )) {
220 6
                $diff .= '../';
221 3
            } else {
222 6
                return $path;
223
            }
224 6
        }, false);
225 6
        $diff .= substr( $targetPath, strlen( $commonParent ) );
226
227 6
        return $diff;
228
    }
229
230
    /**
231
     *  Returns true if the path is a child or descendant of the parent.
232
     *  @param string $path The path to check
233
     *  @param string $parent The parent to check.
234
     *  @return bool True if path is a child or descendant of parent
235
     */
236 8
    public static function isChild($path, $parent)
237
    {
238 8
        return ( strpos( $path, $parent ) === 0 );
239
    }
240
241
    /**
242
     *  Returns true if the given path starts with a '/'.
243
     * @param  string $path The path to check
244
     * @return bool   True is the path starts with a '/'
245
     */
246 8
    public static function isAbsolute($path)
247
    {
248 8
        return $path[0] === '/';
249
    }
250
251
    protected static function getSplitPath($path)
252
    {
253 30
        return array_filter( explode( '/', $path ), function ($entry) {
254 30
            return ( isset( $entry ) && $entry !== '' );
255 30
        });
256
    }
257
258
    /**
259
     *	Applies a callback function to each filename in a path. The result will be the new filename.
260
     *
261
     *	Usage:
262
     *		/arc/path::map( '/foo>bar/', function ($filename) {
263
     *			return htmlentities( $filename, ENT_QUOTES );
264
     *		} ); // => '/foo&gt;bar/'
265
     *
266
     *	@param string $path The path to alter.
267
     *	@param Callable $callback
268
     *	@return string A path with all filenames changed as by the callback method.
269
     */
270 4
    public static function map($path, $callback)
271
    {
272 4
        $splitPath = self::getSplitPath( $path );
273 4
        if (count($splitPath)) {
274 4
            $result = array_map( $callback, $splitPath );
275
276 4
            return '/' . join( $result, '/' ) .'/';
277
        } else {
278 2
            return '/';
279
        }
280
    }
281
282
    /**
283
     *	Applies a callback function to each filename in a path, but the result of the callback is fed back
284
     *	to the next call to the callback method as the first argument.
285
     *
286
     *	Usage:
287
     *		/arc/path::reduce( '/foo/bar/', function ($previousResult, $filename) {
288
     *			return $previousResult . $filename . '\\';
289
     *		}, '\\' ); // => '\\foo\\bar\\'
290
     *
291
     *	@param string $path The path to reduce.
292
     *	@param Callable $callback The method to apply to each filename of the path
293
     *	@param mixed $initial Optional. The initial reduced value to start the callback with.
294
     *	@return mixed The final result of the callback method
295
     */
296 28
    public static function reduce($path, $callback, $initial = null)
297
    {
298 28
        return array_reduce( self::getSplitPath( $path ), $callback, $initial );
299
    }
300
301
    /**
302
     *	Applies a callback function to each parent of a path, in order. Starting at the root by default,
303
     *	but optionally in reverse order. Will continue while the callback method returns null, otherwise
304
     *	returns the result of the callback method.
305
     *
306
     *	Usage:
307
     *		$result = \arc\path::search( '/foo/bar/', function ($parent) {
308
     *			if ($parent == '/foo/') { // silly test
309
     *				return true;
310
     *			}
311
     *		});
312
     *
313
     *	@param string $path Each parent of this path will be passed to the callback method.
314
     *	@param Callable $callback The method to apply to each parent
315
     *	@param bool $startAtRoot Optional. If set to false, root will be called last, otherwise first.
316
     *		Defaults to true.
317
     *	@param string $root Optional. Specify another root, no parents above the root will be called.
318
     *		Defaults to '/'.
319
     *	@return mixed The first non-null result of the callback method
320
     */
321 8
    public static function search($path, $callback, $startAtRoot = true, $root = '/')
322
    {
323 8
        $parents = self::parents( $path, $root );
324 8
        if (!$startAtRoot) {
325 8
            $parents = array_reverse( $parents );
326 4
        }
327 8
        foreach ($parents as $parent) {
328 8
            $result = call_user_func( $callback, $parent );
329 8
            if (isset( $result )) {
330 8
                return $result;
331
            }
332 4
        }
333
    }
334
}
335