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

Utils   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 83.33%

Importance

Changes 0
Metric Value
wmc 7
c 0
b 0
f 0
lcom 0
cbo 1
dl 0
loc 44
ccs 15
cts 18
cp 0.8333
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
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
}