PutRequestMiddleware::handle()   B
last analyzed

Complexity

Conditions 7
Paths 4

Size

Total Lines 55

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 16.3542

Importance

Changes 0
Metric Value
dl 0
loc 55
ccs 14
cts 33
cp 0.4242
rs 8.0484
c 0
b 0
f 0
cc 7
nc 4
nop 2
crap 16.3542

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Djunehor\PutHelper;
4
5
use Closure;
6
use Illuminate\Http\Request;
7
use Illuminate\Http\UploadedFile;
8
9
class PutRequestMiddleware
10
{
11
    /**
12
     * Handle an incoming request.
13
     *
14
     * @param \Illuminate\Http\Request $request
15
     * @param \Closure $next
16
     * @return mixed
17
     */
18
19 5
    public function handle(Request $request, Closure $next)
20
    {
21
        // to indicate put middleware was called
22 5
        session()->put(self::class, true);
23 5
        if ($request->isMethod('PUT')) {
24
            // to indicate that action is performed for PUT request
25 4
            session()->put(self::class, session()->token());
26 4
            $string = file_get_contents('php://input');
27 4
            $array = explode("Content-Disposition: form-data;", $string);
28 4
            $payload = [];
29
30
            // reformat payload
31 4
            foreach ($array as $item) {
32 4
                if (stripos($item, 'name') !== false) {
33
                    $key = $this->getStringBetween($item, 'name="', '"');
34
35
                    // if it's a file
36
                    if (stripos($item, 'filename') != false) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing stripos($item, 'filename') of type integer to the boolean false. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
37
                        $filename = $this->getStringBetween($item, 'filename="', '"');
38
                        if (!$filename) continue;
39
40
                        $contentType = $this->getStringBetween($item, 'Content-Type: ', "\r");
41
                        $newArray = explode('Content-Type: ' . $contentType, $string);
42
                        $filePath = sys_get_temp_dir() . $filename;
43
                        file_put_contents($filePath, trim($newArray[1]));
44
                        $value = new UploadedFile($filePath, $filename, null, null, false, true);
0 ignored issues
show
Unused Code introduced by
The call to UploadedFile::__construct() has too many arguments starting with true.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
45
46
                        $payload[$key] = $value;
47
                        $_FILES[$key] = [
48
                            'name' => $filename,
49
                            'type' => $contentType,
50
                            'tmp_name' => $filePath,
51
                            "error" => 0,
52
                            "size" => $value->getSize()
53
                        ];
54
                    } else {
55
                        $value = $this->getStringBetween($item, 'name="' . $key . '"', '----------------------------');
56
                        $payload[$key] = $value;
57 4
                        $_POST[$key] = $value;
58
                    }
59
60
                }
61
            }
62
63 4
            $request->merge($payload);
64
        }
65
66 5
        $response = $next($request);
67
68
        // let's delete tmp uploaded file, if any, to save space
69 5
        if (isset($filePath)) {
70
            @unlink($filePath);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
71
        }
72 5
        return $response;
73
    }
74
75
    private function getStringBetween($string, $start, $end)
76
    {
77
        $string = ' ' . $string;
78
        $ini = strpos($string, $start);
79
        if ($ini == 0) return '';
80
        $ini += strlen($start);
81
        $len = strpos($string, $end, $ini) - $ini;
82
        $newString = substr($string, $ini, $len);
83
        return trim($newString);
84
    }
85
}
86