-
Notifications
You must be signed in to change notification settings - Fork 8
/
Path.php
100 lines (96 loc) · 2.49 KB
/
Path.php
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
<?php
/*
* Copyright (c) Ouzo contributors, http://ouzoframework.org
* This file is made available under the MIT License (view the LICENSE file for more information).
*/
namespace Ouzo\Utilities;
/**
* Class Path
* @package Ouzo\Utilities
*/
class Path
{
/**
* Returns a path created by placing DIRECTORY_SEPARATOR between each argument
*
* Example:
* <code>
* $path = Path::join('/my', 'path', 'to/file.txt');
* </code>
* Result:
* <code>
* /my/path/to/file.txt
* </code>
*
* @param string ...
* @return mixed
*/
public static function join()
{
$args = Arrays::filterNotBlank(func_get_args());
return preg_replace('~[/\\\]+~', DIRECTORY_SEPARATOR, implode(DIRECTORY_SEPARATOR, $args));
}
/**
* Returns a path starting in the system temporary directory.
*
* Example:
* <code>
* $path = Path::joinWithTemp('my/file.txt');
* </code>
* Result:
* <code>
* //Unix
* /tmp/my/file.txt
* </code>
*
* @param string ...
* @return mixed
*/
public static function joinWithTemp()
{
$args = array_merge(array(sys_get_temp_dir()), func_get_args());
return call_user_func_array([Path::class, 'join'], $args);
}
/**
* Returns a normalized path.
* Actions:
* <ul>
* <li>removes dots from relative path</li>
* <li>removes dots from absolute path</li>
* <li>does not remove leading dots</li>
* <li>removes double slashes</li>
* </ul>
*
* Example:
* <code>
* $normalized = Path::normalize('dir/../dir2/file.txt');
* $normalized = Path::normalize('/tmp/../dir2/file.txt');
* $normalized = Path::normalize('../file.txt');
* $normalized = Path::normalize('//dir/file.txt');
* </code>
* Result:
* <code>
* dir2/file.txt
* /dir2/file.txt
* ../file.txt
* /dir/file.txt
* </code>
*
* @param string $path
* @return string
*/
public static function normalize($path)
{
$parts = explode('/', trim($path, '/'));
$result = array();
foreach ($parts as $part) {
if ($part == '..' && !empty($result)) {
array_pop($result);
} elseif ($part != '.' && !empty($part)) {
array_push($result, $part);
}
}
$root = $path[0] == '/' ? '/' : '';
return $root . implode('/', $result);
}
}