Skip to content

Commit

Permalink
Enable formatted JSON requests to be validated (#15)
Browse files Browse the repository at this point in the history
Allows for formats like JSON-API (`application/vnd.api+json`) to be used
  • Loading branch information
shadowhand authored and hkarlstrom committed Feb 26, 2019
1 parent c46b16a commit 2948149
Showing 1 changed file with 10 additions and 11 deletions.
21 changes: 10 additions & 11 deletions src/OpenApiValidation.php
Original file line number Diff line number Diff line change
Expand Up @@ -243,17 +243,10 @@ public function validateRequest(ServerRequestInterface &$request, string $path,
if ($requestBody && $requestMediaType = $requestBody->getContent($mediaType)) {
if (empty($requestBodyData) && $requestBody->required) {
$errors[] = ['name' => 'requestBody', 'code' => 'error_required'];
} else {
switch ($mediaType) {
case 'application/json':
if (!empty($requestBodyData)) {
$errors = array_merge($errors, $this->validateObject($requestMediaType->schema, $requestBodyData));
}
break;
case 'multipart/form-data':
$errors = array_merge($errors, $this->validateFormData($requestMediaType->schema, $requestMediaType->encoding, $request));
break;
}
} elseif ($requestBodyData && $this->isJsonMediaType($mediaType)) {
$errors = array_merge($errors, $this->validateObject($requestMediaType->schema, $requestBodyData));
} elseif ('multipart/form-data' === $mediaType) {
$errors = array_merge($errors, $this->validateFormData($requestMediaType->schema, $requestMediaType->encoding, $request));
}
}
return $errors;
Expand Down Expand Up @@ -523,4 +516,10 @@ private function getMediaType(MessageInterface $message) : ?string
$contentTypeParts = preg_split('/\s*[;,]\s*/', $header[0]);
return mb_strtolower($contentTypeParts[0]);
}

private function isJsonMediaType(string $type) : bool
{
// Allow JSON and JSON-formatted (eg: JSON-API) requests to be validated.
return 'application/json' === $type || false !== mb_strpos($type, '+json');
}
}

0 comments on commit 2948149

Please sign in to comment.