Completed
Push — master ( b77dd2...b4def4 )
by Michal
04:25
created

Utils::normalizePath()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 25
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 25
ccs 10
cts 10
cp 1
rs 8.5806
cc 4
eloc 11
nc 6
nop 1
crap 4
1
<?php
2
3
namespace Webrouse\AssetMacro;
4
5
use Nette\Utils\Strings;
6
use Webrouse\AssetMacro\Exceptions\InvalidPathException;
7
8
9
class Utils
10
{
11
12
	/**
13
	 * @param string $path
14
	 * @param string $separator
0 ignored issues
show
Bug introduced by
There is no parameter named $separator. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
15
	 * @return string
16
	 */
17
	public static function normalizePath($path)
18
	{
19
		// Remove any kind of unicode whitespace
20 1
		$normalized = preg_replace('#\p{C}+|^\./#u', '', $path);
21
22
		// Path remove self referring paths ("/./").
23 1
		$normalized = preg_replace('#/\.(?=/)|^\./|\./$#', '', $normalized);
24
25
		// Regex for resolving relative paths
26 1
		$regex = '#\/*[^/\.]+/\.\.#Uu';
27
28 1
		while (preg_match($regex, $normalized)) {
29 1
			$normalized = preg_replace($regex, '', $normalized);
30
		}
31
32 1
		if (preg_match('#/\.{2}|\.{2}/#', $normalized)) {
33 1
			throw new InvalidPathException(
34 1
				sprintf("Path is outside of the defined root, path: '%s', resolved: '%s'.", $path, $normalized)
35
			);
36
		}
37
38 1
		$normalized = trim($normalized, '\\/');
39
40 1
		return Strings::match($path, '~^\\/~') ? ('/' . $normalized) : $normalized;
41
	}
42
43
44
	/**
45
	 * Throw exception, trigger error or ignore according of action
46
	 * @param \Exception $e
47
	 * @param string $action
48
	 * @param bool $need
49
	 * @throws \Exception
50
	 */
51 1
	public static function throwError(\Exception $e, $action = 'exception', $need = TRUE)
52
	{
53 1
		if ($need) {
54 1
			if ($action === 'exception') {
55 1
				throw $e;
56
57 1
			} elseif ($action === 'notice') {
58 1
				trigger_error($e->getMessage(), E_USER_NOTICE);
59
			}
60
		}
61 1
	}
62
63
}
64