From 6c17b8026a231c77022d6ea5da054ac0ea5a60ea Mon Sep 17 00:00:00 2001 From: Andreas Schempp Date: Mon, 9 Dec 2024 15:11:36 +0100 Subject: [PATCH] Support indexed keys of file uploads in file upload normalizer (#229) --- src/FileUploadNormalizer.php | 20 +++++++++++++ tests/FileUploadNormalizerTest.php | 48 ++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/src/FileUploadNormalizer.php b/src/FileUploadNormalizer.php index 9579ef6..66f4fcc 100644 --- a/src/FileUploadNormalizer.php +++ b/src/FileUploadNormalizer.php @@ -33,6 +33,7 @@ public function __construct( public function normalize(array $files): array { $standardizedPerKey = []; + $groups = []; foreach ($files as $k => $file) { switch (true) { @@ -56,6 +57,25 @@ public function normalize(array $files): array $standardizedPerKey[$k][] = $this->fromFile($filePath); break; } + + if (is_string($k) && str_ends_with($k, '_0')) { + $groups[] = substr($k, 0, -2); + } + } + + foreach ($groups as $group) { + if (array_key_exists($group, $standardizedPerKey)) { + continue; + } + + $standardizedPerKey[$group] = []; + + foreach ($standardizedPerKey as $k => $file) { + if (1 === \count($file) && preg_match('/^'.preg_quote($group, '/').'_\d+$/', $k)) { + $standardizedPerKey[$group][] = reset($file); + unset($standardizedPerKey[$k]); + } + } } return $standardizedPerKey; diff --git a/tests/FileUploadNormalizerTest.php b/tests/FileUploadNormalizerTest.php index 27be148..5b2f1aa 100644 --- a/tests/FileUploadNormalizerTest.php +++ b/tests/FileUploadNormalizerTest.php @@ -118,6 +118,54 @@ public static function normalizeProvider(): iterable null, ]; + yield 'File upload with indexed keys' => [ + [ + 'file_0' => [ + 'name' => 'name.jpg', + 'type' => 'image/jpeg', + 'tmp_name' => 'path/to/name.jpg', + 'error' => 0, + 'size' => 333, + 'uploaded' => true, + 'uuid' => '660d272c-f4c3-11ed-a05b-0242ac120003', + ], + 'file_1' => [ + 'name' => 'name.jpg', + 'type' => 'image/jpeg', + 'tmp_name' => 'path/to/name.jpg', + 'error' => 0, + 'size' => 333, + 'uploaded' => true, + 'uuid' => '660d272c-f4c3-11ed-a05b-0242ac120003', + ], + ], + [ + 'file' => [ + [ + 'name' => 'name.jpg', + 'type' => 'image/jpeg', + 'tmp_name' => 'path/to/name.jpg', + 'error' => 0, + 'size' => 333, + 'uploaded' => true, + 'uuid' => '660d272c-f4c3-11ed-a05b-0242ac120003', + ], + [ + 'name' => 'name.jpg', + 'type' => 'image/jpeg', + 'tmp_name' => 'path/to/name.jpg', + 'error' => 0, + 'size' => 333, + 'uploaded' => true, + 'uuid' => '660d272c-f4c3-11ed-a05b-0242ac120003', + ], + ], + ], + '/project-dir', + null, + null, + ]; + yield 'Array of it all' => [ [ 'upload_field_already_correct' => [