Completed
Pull Request — master (#397)
by Albin
02:43
created

Path   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 80
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 10
c 2
b 1
f 0
lcom 0
cbo 0
dl 0
loc 80
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
B normalize() 0 26 6
A isAbsolute() 0 4 1
A getAbsolutePrefix() 0 10 2
A dirname() 0 4 1
1
<?php
2
3
namespace Gaufrette\Util;
4
5
/**
6
 * Path utils.
7
 *
8
 * @author  Antoine Hérault <[email protected]>
9
 */
10
class Path
11
{
12
    /**
13
     * Normalizes the given path.
14
     *
15
     * @param string $path
16
     *
17
     * @return string
18
     */
19
    public static function normalize($path)
20
    {
21
        $path = str_replace('\\', '/', $path);
22
        $prefix = static::getAbsolutePrefix($path);
23
        $path = substr($path, strlen($prefix));
24
        $parts = array_filter(explode('/', $path), 'strlen');
25
        $tokens = array();
26
27
        foreach ($parts as $part) {
28
            switch ($part) {
29
                case '.':
30
                    continue;
31
                case '..':
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
32
                    if (0 !== count($tokens)) {
33
                        array_pop($tokens);
34
                        continue;
35
                    } elseif (!empty($prefix)) {
36
                        continue;
37
                    }
38
                default:
39
                    $tokens[] = $part;
40
            }
41
        }
42
43
        return $prefix.implode('/', $tokens);
44
    }
45
46
    /**
47
     * Indicates whether the given path is absolute or not.
48
     *
49
     * @param string $path A normalized path
50
     *
51
     * @return bool
52
     */
53
    public static function isAbsolute($path)
54
    {
55
        return '' !== static::getAbsolutePrefix($path);
56
    }
57
58
    /**
59
     * Returns the absolute prefix of the given path.
60
     *
61
     * @param string $path A normalized path
62
     *
63
     * @return string
64
     */
65
    public static function getAbsolutePrefix($path)
66
    {
67
        preg_match('|^(?P<prefix>([a-zA-Z]+:)?//?)|', $path, $matches);
68
69
        if (empty($matches['prefix'])) {
70
            return '';
71
        }
72
73
        return strtolower($matches['prefix']);
74
    }
75
76
    /**
77
     * Wrap native dirname function in order to handle only UNIX-style paths
78
     *
79
     * @param string $path
80
     *
81
     * @return string
82
     *
83
     * @see http://php.net/manual/en/function.dirname.php
84
     */
85
    public static function dirname($path)
86
    {
87
        return str_replace('\\', '/', \dirname($path));
88
    }
89
}
90