diff --git a/src/RequestBridge.php b/src/RequestBridge.php index 8c3c383..51fb4d7 100644 --- a/src/RequestBridge.php +++ b/src/RequestBridge.php @@ -2,6 +2,7 @@ namespace Chadicus\Slim\OAuth2\Http; use Psr\Http\Message\ServerRequestInterface; +use Psr\Http\Message\UploadedFileInterface; use OAuth2; /** @@ -69,23 +70,36 @@ private static function cleanupHeaders(array $uncleanHeaders = []) /** * Convert a PSR-7 uploaded files structure to a $_FILES structure. * - * @param \Psr\Http\Message\UploadedFileInterface[] $uploadedFiles Array of file objects. + * @param array $uploadedFiles Array of file objects. * * @return array */ private static function convertUploadedFiles(array $uploadedFiles) { $files = []; - foreach ($uploadedFiles as $name => $upload) { - $files[$name] = [ - 'name' => $upload->getClientFilename(), - 'type' => $upload->getClientMediaType(), - 'size' => $upload->getSize(), - 'tmp_name' => $upload->getStream()->getMetadata('uri'), - 'error' => $upload->getError(), - ]; + foreach ($uploadedFiles as $name => $uploadedFile) { + if (!is_array($uploadedFile)) { + $files[$name] = self::convertUploadedFile($uploadedFile); + continue; + } + + $files[$name] = []; + foreach ($uploadedFile as $file) { + $files[$name][] = self::convertUploadedFile($file); + } } return $files; } + + private static function convertUploadedFile(UploadedFileInterface $uploadedFile) + { + return [ + 'name' => $uploadedFile->getClientFilename(), + 'type' => $uploadedFile->getClientMediaType(), + 'size' => $uploadedFile->getSize(), + 'tmp_name' => $uploadedFile->getStream()->getMetadata('uri'), + 'error' => $uploadedFile->getError(), + ]; + } } diff --git a/tests/RequestBridgeTest.php b/tests/RequestBridgeTest.php index 01ca5a6..2a35f61 100644 --- a/tests/RequestBridgeTest.php +++ b/tests/RequestBridgeTest.php @@ -177,4 +177,57 @@ public function toOAuth2BodyContentsOfRequestPreserved() $this->assertSame('foo', $psr7Request->getBody()->getContents()); $this->assertSame('foo', $oauth2Request->getContent()); } + + /** + * @test + * @covers ::toOAuth2 + * + * @return void + */ + public function toOAuth2WithMultipleFiles() + { + $files = [ + 'multi' => [ + new UploadedFile( + __FILE__, + 100, + UPLOAD_ERR_OK, + 'foo1.txt', + 'text/plain' + ), + new UploadedFile( + __FILE__, + 100, + UPLOAD_ERR_OK, + 'foo2.txt', + 'text/plain' + ), + ], + ]; + + $psr7Request = (new ServerRequest())->withUploadedFiles($files); + $oauth2Request = RequestBridge::toOauth2($psr7Request); + + $this->assertSame( + [ + 'multi' => [ + [ + 'name' => 'foo1.txt', + 'type' => 'text/plain', + 'size' => 100, + 'tmp_name' => __FILE__, + 'error' => UPLOAD_ERR_OK, + ], + [ + 'name' => 'foo2.txt', + 'type' => 'text/plain', + 'size' => 100, + 'tmp_name' => __FILE__, + 'error' => UPLOAD_ERR_OK, + ], + ], + ], + $oauth2Request->files + ); + } }