SanitizePaths::guardedPaths()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
ccs 0
cts 3
cp 0
crap 2
rs 10
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