-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
ResponseValidator.php
184 lines (149 loc) · 5 KB
/
ResponseValidator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
<?php
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
{
protected $uri;
protected $response;
protected $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, $version = '3.0')
{
$instance = new self($uri, $response, $operation, $version);
$instance->handle();
}
/**
* @throws ResponseValidationException
*/
protected function handle()
{
$responseObject = $this->response();
if ($responseObject->content) {
$this->parseResponse($responseObject);
}
}
/**
* @throws ResponseValidationException
*/
protected function parseResponse(Response $response)
{
$contentType = $this->contentType();
if (!array_key_exists($contentType, $response->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)
);
}
/**
* @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 ($result instanceof ValidationResult && $result->isValid() === false) {
$error = $result->getFirstError();
$args = json_encode($error->keywordArgs());
$dataPointer = implode('.', $error->dataPointer());
throw ResponseValidationException::withError("{$shortHandler} json response field {$dataPointer} does not match the spec: [ {$error->keyword()}: {$args} ]", $result->getErrors());
}
}
/**
* @throws ResponseValidationException
*/
protected function response(): Response
{
$responses = $this->operation->responses;
if ($responses[$this->response->getStatusCode()] !== null) {
return $responses[$this->response->getStatusCode()];
}
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
{
$validator = new 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;
}
}