Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue/19 json oas compat #20

Merged
merged 5 commits into from
Dec 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 22 additions & 4 deletions src/Assertions.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
use Closure;
use Illuminate\Support\Arr;
use PHPUnit\Framework\Assert as PHPUnit;
use Spectator\Exceptions\InvalidPathException;
use Spectator\Exceptions\MissingSpecException;
use Spectator\Exceptions\RequestValidationException;
use Spectator\Exceptions\ResponseValidationException;
use cebe\openapi\exceptions\UnresolvableReferenceException;
Expand All @@ -19,7 +21,12 @@ public function assertValidRequest()
$contents = $this->getContent() ? $contents = (array) $this->json() : [];

PHPUnit::assertFalse(
in_array(Arr::get($contents, 'exception'), [RequestValidationException::class, UnresolvableReferenceException::class]),
in_array(Arr::get($contents, 'exception'), [
InvalidPathException::class,
MissingSpecException::class,
RequestValidationException::class,
UnresolvableReferenceException::class,
]),
$this->decodeExceptionMessage($contents)
);

Expand All @@ -35,7 +42,12 @@ public function assertInvalidRequest()
$contents = (array) $this->json();

PHPUnit::assertTrue(
!in_array(Arr::get($contents, 'exception'), [RequestValidationException::class, UnresolvableReferenceException::class]),
in_array(Arr::get($contents, 'exception'), [
InvalidPathException::class,
MissingSpecException::class,
RequestValidationException::class,
UnresolvableReferenceException::class,
]),
$this->decodeExceptionMessage($contents)
);

Expand All @@ -51,7 +63,10 @@ public function assertValidResponse()
$contents = $this->getContent() ? (array) $this->json() : [];

PHPUnit::assertFalse(
in_array(Arr::get($contents, 'exception'), [ResponseValidationException::class, UnresolvableReferenceException::class]),
in_array(Arr::get($contents, 'exception'), [
ResponseValidationException::class,
UnresolvableReferenceException::class,
]),
$this->decodeExceptionMessage($contents)
);

Expand All @@ -76,7 +91,10 @@ public function assertInvalidResponse()
$contents = (array) $this->json();

PHPUnit::assertTrue(
in_array(Arr::get($contents, 'exception'), [ResponseValidationException::class, UnresolvableReferenceException::class]),
in_array(Arr::get($contents, 'exception'), [
ResponseValidationException::class,
UnresolvableReferenceException::class,
]),
$this->decodeExceptionMessage($contents)
);

Expand Down
10 changes: 7 additions & 3 deletions src/Middleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ class Middleware
{
protected $spectator;

protected $version = '3.0';

public function __construct(RequestFactory $spectator)
{
$this->spectator = $spectator;
Expand All @@ -32,14 +34,14 @@ public function handle(Request $request, Closure $next)

try {
$response = $this->validate($request, $next);
} catch (InvalidPathException $exception) {
return $this->formatResponse($exception, 422);
} catch (RequestValidationException $exception) {
return $this->formatResponse($exception, 400);
} catch (ResponseValidationException $exception) {
return $this->formatResponse($exception, 400);
} catch (InvalidMethodException $exception) {
return $this->formatResponse($exception, 405);
} catch (InvalidPathException $exception) {
return $this->formatResponse($exception, 422);
} catch (MissingSpecException $exception) {
return $this->formatResponse($exception, 500);
} catch (UnresolvableReferenceException $exception) {
Expand Down Expand Up @@ -73,7 +75,7 @@ protected function validate(Request $request, Closure $next)

$response = $next($request);

ResponseValidator::validate($request_path, $response, $operation);
ResponseValidator::validate($request_path, $response, $operation, $this->version);

$this->spectator->reset();

Expand All @@ -88,6 +90,8 @@ protected function operation($request_path, $request_method)

$openapi = $this->spectator->resolve();

$this->version = $openapi->openapi;

foreach ($openapi->paths as $path => $pathItem) {
if ($this->resolvePath($path) === $request_path) {
$methods = array_keys($pathItem->getOperations());
Expand Down
174 changes: 133 additions & 41 deletions src/Validation/ResponseValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,85 +2,155 @@

namespace Spectator\Validation;

use Exception;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use cebe\openapi\spec\Schema;
use Opis\JsonSchema\Validator;
use cebe\openapi\spec\Response;
use cebe\openapi\spec\Operation;
use Opis\JsonSchema\ValidationResult;
use Opis\JsonSchema\Exception\SchemaKeywordException;
use Spectator\Exceptions\ResponseValidationException;

class ResponseValidator
{
/** @var string request uri */
protected $uri;

protected $response;

protected $operation;

public function __construct(string $uri, $response, Operation $operation)
protected $version;

public function __construct(string $uri, $response, Operation $operation, $version = '3.0')
{
$this->uri = $uri;
$this->response = $response;
$this->operation = $operation;
$this->version = $version;
}

public static function validate(string $uri, $response, Operation $operation)
public static function validate(string $uri, $response, Operation $operation, $version = '3.0')
{
$instance = new self($uri, $response, $operation);
$instance = new self($uri, $response, $operation, $version);

$instance->handle();
}

/**
* @throws ResponseValidationException
*/
protected function handle()
{
$contentType = $this->response->headers->get('Content-Type');
$body = $this->response->getContent();
$responses = $this->operation->responses;
$responseObject = $this->response();

if ($responseObject->content) {
$this->parseResponse($responseObject);
}
}

$shortHandler = class_basename($this->operation->operationId) ?: $this->uri;
/**
* @throws ResponseValidationException
*/
protected function parseResponse(Response $response)
{
$contentType = $this->contentType();

// Get matching response object based on status code.
if ($responses[$this->response->getStatusCode()] !== null) {
$responseObject = $responses[$this->response->getStatusCode()];
} elseif ($responses['default'] !== null) {
$responseObject = $responses['default'];
} else {
throw new ResponseValidationException("No response object matching returned status code [{$this->response->getStatusCode()}].");
if (!array_key_exists($contentType, $response->content)) {
throw new ResponseValidationException('Response did not match any specified media type.');
}

if ($responseObject->content) {
if (!array_key_exists($contentType, $responseObject->content)) {
throw new ResponseValidationException('Response did not match any specified media type.');
}
$schema = $response->content[$contentType]->schema;

$this->validateResponse(
$schema, $this->body($contentType, $schema->type)
);
}

$schema = $responseObject->content[$contentType]->schema;
/**
* @param $body
*
* @throws ResponseValidationException
*/
protected function validateResponse(Schema $schema, $body)
{
$result = null;
$validator = $this->validator();
$shortHandler = $this->shortHandler();

try {
$result = $validator->dataValidation($body, $this->prepareData($schema->getSerializableData()), -1);
} catch (SchemaKeywordException $exception) {
throw ResponseValidationException::withError("{$shortHandler} has invalid schema: [ {$exception->getMessage()} ]");
} catch (Exception $exception) {
throw ResponseValidationException::withError($exception->getMessage());
}

if ($schema->type === 'object' || $schema->type === 'array') {
if (in_array($contentType, ['application/json', 'application/vnd.api+json'])) {
$body = json_decode($body);
} else {
throw new ResponseValidationException("Unable to map [{$contentType}] to schema type [object].");
}
}
if ($result instanceof ValidationResult && $result->isValid() === false) {
$error = $result->getFirstError();
$args = json_encode($error->keywordArgs());
$dataPointer = implode('.', $error->dataPointer());

$validator = $this->validator();
$result = null;
throw ResponseValidationException::withError("{$shortHandler} json response field {$dataPointer} does not match the spec: [ {$error->keyword()}: {$args} ]", $result->getErrors());
}
}

try {
$result = $validator->dataValidation($body, $schema->getSerializableData(), -1);
} catch (SchemaKeywordException $exception) {
throw ResponseValidationException::withError("{$shortHandler} has invalid schema: [ {$exception->getMessage()} ]");
} catch (\Exception $exception) {
throw ResponseValidationException::withError($exception->getMessage());
}
/**
* @throws ResponseValidationException
*/
protected function response(): Response
{
$responses = $this->operation->responses;

if (optional($result)->isValid() === false) {
$error = $result->getFirstError();
$args = json_encode($error->keywordArgs());
$dataPointer = implode('.', $error->dataPointer());
if ($responses[$this->response->getStatusCode()] !== null) {
return $responses[$this->response->getStatusCode()];
}

throw ResponseValidationException::withError("{$shortHandler} json response field {$dataPointer} does not match the spec: [ {$error->keyword()}: {$args} ]", $result->getErrors());
if ($responses['default'] !== null) {
return $responses['default'];
}

throw new ResponseValidationException("No response object matching returned status code [{$this->response->getStatusCode()}].");
}

/**
* @return string
*/
protected function contentType()
{
return $this->response->headers->get('Content-Type');
}

/**
* @param $contentType
* @param $schemaType
*
* @return mixed
*
* @throws ResponseValidationException
*/
protected function body($contentType, $schemaType)
{
$body = $this->response->getContent();

if (in_array($schemaType, ['object', 'array'], true)) {
if (in_array($contentType, ['application/json', 'application/vnd.api+json'])) {
return json_decode($body);
} else {
throw new ResponseValidationException("Unable to map [{$contentType}] to schema type [object].");
}
}

return $body;
}

/**
* @return string
*/
protected function shortHandler()
{
return class_basename($this->operation->operationId) ?: $this->uri;
}

protected function validator(): Validator
Expand All @@ -89,4 +159,26 @@ protected function validator(): Validator

return $validator;
}

protected function prepareData($data)
{
if (!isset($data->properties)) {
return $data;
}

$clone = clone $data;

$v30 = Str::startsWith($this->version, '3.0');

foreach ($clone->properties as $key => $attributes) {
if ($v30 && isset($attributes->nullable)) {
$type = Arr::wrap($attributes->type);
$type[] = 'null';
$attributes->type = array_unique($type);
unset($attributes->nullable);
}
}

return $clone;
}
}
17 changes: 17 additions & 0 deletions tests/AssertionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,23 @@ public function setUp(): void
Spectator::using('Test.v1.json');
}

public function testAssertsInvalidPath()
{
Route::get('/invalid', function () {
return [
[
'id' => 1,
'name' => 'Jim',
'email' => '[email protected]',
],
];
})->middleware(Middleware::class);

$this->getJson('/invalid')
->assertInvalidRequest()
->assertValidationMessage('Path [GET /invalid] not found in spec.');
}

public function testExceptionPointsToMixinMethod()
{
$this->expectException(\ErrorException::class);
Expand Down