Completed
Push — master ( 9fe7e8...7331b7 )
by Aurimas
12:47
created

MultiPartBodyParser::parse()   C

Complexity

Conditions 10
Paths 15

Size

Total Lines 50
Code Lines 29

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 50
rs 5.7647
cc 10
eloc 29
nc 15
nop 1

How to fix   Complexity   

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 Thruster\Component\Http\Parser;
4
5
use Psr\Http\Message\ServerRequestInterface;
6
use Thruster\Component\Http\UploadedFile;
7
8
/**
9
 * Class MultiPartBodyParser
10
 *
11
 * @package Thruster\Component\Http\Parser
12
 * @author  Aurimas Niekis <[email protected]>
13
 */
14
class MultiPartBodyParser implements ParserInterface
15
{
16
    /**
17
     * @inheritDoc
18
     */
19
    public function parse(ServerRequestInterface $request) : ServerRequestInterface
20
    {
21
        $headerLine = $request->getHeaderLine('Content-Type');
22
        if (false === strpos($headerLine, 'multipart/')) {
23
            return $request;
24
        }
25
26
        $boundary = null;
27
        if (preg_match("/boundary=\"?(.*)\"?$/", $headerLine, $matches)) {
28
            $boundary = $matches[1];
29
        }
30
31
        $variables = [];
32
        $files     = [];
33
34
        $body     = $request->getBody()->detach();
35
        $partInfo = null;
36
37
        while (false !== ($lineN = fgets($body))) {
38
            if (0 === strpos($lineN, '--')) {
39
                if (null === $boundary) {
40
                    $boundary = rtrim($lineN);
41
                }
42
43
                continue;
44
            }
45
46
            $line = rtrim($lineN);
47
48
            if ('' === $line) {
49
                if (isset($partInfo['Content-Disposition']) &&
50
                    true !== empty($partInfo['Content-Disposition']['filename'])
51
                ) {
52
                    $this->parseFile($body, $boundary, $partInfo, $files);
53
                } elseif ($partInfo !== null) {
54
                    $this->parseVariable($body, $boundary, $partInfo['Content-Disposition']['name'], $variables);
55
                }
56
57
                $partInfo = null;
58
                continue;
59
            }
60
61
            list($key, $value) = explode(':', $line, 2);
62
63
            $partInfo[$key] = $this->parseHeader($value, $key);
64
        }
65
66
        return $request->withParsedBody($variables)
67
            ->withUploadedFiles($files);
68
    }
69
70
    protected function parseFile($body, $boundary, $partInfo, &$files)
71
    {
72
        $tempDir = sys_get_temp_dir();
73
74
        $name        = $partInfo['Content-Disposition']['name'];
75
        $fileName    = $partInfo['Content-Disposition']['filename'] ?? null;
76
        $contentType = $partInfo['Content-Type']['value'] ?? null;
77
78
        if (empty($tempDir)) {
79
            $errorCode = UPLOAD_ERR_NO_TMP_DIR;
80
81
            $files[$name] = new UploadedFile(null, 0, $errorCode, $fileName, $contentType);
82
83
            return;
84
        }
85
86
        $tempName = tempnam($tempDir, 'thruster_file_upload');
87
        $stream   = fopen($tempName, 'wb');
88
89
        if (false === $stream) {
90
            $errorCode = UPLOAD_ERR_CANT_WRITE;
91
92
            $files[$name] = new UploadedFile(null, 0, $errorCode, $fileName, $contentType);
93
94
            return;
95
        }
96
97
        $lastLine = null;
98
        while (false !== ($lineN = fgets($body, 4096))) {
99
            if ($lastLine !== null) {
100
                if (false !== strpos($lineN, $boundary)) {
101
                    break;
102
                }
103
104 View Code Duplication
                if (false === fwrite($stream, $lastLine)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
                    $errorCode = UPLOAD_ERR_CANT_WRITE;
106
107
                    $files[$name] = new UploadedFile(null, 0, $errorCode, $fileName, $contentType);
108
                    fclose($stream);
109
                    unlink($tempName);
110
111
                    return;
112
                }
113
114
            }
115
116
            $lastLine = $lineN;
117
        }
118
119
        if (null !== $lastLine) {
120 View Code Duplication
            if (false === fwrite($stream, rtrim($lastLine, "\r\n"))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
121
                $errorCode = UPLOAD_ERR_CANT_WRITE;
122
123
                $files[$name] = new UploadedFile(null, 0, $errorCode, $fileName, $contentType);
124
                fclose($stream);
125
                unlink($tempName);
126
127
                return;
128
            }
129
        }
130
        
131
        fclose($stream);
132
133
        $files[$name] = new UploadedFile(
134
            $tempName,
135
            filesize($tempName),
136
            UPLOAD_ERR_OK,
137
            $fileName,
138
            $contentType
139
        );
140
    }
141
142
    protected function parseVariable($body, $boundary, $name, &$variables)
143
    {
144
        $fullValue = '';
145
        $lastLine = null;
146
147
        while (false !== ($lineN = fgets($body)) && false === strpos($lineN, $boundary)) {
148
            if (null !== $lastLine) {
149
                $fullValue .= $lastLine;
150
            }
151
152
            $lastLine = $lineN;
153
        }
154
155
        if (null !== $lastLine) {
156
            $fullValue .= rtrim($lastLine, "\r\n");
157
        }
158
159
        $variables[$name] = $fullValue;
160
    }
161
162
    protected function parseHeader($value, $key = '')
163
    {
164
        $result = [];
165
166
        $regex = '/(^|;)\s*(?P<name>[^=:,;\s"]*):?(=("(?P<quotedValue>' .
167
            '[^"]*(\\.[^"]*)*)")|(\s*(?P<value>[^=,;\s"]*)))?/mx';
168
169
        preg_match_all($regex, $value, $matches, PREG_SET_ORDER);
170
171
        foreach ($matches as $index => $match) {
0 ignored issues
show
Bug introduced by
The expression $matches of type null|array<integer,array<integer,string>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
172
            $name        = $match['name'];
173
            $quotedValue = $match['quotedValue'];
174
175
            if (empty($quotedValue)) {
176
                $value = $match['value'];
177
            } else {
178
                $value = stripcslashes($quotedValue);
179
            }
180
181
            if ($name == $key && 0 === $index) {
182
                $name = 'value';
183
            }
184
185
            $result[$name] = $value;
186
        }
187
188
        return $result;
189
    }
190
191
}
192