Skip to content

Commit 2948149

Browse files
shadowhandhkarlstrom
authored andcommitted
Enable formatted JSON requests to be validated (#15)
Allows for formats like JSON-API (`application/vnd.api+json`) to be used
1 parent c46b16a commit 2948149

File tree

1 file changed

+10
-11
lines changed

1 file changed

+10
-11
lines changed

src/OpenApiValidation.php

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -243,17 +243,10 @@ public function validateRequest(ServerRequestInterface &$request, string $path,
243243
if ($requestBody && $requestMediaType = $requestBody->getContent($mediaType)) {
244244
if (empty($requestBodyData) && $requestBody->required) {
245245
$errors[] = ['name' => 'requestBody', 'code' => 'error_required'];
246-
} else {
247-
switch ($mediaType) {
248-
case 'application/json':
249-
if (!empty($requestBodyData)) {
250-
$errors = array_merge($errors, $this->validateObject($requestMediaType->schema, $requestBodyData));
251-
}
252-
break;
253-
case 'multipart/form-data':
254-
$errors = array_merge($errors, $this->validateFormData($requestMediaType->schema, $requestMediaType->encoding, $request));
255-
break;
256-
}
246+
} elseif ($requestBodyData && $this->isJsonMediaType($mediaType)) {
247+
$errors = array_merge($errors, $this->validateObject($requestMediaType->schema, $requestBodyData));
248+
} elseif ('multipart/form-data' === $mediaType) {
249+
$errors = array_merge($errors, $this->validateFormData($requestMediaType->schema, $requestMediaType->encoding, $request));
257250
}
258251
}
259252
return $errors;
@@ -523,4 +516,10 @@ private function getMediaType(MessageInterface $message) : ?string
523516
$contentTypeParts = preg_split('/\s*[;,]\s*/', $header[0]);
524517
return mb_strtolower($contentTypeParts[0]);
525518
}
519+
520+
private function isJsonMediaType(string $type) : bool
521+
{
522+
// Allow JSON and JSON-formatted (eg: JSON-API) requests to be validated.
523+
return 'application/json' === $type || false !== mb_strpos($type, '+json');
524+
}
526525
}

0 commit comments

Comments
 (0)