Completed
Push — master ( bc3e86...3980d1 )
by Michal
03:02
created

Utils::normalizePath()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 23
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.243

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 23
ccs 7
cts 10
cp 0.7
rs 9.0856
cc 3
eloc 10
nc 4
nop 2
crap 3.243
1
<?php
2
3
namespace Webrouse\AssetMacro;
4
5
6
use Webrouse\AssetMacro\Exceptions\InvalidPathException;
7
8
class Utils
9
{
10 1
    public static function normalizePath($path, $separator = '\\/')
11
    {
12
        // Remove any kind of unicode whitespace
13 1
        $normalized = preg_replace('#\p{C}+|^\./#u', '', $path);
14
15
        // Path remove self referring paths ("/./").
16 1
        $normalized = preg_replace('#/\.(?=/)|^\./|\./$#', '', $normalized);
17
18
        // Regex for resolving relative paths
19 1
        $regex = '#\/*[^/\.]+/\.\.#Uu';
20
21 1
        while (preg_match($regex, $normalized)) {
22
            $normalized = preg_replace($regex, '', $normalized);
23
        }
24
25 1
        if (preg_match('#/\.{2}|\.{2}/#', $normalized)) {
26
            throw new InvalidPathException(
27
                sprintf("Path is outside of the defined root, path: '%s', resolved: '%s'.", $path, $normalized)
28
            );
29
        }
30
31 1
        return rtrim($normalized, $separator);
32
    }
33
34
    /**
35
     * @param \Exception $e
36
     * @param string $action
37
     * @param bool $need
38
     * @throws \Exception
39
     */
40 1
    public static function throwError(\Exception $e, $action = 'exception', $need = TRUE)
41
    {
42 1
        if ($need) {
43 1
            if ($action === 'exception') {
44 1
                throw $e;
45
46 1
            } elseif ($action === 'notice') {
47 1
                trigger_error($e->getMessage(), E_USER_NOTICE);
48
            }
49
        }
50
    }
51
}