Skip to content

Commit 73a6303

Browse files
committed
Throw if file was declared but not uploaded
Fixes #26
1 parent 6859a9e commit 73a6303

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/UploadMiddleware.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ private function parseUploadedFiles(ServerRequestInterface $request): ServerRequ
4747
$map = $this->decodeArray($bodyParams, 'map');
4848
$result = $this->decodeArray($bodyParams, 'operations');
4949

50+
$uploadedFiles = $request->getUploadedFiles();
5051
foreach ($map as $fileKey => $locations) {
5152
foreach ($locations as $location) {
5253
$items = &$result;
@@ -57,7 +58,13 @@ private function parseUploadedFiles(ServerRequestInterface $request): ServerRequ
5758
$items = &$items[$key];
5859
}
5960

60-
$items = $request->getUploadedFiles()[$fileKey];
61+
if (!array_key_exists($fileKey, $uploadedFiles)) {
62+
throw new RequestError(
63+
"GraphQL query declared an upload in `$location`, but no corresponding file were actually uploaded"
64+
);
65+
}
66+
67+
$items = $uploadedFiles[$fileKey];
6168
}
6269
}
6370

tests/UploadMiddlewareTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,32 @@ public function testRequestWithMapThatIsNotValidJsonShouldThrows(): void
201201
$this->middleware->processRequest($request);
202202
}
203203

204+
public function testMissingUploadedFileShouldThrow(): void
205+
{
206+
$query = '{my query}';
207+
$variables = [
208+
'uploads' => [
209+
0 => null,
210+
1 => null,
211+
],
212+
];
213+
$map = [
214+
1 => ['variables.uploads.0'],
215+
2 => ['variables.uploads.1'],
216+
];
217+
218+
$file1 = new PsrUploadedFileStub('image.jpg', 'image/jpeg');
219+
$files = [
220+
1 => $file1,
221+
];
222+
223+
$request = $this->createRequest($query, $variables, $map, $files, 'op');
224+
225+
$this->expectException(RequestError::class);
226+
$this->expectExceptionMessage('GraphQL query declared an upload in `variables.uploads.1`, but no corresponding file were actually uploaded');
227+
$this->middleware->processRequest($request);
228+
}
229+
204230
public function testCanUploadFileWithStandardServer(): void
205231
{
206232
$query = 'mutation TestUpload($text: String, $file: Upload) {

0 commit comments

Comments
 (0)