/
Path.php
90 lines (80 loc) · 2.02 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
<?php
namespace Gaufrette\Util;
/**
* Path utils.
*
* @author Antoine Hérault <antoine.herault@gmail.com>
*/
class Path
{
/**
* Normalizes the given path.
*
* @param string $path
*
* @return string
*/
public static function normalize($path)
{
$path = str_replace('\\', '/', $path);
$prefix = static::getAbsolutePrefix($path);
$path = substr($path, strlen($prefix));
$parts = array_filter(explode('/', $path), 'strlen');
$tokens = [];
foreach ($parts as $part) {
switch ($part) {
case '.':
continue 2;
case '..':
if (0 !== count($tokens)) {
array_pop($tokens);
continue 2;
} elseif (!empty($prefix)) {
continue 2;
}
default:
$tokens[] = $part;
}
}
return $prefix . implode('/', $tokens);
}
/**
* Indicates whether the given path is absolute or not.
*
* @param string $path A normalized path
*
* @return bool
*/
public static function isAbsolute($path)
{
return '' !== static::getAbsolutePrefix($path);
}
/**
* Returns the absolute prefix of the given path.
*
* @param string $path A normalized path
*
* @return string
*/
public static function getAbsolutePrefix($path)
{
preg_match('|^(?P<prefix>([a-zA-Z]+:)?//?)|', $path, $matches);
if (empty($matches['prefix'])) {
return '';
}
return strtolower($matches['prefix']);
}
/**
* Wrap native dirname function in order to handle only UNIX-style paths
*
* @param string $path
*
* @return string
*
* @see http://php.net/manual/en/function.dirname.php
*/
public static function dirname($path)
{
return str_replace('\\', '/', \dirname($path));
}
}