Completed
Pull Request — master (#23)
by Auke
02:10
created

path   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 318
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 17
Bugs 6 Features 5
Metric Value
wmc 36
c 17
b 6
f 5
lcom 1
cbo 0
dl 0
loc 318
ccs 0
cts 109
cp 0
rs 8.8

13 Methods

Rating   Name   Duplication   Size   Complexity  
A head() 0 8 2
A tail() 0 8 2
A parents() 0 16 3
C collapse() 0 41 8
A clean() 0 18 4
A parent() 0 17 4
A diff() 0 16 2
A isChild() 0 4 1
A isAbsolute() 0 4 1
A getSplitPath() 0 6 2
A map() 0 11 2
A reduce() 0 4 1
A search() 0 13 4
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
    public static function parents($path, $root = '/')
34
    {
35
        // returns all parents starting at the root, up to and including the path itself
36
        $prevpath = '/';
37
        $parents = self::reduce( $path, function ($result, $entry) use ($root, &$prevpath) {
38
            $prevpath .= $entry . '/';
39
            if (strpos( $prevpath, $root ) === 0 && $prevpath !== $root) {
40
                // Add only parents below the root
41
                $result[] = $prevpath;
42
            }
43
44
            return $result;
45
        }, array( $root ) );
46
47
        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
    public static function collapse($path, $cwd = '/')
64
    {
65
        // removes '.', changes '//' to '/', changes '\\' to '/', calculates '..' up to '/'
66
        if (!isset($path[0])) {
67
            return $cwd;
68
        }
69
        if ($path[0] !== '/' && $path[0] !== '\\') {
70
            $path = $cwd . '/' . $path;
71
        }
72
        if (isset( self::$collapseCache[$path] )) { // cache hit - so return that
73
74
            return self::$collapseCache[$path];
75
        }
76
        $tempPath = str_replace('\\', '/', (string) $path);
77
        $collapsedPath = self::reduce(
78
            $tempPath,
79
            function ($result, $entry) {
80
                switch ($entry) {
81
                    case '..':
82
                        $result = dirname( $result );
83
                        if (isset($result[1])) { // fast check to see if there is a dirname
84
                            $result .= '/';
85
                        }
86
                        $result[0] = '/'; // php has a bug in dirname('/') -> returns a '\\' in windows
87
                        break;
88
                    case '.':
89
                        break;
90
                    default:
91
                        $result .= $entry .'/';
92
                        break;
93
                }
94
95
                return $result;
96
            },
97
            '/' // initial value, always start paths with a '/'
98
        );
99
        // store the collapsed path in the cache, improves performance by factor > 10.
100
        self::$collapseCache[$path] = $collapsedPath;
101
102
        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
    public static function clean($path, $filter = null, $flags = null)
120
    {
121
        if (is_callable( $filter )) {
122
            $callback = $filter;
123
        } else {
124
            if (!isset( $filter )) {
125
                 $filter = FILTER_SANITIZE_ENCODED;
126
            }
127
            if (!isset($flags)) {
128
                $flags = FILTER_FLAG_ENCODE_LOW | FILTER_FLAG_ENCODE_HIGH;
129
            }
130
            $callback = function ($entry) use ($filter, $flags) {
131
                return filter_var( $entry, $filter, $flags);
132
            };
133
        }
134
135
        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
    public static function parent($path, $root = '/')
151
    {
152
        if ($path == $root) {
153
            return null;
154
        }
155
        $parent = dirname( $path );
156
        if (isset($parent[1])) { // fast check to see if there is a dirname
157
            $parent .= '/';
158
        }
159
        $parent[0] = '/'; // dirname('/something/') returns '\' in windows.
160
        if (strpos( $parent, $root ) !== 0) { // parent is outside of the root
161
162
            return null;
163
        }
164
165
        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
    public static function diff($sourcePath, $targetPath)
214
    {
215
        $diff = '';
216
        $targetPath = \arc\path::collapse( $targetPath );
217
        $sourcePath = \arc\path::collapse( $sourcePath );
218
        $commonParent = \arc\path::search( $sourcePath, function ($path) use ($targetPath, &$diff) {
219
            if (!\arc\path::isChild( $targetPath, $path )) {
220
                $diff .= '../';
221
            } else {
222
                return $path;
223
            }
224
        }, false);
225
        $diff .= substr( $targetPath, strlen( $commonParent ) );
226
227
        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
    public static function isChild($path, $parent)
237
    {
238
        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
    public static function isAbsolute($path)
247
    {
248
        return $path[0] === '/';
249
    }
250
251
    protected static function getSplitPath($path)
252
    {
253
        return array_filter( explode( '/', $path ), function ($entry) {
254
            return ( isset( $entry ) && $entry !== '' );
255
        });
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
    public static function map($path, $callback)
271
    {
272
        $splitPath = self::getSplitPath( $path );
273
        if (count($splitPath)) {
274
            $result = array_map( $callback, $splitPath );
275
276
            return '/' . join( $result, '/' ) .'/';
277
        } else {
278
            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
    public static function reduce($path, $callback, $initial = null)
297
    {
298
        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
    public static function search($path, $callback, $startAtRoot = true, $root = '/')
322
    {
323
        $parents = self::parents( $path, $root );
324
        if (!$startAtRoot) {
325
            $parents = array_reverse( $parents );
326
        }
327
        foreach ($parents as $parent) {
328
            $result = call_user_func( $callback, $parent );
329
            if (isset( $result )) {
330
                return $result;
331
            }
332
        }
333
    }
334
}
335