Passed
Push — master ( d70309...589f51 )
by Shane
14:25
created

Path::withStartingSlash()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

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