Completed
Push — master ( 49564a...c92cef )
by Dmitry
30s
created

MultipartFormDataParser::parse()   C

Complexity

Conditions 13
Paths 12

Size

Total Lines 77
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 13.4587

Importance

Changes 0
Metric Value
dl 0
loc 77
ccs 37
cts 43
cp 0.8605
rs 5.2202
c 0
b 0
f 0
cc 13
eloc 49
nc 12
nop 2
crap 13.4587

How to fix   Long Method    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
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\web;
9
10
use yii\base\Object;
11
use yii\helpers\ArrayHelper;
12
use yii\helpers\StringHelper;
13
14
/**
15
 * MultipartFormDataParser parses content encoded as 'multipart/form-data'.
16
 * This parser provides the fallback for the 'multipart/form-data' processing on non POST requests,
17
 * for example: the one with 'PUT' request method.
18
 *
19
 * In order to enable this parser you should configure [[Request::parsers]] in the following way:
20
 *
21
 * ```php
22
 * return [
23
 *     'components' => [
24
 *         'request' => [
25
 *             'parsers' => [
26
 *                 'multipart/form-data' => 'yii\web\MultipartFormDataParser'
27
 *             ],
28
 *         ],
29
 *         // ...
30
 *     ],
31
 *     // ...
32
 * ];
33
 * ```
34
 *
35
 * Method [[parse()]] of this parser automatically populates `$_FILES` with the files parsed from raw body.
36
 *
37
 * > Note: since this is a request parser, it will initialize `$_FILES` values on [[Request::getBodyParams()]].
38
 * Until this method is invoked, `$_FILES` array will remain empty even if there are submitted files in the
39
 * request body. Make sure you have requested body params before any attempt to get uploaded file in case
40
 * you are using this parser.
41
 *
42
 * Usage example:
43
 *
44
 * ```php
45
 * use yii\web\UploadedFile;
46
 *
47
 * $restRequestData = Yii::$app->request->getBodyParams();
48
 * $uploadedFile = UploadedFile::getInstancesByName('photo');
49
 *
50
 * $model = new Item();
51
 * $model->populate($restRequestData);
52
 * copy($uploadedFile->tempName, '/path/to/file/storage/photo.jpg');
53
 * ```
54
 *
55
 * > Note: although this parser fully emulates regular structure of the `$_FILES`, related temporary
56
 * files, which are available via `tmp_name` key, will not be recognized by PHP as uploaded ones.
57
 * Thus functions like `is_uploaded_file()` and `move_uploaded_file()` will fail on them. This also
58
 * means [[UploadedFile::saveAs()]] will fail as well.
59
 *
60
 * @property int $uploadFileMaxCount Maximum upload files count.
61
 * @property int $uploadFileMaxSize Upload file max size in bytes.
62
 *
63
 * @author Paul Klimov <[email protected]>
64
 * @since 2.0.10
65
 */
66
class MultipartFormDataParser extends Object implements RequestParserInterface
67
{
68
    /**
69
     * @var int upload file max size in bytes.
70
     */
71
    private $_uploadFileMaxSize;
72
    /**
73
     * @var int maximum upload files count.
74
     */
75
    private $_uploadFileMaxCount;
76
77
78
    /**
79
     * @return int upload file max size in bytes.
80
     */
81 3
    public function getUploadFileMaxSize()
82
    {
83 3
        if ($this->_uploadFileMaxSize === null) {
84 2
            $this->_uploadFileMaxSize = $this->getByteSize(ini_get('upload_max_filesize'));
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getByteSize(ini_g...'upload_max_filesize')) can also be of type double. However, the property $_uploadFileMaxSize is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
85
        }
86 3
        return $this->_uploadFileMaxSize;
87
    }
88
89
    /**
90
     * @param int $uploadFileMaxSize upload file max size in bytes.
91
     */
92 1
    public function setUploadFileMaxSize($uploadFileMaxSize)
93
    {
94 1
        $this->_uploadFileMaxSize = $uploadFileMaxSize;
95 1
    }
96
97
    /**
98
     * @return int maximum upload files count.
99
     */
100 3
    public function getUploadFileMaxCount()
101
    {
102 3
        if ($this->_uploadFileMaxCount === null) {
103 2
            $this->_uploadFileMaxCount = ini_get('max_file_uploads');
0 ignored issues
show
Documentation Bug introduced by
The property $_uploadFileMaxCount was declared of type integer, but ini_get('max_file_uploads') is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
104
        }
105 3
        return $this->_uploadFileMaxCount;
106
    }
107
108
    /**
109
     * @param int $uploadFileMaxCount maximum upload files count.
110
     */
111 1
    public function setUploadFileMaxCount($uploadFileMaxCount)
112
    {
113 1
        $this->_uploadFileMaxCount = $uploadFileMaxCount;
114 1
    }
115
116
    /**
117
     * @inheritdoc
118
     */
119 5
    public function parse($rawBody, $contentType)
120
    {
121 5
        if (!empty($_POST) || !empty($_FILES)) {
122
            // normal POST request is parsed by PHP automatically
123 2
            return $_POST;
124
        }
125
126 3
        if (empty($rawBody)) {
127
            return [];
128
        }
129
130 3
        if (!preg_match('/boundary=(.*)$/is', $contentType, $matches)) {
131
            return [];
132
        }
133 3
        $boundary = $matches[1];
134
135 3
        $bodyParts = preg_split('/\\R?-+' . preg_quote($boundary, '/') . '/s', $rawBody);
136 3
        array_pop($bodyParts); // last block always has no data, contains boundary ending like `--`
137
138 3
        $bodyParams = [];
139 3
        $filesCount = 0;
140 3
        foreach ($bodyParts as $bodyPart) {
141 3
            if (empty($bodyPart)) {
142 3
                continue;
143
            }
144 3
            list($headers, $value) = preg_split("/\\R\\R/", $bodyPart, 2);
145 3
            $headers = $this->parseHeaders($headers);
146
147 3
            if (!isset($headers['content-disposition']['name'])) {
148
                continue;
149
            }
150
151 3
            if (isset($headers['content-disposition']['filename'])) {
152
                // file upload:
153 3
                if ($filesCount >= $this->getUploadFileMaxCount()) {
154 1
                    continue;
155
                }
156
157
                $fileInfo = [
158 3
                    'name' => $headers['content-disposition']['filename'],
159 3
                    'type' => ArrayHelper::getValue($headers, 'content-type', 'application/octet-stream'),
160 3
                    'size' => StringHelper::byteLength($value),
161 3
                    'error' => UPLOAD_ERR_OK,
162
                    'tmp_name' => null,
163
                ];
164
165 3
                if ($fileInfo['size'] > $this->getUploadFileMaxSize()) {
166 1
                    $fileInfo['error'] = UPLOAD_ERR_INI_SIZE;
167
                } else {
168 3
                    $tmpResource = tmpfile();
169 3
                    if ($tmpResource === false) {
170
                        $fileInfo['error'] = UPLOAD_ERR_CANT_WRITE;
171
                    } else {
172 3
                        $tmpResourceMetaData = stream_get_meta_data($tmpResource);
173 3
                        $tmpFileName = $tmpResourceMetaData['uri'];
174 3
                        if (empty($tmpFileName)) {
175
                            $fileInfo['error'] = UPLOAD_ERR_CANT_WRITE;
176
                            @fclose($tmpResource);
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...
177
                        } else {
178 3
                            fwrite($tmpResource, $value);
179 3
                            $fileInfo['tmp_name'] = $tmpFileName;
180 3
                            $fileInfo['tmp_resource'] = $tmpResource; // save file resource, otherwise it will be deleted
181
                        }
182
                    }
183
                }
184
185 3
                $this->addFile($_FILES, $headers['content-disposition']['name'], $fileInfo);
186
187 3
                $filesCount++;
188
            } else {
189
                // regular parameter:
190 1
                $this->addValue($bodyParams, $headers['content-disposition']['name'], $value);
191
            }
192
        }
193
194 3
        return $bodyParams;
195
    }
196
197
    /**
198
     * Parses content part headers.
199
     * @param string $headerContent headers source content
200
     * @return array parsed headers.
201
     */
202 3
    private function parseHeaders($headerContent)
203
    {
204 3
        $headers = [];
205 3
        $headerParts = preg_split("/\\R/s", $headerContent, -1, PREG_SPLIT_NO_EMPTY);
206 3
        foreach ($headerParts as $headerPart) {
207 3
            if (($separatorPos = strpos($headerPart, ':')) === false) {
208
                continue;
209
            }
210
211 3
            list($headerName, $headerValue) = explode(':', $headerPart, 2);
212 3
            $headerName = strtolower(trim($headerName));
213 3
            $headerValue = trim($headerValue);
214
215 3
            if (strpos($headerValue, ';') === false) {
216 3
                $headers[$headerName] = $headerValue;
217
            } else {
218 3
                $headers[$headerName] = [];
219 3
                foreach (explode(';', $headerValue) as $part) {
220 3
                    $part = trim($part);
221 3
                    if (strpos($part, '=') === false) {
222 3
                        $headers[$headerName][] = $part;
223
                    } else {
224 3
                        list($name, $value) = explode('=', $part, 2);
225 3
                        $name = strtolower(trim($name));
226 3
                        $value = trim(trim($value), '"');
227 3
                        $headers[$headerName][$name] = $value;
228
                    }
229
                }
230
            }
231
        }
232
233 3
        return $headers;
234
    }
235
236
    /**
237
     * Adds value to the array by input name, e.g. `Item[name]`.
238
     * @param array $array array which should store value.
239
     * @param string $name input name specification.
240
     * @param mixed $value value to be added.
241
     */
242 1
    private function addValue(&$array, $name, $value)
243
    {
244 1
        $nameParts = preg_split('/\\]\\[|\\[/s', $name);
245 1
        $current = &$array;
246 1
        foreach ($nameParts as $namePart) {
247 1
            $namePart = trim($namePart, ']');
248 1
            if ($namePart === '') {
249
                $current[] = [];
250
                $lastKey = array_pop(array_keys($current));
0 ignored issues
show
Bug introduced by
array_keys($current) cannot be passed to array_pop() as the parameter $array expects a reference.
Loading history...
251
                $current = &$current[$lastKey];
252
            } else {
253 1
                if (!isset($current[$namePart])) {
254 1
                    $current[$namePart] = [];
255
                }
256 1
                $current = &$current[$namePart];
257
            }
258
        }
259 1
        $current = $value;
260 1
    }
261
262
    /**
263
     * Adds file info to the uploaded files array by input name, e.g. `Item[file]`.
264
     * @param array $files array containing uploaded files
265
     * @param string $name input name specification.
266
     * @param array $info file info.
267
     */
268 3
    private function addFile(&$files, $name, $info)
269
    {
270 3
        if (strpos($name, '[') === false) {
271 3
            $files[$name] = $info;
272 3
            return;
273
        }
274
275
        $fileInfoAttributes = [
276 1
            'name',
277
            'type',
278
            'size',
279
            'error',
280
            'tmp_name',
281
            'tmp_resource'
282
        ];
283
284 1
        $nameParts = preg_split('/\\]\\[|\\[/s', $name);
285 1
        $baseName = array_shift($nameParts);
286 1
        if (!isset($files[$baseName])) {
287 1
            $files[$baseName] = [];
288 1
            foreach ($fileInfoAttributes as $attribute) {
289 1
                $files[$baseName][$attribute] = [];
290
            }
291
        } else {
292
            foreach ($fileInfoAttributes as $attribute) {
293
                $files[$baseName][$attribute] = (array)$files[$baseName][$attribute];
294
            }
295
        }
296
297 1
        foreach ($fileInfoAttributes as $attribute) {
298 1
            if (!isset($info[$attribute])) {
299
                continue;
300
            }
301
302 1
            $current = &$files[$baseName][$attribute];
303 1
            foreach ($nameParts as $namePart) {
304 1
                $namePart = trim($namePart, ']');
305 1
                if ($namePart === '') {
306
                    $current[] = [];
307
                    $lastKey = array_pop(array_keys($current));
0 ignored issues
show
Bug introduced by
array_keys($current) cannot be passed to array_pop() as the parameter $array expects a reference.
Loading history...
308
                    $current = &$current[$lastKey];
309
                } else {
310 1
                    if (!isset($current[$namePart])) {
311 1
                        $current[$namePart] = [];
312
                    }
313 1
                    $current = &$current[$namePart];
314
                }
315
            }
316 1
            $current = $info[$attribute];
317
        }
318 1
    }
319
320
    /**
321
     * Gets the size in bytes from verbose size representation.
322
     * For example: '5K' => 5*1024
323
     * @param string $verboseSize verbose size representation.
324
     * @return int actual size in bytes.
325
     */
326 2
    private function getByteSize($verboseSize)
327
    {
328 2
        if (empty($verboseSize)) {
329
            return 0;
330
        }
331 2
        if (is_numeric($verboseSize)) {
332
            return (int) $verboseSize;
333
        }
334 2
        $sizeUnit = trim($verboseSize, '0123456789');
335 2
        $size = str_replace($sizeUnit, '', $verboseSize);
336 2
        $size = trim($size);
337 2
        if (!is_numeric($size)) {
338
            return 0;
339
        }
340 2
        switch (strtolower($sizeUnit)) {
341 2
            case 'kb':
342 2
            case 'k':
343
                return $size * 1024;
344 2
            case 'mb':
345 2
            case 'm':
346 2
                return $size * 1024 * 1024;
347
            case 'gb':
348
            case 'g':
349
                return $size * 1024 * 1024 * 1024;
350
            default:
351
                return 0;
352
        }
353
    }
354
}
355