Skip to content

Commit

Permalink
Merge pull request #13 from justlevine/fix/throw-on-unset-file
Browse files Browse the repository at this point in the history
fix: throw RequestError if file is missing from location
  • Loading branch information
dre1080 authored Jul 15, 2023
2 parents cd8b98d + ff40c36 commit 7dcb63a
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/Request/BodyParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public static function init()
* Based on the GraphQL multipart request specification.
*
* @see https://github.com/jaydenseric/graphql-multipart-request-spec
* @see https://github.com/Ecodev/graphql-upload/blob/73a63038455e5fb5aa6c3f0e41a06208c45e8539/src/UploadMiddleware.php#L27
*
* @param array $bodyParams The parsed body parameters.
* @param array $requestContext The GraphQL request context.
Expand Down Expand Up @@ -64,6 +65,17 @@ public static function processRequest(array $bodyParams, array $requestContext)
$items = &$items[$key];
}

// Throw an error if the file wasnt found in the location specified in the map
if (! array_key_exists($fileKey, $_FILES)) {
throw new RequestError(
sprintf(
// translators: %s is the location of the file
__('The uploaded file was not found in the specified location `%s`', 'wp-graphql-upload'),
$location
)
);
}

$items = $_FILES[$fileKey];
}
}
Expand Down
38 changes: 38 additions & 0 deletions tests/BodyParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,44 @@ public function testEmptyRequestShouldThrows(): void
BodyParser::processRequest([], ['method' => 'POST']);
}

public function testMissingFileShouldThrows(): void
{
$query = '{my query}';
$variables = [
'test' => 1,
'test2' => 2,
'uploads' => [
0 => null,
1 => null,
],
];
$map = [
1 => ['variables.uploads.0'],
2 => ['variables.uploads.1'],
];

$file1 = ['name' => 'image.jpg', 'type' => 'image/jpeg', 'size' => 1455000, 'tmp_name' => '/tmp/random'];
$_FILES = [
1 => $file1,
];

$params = [
'operations' => json_encode([
'query' => $query,
'variables' => $variables,
'operation_name' => 'testUpload',
]),
'map' => json_encode($map),
];

$_SERVER['CONTENT_TYPE'] = 'multipart/form-data';

$this->expectException(RequestError::class);
$this->expectExceptionMessage('The uploaded file was not found in the specified location `variables.uploads.1`');

BodyParser::processRequest($params, ['method' => 'POST']);
}

public function testOtherContentTypeShouldNotBeTouched(): void
{
$_SERVER['CONTENT_TYPE'] = 'application/json';
Expand Down

0 comments on commit 7dcb63a

Please sign in to comment.