Path::canonical()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 20
ccs 6
cts 6
cp 1
rs 9.9332
cc 4
nc 4
nop 1
crap 4
1
<?php
2
3
namespace ElegantMedia\PHPToolkit;
4
5
class Path
6
{
7
	/**
8
	 * Add a trailing slash to the end of a string (if it doesn't exist).
9
	 *
10
	 * @param $path
11
	 *
12
	 * @return string
13
	 */
14
	public static function withEndingSlash($path): string
15
	{
16
		return rtrim($path, '/') . '/';
17 3
	}
18
19 3
	/**
20
	 * Remove the trailing slash from a string (if exists).
21
	 *
22
	 * @param $path
23
	 *
24
	 * @return string
25
	 */
26
	public static function withoutEndingSlash($path): string
27
	{
28
		return rtrim($path, '/');
29
	}
30 3
31
	/**
32 3
	 * Remove the leading slash of a string (if exists).
33
	 *
34
	 * @param $path
35
	 *
36
	 * @return string
37
	 */
38
	public static function withoutStartingSlash($path): string
39
	{
40
		$firstChar = $path[0];
41
		$hasLeadingSlash = $firstChar === '/';
42
		if (!$hasLeadingSlash) {
43 3
			return $path;
44
		}
45 3
46 3
		return ltrim($path, $firstChar);
47 3
	}
48 3
49
	/**
50
	 * Add a leading slash to a string (if it doesn't exist).
51 3
	 *
52
	 * @param $path
53
	 *
54
	 * @return string
55
	 */
56
	public static function withStartingSlash($path): string
57
	{
58
		return '/' . ltrim($path, '/');
59
	}
60
61
	/**
62
	 * Remove dot segments from paths.
63
	 *
64 3
	 * @see https://tools.ietf.org/html/rfc3986#section-5.2.4
65
	 * @see https://stackoverflow.com/a/21486848/1234452
66 3
	 *
67 3
	 * @param $path
68 3
	 *
69 3
	 * @return string
70
	 */
71 3
	public static function canonical($path): string
72 3
	{
73
		$path = explode('/', $path);
74
		$stack = [];
75 3
		foreach ($path as $seg) {
76
			if ($seg == '..') {
77 3
				// Ignore this segment, remove last segment from stack
78
				array_pop($stack);
79
				continue;
80 3
			}
81
82
			if ($seg == '.') {
83 3
				// Ignore this segment
84
				continue;
85
			}
86
87
			$stack[] = $seg;
88
		}
89
90
		return implode('/', $stack);
91
	}
92
}
93