Test Failed
Pull Request — master (#31)
by Anatoly
39:08
created

server_request_files()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 42
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 25
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 42
ccs 15
cts 15
cp 1
crap 7
rs 8.5866
1
<?php declare(strict_types=1);
2
3
/**
4
 * It's free open-source software released under the MIT License.
5
 *
6
 * @author Anatoly Nekhay <[email protected]>
7
 * @copyright Copyright (c) 2018, Anatoly Nekhay
8
 * @license https://github.com/sunrise-php/http-message/blob/master/LICENSE
9
 * @link https://github.com/sunrise-php/http-message
10
 */
11
12
namespace Sunrise\Http\Message;
13
14
/**
15
 * Import classes
16
 */
17
use Sunrise\Http\Message\Stream\FileStream;
18
19
/**
20
 * Import functions
21
 */
22
use function is_array;
23
24
/**
25
 * Import constants
26
 */
27
use const UPLOAD_ERR_OK;
28
use const UPLOAD_ERR_NO_FILE;
29
30
/**
31
 * Gets the request's uploaded files
32
 *
33
 * Please note that unsent files will not be handled.
34
 *
35
 * @param array|null $files
36
 *
37
 * @return array
38
 *
39
 * @link http://php.net/manual/en/reserved.variables.files.php
40
 * @link https://www.php.net/manual/ru/features.file-upload.post-method.php
41
 * @link https://www.php.net/manual/ru/features.file-upload.multiple.php
42
 * @link https://github.com/php/php-src/blob/8c5b41cefb88b753c630b731956ede8d9da30c5d/main/rfc1867.c
43
 */
44
function server_request_files(?array $files = null): array
45 39
{
46
    $files ??= $_FILES;
47 39
48 2
    $walker = static function ($path, $size, $error, $name, $type) use (&$walker) {
49 2
        if (!is_array($path)) {
50
            // It makes no sense to create a stream if the file has not been successfully uploaded.
51
            $stream = UPLOAD_ERR_OK <> $error ? null : new FileStream($path, 'rb');
52 1
53 1
            return new UploadedFile($stream, $size, $error, $name, $type);
54 1
        }
55 1
56
        $result = [];
57
        foreach ($path as $key => $_) {
58
            if (UPLOAD_ERR_NO_FILE <> $error[$key]) {
59 1
                $result[$key] = $walker(
60 39
                    $path[$key],
61
                    $size[$key],
62 39
                    $error[$key],
63 39
                    $name[$key],
64 2
                    $type[$key]
65 2
                );
66
            }
67
        }
68
69 39
        return $result;
70
    };
71
72
    $result = [];
73
    foreach ($files as $key => $file) {
74
        if (UPLOAD_ERR_NO_FILE <> $file['error']) {
75
            $result[$key] = $walker(
76
                $file['tmp_name'],
77
                $file['size'],
78
                $file['error'],
79
                $file['name'],
80
                $file['type']
81
            );
82
        }
83
    }
84
85
    return $result;
86
}
87