Passed
Pull Request — master (#31)
by Anatoly
39:30
created

server_request_files()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 48
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 34
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 30
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 48
ccs 34
cts 34
cp 1
crap 6
rs 8.8177
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_NO_FILE;
28
29
/**
30
 * Gets the request's uploaded files
31
 *
32
 * Note that not sent files will not be handled.
33
 *
34
 * @param array|null $files
35
 *
36
 * @return array
37
 *
38
 * @link http://php.net/manual/en/reserved.variables.files.php
39
 * @link https://www.php.net/manual/ru/features.file-upload.post-method.php
40
 * @link https://www.php.net/manual/ru/features.file-upload.multiple.php
41
 * @link https://github.com/php/php-src/blob/8c5b41cefb88b753c630b731956ede8d9da30c5d/main/rfc1867.c
42
 */
43
function server_request_files(?array $files = null): array
44
{
45 39
    $files ??= $_FILES;
46
47 39
    $walker = function ($path, $size, $error, $name, $type) use (&$walker) {
48 2
        if (!is_array($path)) {
49
            // What if the path is an empty string?
50 2
            $stream = new FileStream($path, 'rb');
51
52 2
            return new UploadedFile(
53 2
                $stream,
54 2
                $size,
55 2
                $error,
56 2
                $name,
57 2
                $type
58 2
            );
59
        }
60
61 1
        $result = [];
62 1
        foreach ($path as $key => $_) {
63 1
            if (UPLOAD_ERR_NO_FILE <> $error[$key]) {
64 1
                $result[$key] = $walker(
65 1
                    $path[$key],
66 1
                    $size[$key],
67 1
                    $error[$key],
68 1
                    $name[$key],
69 1
                    $type[$key]
70 1
                );
71
            }
72
        }
73
74 1
        return $result;
75 39
    };
76
77 39
    $result = [];
78 39
    foreach ($files as $key => $file) {
79 2
        if (UPLOAD_ERR_NO_FILE <> $file['error']) {
80 2
            $result[$key] = $walker(
81 2
                $file['tmp_name'],
82 2
                $file['size'],
83 2
                $file['error'],
84 2
                $file['name'],
85 2
                $file['type']
86 2
            );
87
        }
88
    }
89
90 39
    return $result;
91
}
92