SanitizePaths   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 21
c 2
b 0
f 0
dl 0
loc 63
ccs 0
cts 23
cp 0
rs 10
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A handle() 0 9 2
A sanitizePath() 0 25 6
A guardedPaths() 0 5 1
1
<?php
2
3
namespace Terranet\Administrator\Middleware;
4
5
use Closure;
6
use Illuminate\Http\Request;
7
use Illuminate\Support\Arr;
8
9
class SanitizePaths
10
{
11
    /**
12
     * Handle an incoming request.
13
     *
14
     * @param \Illuminate\Http\Request $request
15
     * @param \Closure $next
16
     *
17
     * @return mixed
18
     */
19
    public function handle(Request $request, Closure $next)
20
    {
21
        if (!empty($paths = $this->guardedPaths($request))) {
22
            $request->merge(
23
                array_map([$this, 'sanitizePath'], $paths)
24
            );
25
        }
26
27
        return $next($request);
28
    }
29
30
    /**
31
     * @param string $path
32
     *
33
     * @return string
34
     */
35
    protected function sanitizePath($path)
36
    {
37
        if (\is_array($path)) {
0 ignored issues
show
introduced by
The condition is_array($path) is always false.
Loading history...
38
            return array_map([$this, 'sanitizePath'], $path);
39
        }
40
41
        $path = iconv($encoding = 'UTF-8', "$encoding//IGNORE//TRANSLIT", $path);
42
43
        $parts = explode('/', $path);
44
        $safe = [];
45
        foreach ($parts as $part) {
46
            if (empty($part) || ('.' === $part)) {
47
                continue;
48
            }
49
50
            if ('..' === $part) {
51
                array_pop($safe);
52
53
                continue;
54
            }
55
56
            $safe[] = $part;
57
        }
58
59
        return implode(\DIRECTORY_SEPARATOR, $safe);
60
    }
61
62
    /**
63
     * @param Request $request
64
     *
65
     * @return array
66
     */
67
    protected function guardedPaths(Request $request)
68
    {
69
        return Arr::only(
70
            $request->all(),
71
            ['path', 'basedir', 'directories', 'from', 'to', 'name']
72
        );
73
    }
74
}
75