Completed
Push — master ( 3980d1...e5ab6e )
by Michal
04:31
created

Utils   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 82.35%

Importance

Changes 0
Metric Value
wmc 7
c 0
b 0
f 0
lcom 0
cbo 1
dl 0
loc 53
ccs 14
cts 17
cp 0.8235
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A normalizePath() 0 23 3
A throwError() 0 11 4
1
<?php
2
3
namespace Webrouse\AssetMacro;
4
5
use Webrouse\AssetMacro\Exceptions\InvalidPathException;
6
7
8
class Utils
9
{
10
11
	/**
12
	 * @param string $path
13
	 * @param string $separator
14
	 * @return string
15
	 */
16 1
	public static function normalizePath($path, $separator = '\\/')
17
	{
18
		// Remove any kind of unicode whitespace
19 1
		$normalized = preg_replace('#\p{C}+|^\./#u', '', $path);
20
21
		// Path remove self referring paths ("/./").
22 1
		$normalized = preg_replace('#/\.(?=/)|^\./|\./$#', '', $normalized);
23
24
		// Regex for resolving relative paths
25 1
		$regex = '#\/*[^/\.]+/\.\.#Uu';
26
27 1
		while (preg_match($regex, $normalized)) {
28
			$normalized = preg_replace($regex, '', $normalized);
29
		}
30
31 1
		if (preg_match('#/\.{2}|\.{2}/#', $normalized)) {
32
			throw new InvalidPathException(
33
				sprintf("Path is outside of the defined root, path: '%s', resolved: '%s'.", $path, $normalized)
34
			);
35
		}
36
37 1
		return rtrim($normalized, $separator);
38
	}
39
40
41
	/**
42
	 * Throw exception, trigger error or ignore according of action
43
	 * @param \Exception $e
44
	 * @param string $action
45
	 * @param bool $need
46
	 * @throws \Exception
47
	 */
48 1
	public static function throwError(\Exception $e, $action = 'exception', $need = TRUE)
49
	{
50 1
		if ($need) {
51 1
			if ($action === 'exception') {
52 1
				throw $e;
53
54 1
			} elseif ($action === 'notice') {
55 1
				trigger_error($e->getMessage(), E_USER_NOTICE);
56
			}
57
		}
58 1
	}
59
60
}
61