3 * @see https://github.com/zendframework/zend-diactoros for the canonical source repository
4 * @copyright Copyright (c) 2018 Zend Technologies USA Inc. (https://www.zend.com)
5 * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License
8 namespace Zend\Diactoros
;
10 use InvalidArgumentException
;
11 use Psr\Http\Message\UploadedFileInterface
;
13 use function is_array
;
16 * Normalize uploaded files
18 * Transforms each value into an UploadedFile instance, and ensures that nested
19 * arrays are normalized.
22 * @return UploadedFileInterface[]
23 * @throws InvalidArgumentException for unrecognized values
25 function normalizeUploadedFiles(array $files)
28 * Normalize an array of file specifications.
30 * Loops through all nested files (as determined by receiving an array to the
31 * `tmp_name` key of a `$_FILES` specification) and returns a normalized array
32 * of UploadedFile instances.
34 * This function normalizes a `$_FILES` array representing a nested set of
35 * uploaded files as produced by the php-fpm SAPI, CGI SAPI, or mod_php
39 * @return UploadedFile[]
41 $normalizeUploadedFileSpecification = function (array $files = []) {
42 if (! isset($files['tmp_name']) ||
! is_array($files['tmp_name'])
43 ||
! isset($files['size']) ||
! is_array($files['size'])
44 ||
! isset($files['error']) ||
! is_array($files['error'])
46 throw new InvalidArgumentException(sprintf(
47 '$files provided to %s MUST contain each of the keys "tmp_name",'
48 . ' "size", and "error", with each represented as an array;'
49 . ' one or more were missing or non-array values',
56 foreach (array_keys($files['tmp_name']) as $key) {
58 'tmp_name' => $files['tmp_name'][$key],
59 'size' => $files['size'][$key],
60 'error' => $files['error'][$key],
61 'name' => isset($files['name'][$key]) ?
$files['name'][$key] : null,
62 'type' => isset($files['type'][$key]) ?
$files['type'][$key] : null,
64 $normalized[$key] = createUploadedFile($spec);
70 foreach ($files as $key => $value) {
71 if ($value instanceof UploadedFileInterface
) {
72 $normalized[$key] = $value;
76 if (is_array($value) && isset($value['tmp_name']) && is_array($value['tmp_name'])) {
77 $normalized[$key] = $normalizeUploadedFileSpecification($value);
81 if (is_array($value) && isset($value['tmp_name'])) {
82 $normalized[$key] = createUploadedFile($value);
86 if (is_array($value)) {
87 $normalized[$key] = normalizeUploadedFiles($value);
91 throw new InvalidArgumentException('Invalid value in files specification');