forked from cebe/php-openapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphp-openapi
More file actions
executable file
·357 lines (319 loc) · 13.3 KB
/
php-openapi
File metadata and controls
executable file
·357 lines (319 loc) · 13.3 KB
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
#!/usr/bin/env php
<?php
/**
* PHP OpenAPI validation tool
*
* @copyright Copyright (c) 2018 Carsten Brandt <mail@cebe.cc> and contributors
* @license https://github.com/cebe/php-openapi/blob/master/LICENSE
*/
use cebe\openapi\ReferenceContext;
$composerAutoload = [
__DIR__ . '/../vendor/autoload.php', // standalone with "composer install" run
__DIR__ . '/../../../autoload.php', // script is installed as a composer binary
];
foreach ($composerAutoload as $autoload) {
if (file_exists($autoload)) {
require($autoload);
break;
}
}
// Send all errors to stderr
ini_set('display_errors', 'stderr');
// open streams if not in CLI sapi
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
defined('STDERR') or define('STDERR', fopen('php://stderr', 'w'));
$command = null;
$inputFile = null;
$inputFormat = null;
$outputFile = null;
$outputFormat = null;
$silentMode = false;
foreach($argv as $k => $arg) {
if ($k == 0) {
continue;
}
if ($arg[0] == '-' || $arg === 'help') {
$arg = explode('=', $arg);
switch($arg[0]) {
case '--read-yaml':
if ($inputFormat === null) {
$inputFormat = 'yaml';
} else {
error("Conflicting arguments: only one of --read-json or --read-yaml is allowed!", "usage");
}
break;
case '--read-json':
if ($inputFormat === null) {
$inputFormat = 'json';
} else {
error("Conflicting arguments: only one of --read-json or --read-yaml is allowed!", "usage");
}
break;
case '--write-yaml':
if ($outputFormat === null) {
$outputFormat = 'yaml';
} else {
error("Conflicting arguments: only one of --write-json or --write-yaml is allowed!", "usage");
}
break;
case '--write-json':
if ($outputFormat === null) {
$outputFormat = 'json';
} else {
error("Conflicting arguments: only one of --write-json or --write-yaml is allowed!", "usage");
}
break;
case '-s':
case '--silent':
$silentMode = true;
break;
case '-h':
case '--help':
case 'help':
print_formatted(
"\BPHP OpenAPI 3 tool\C\n"
. "\B------------------\C\n"
. "by Carsten Brandt <mail@cebe.cc>\n\n",
STDERR
);
usage();
break;
default:
error("Unknown argument " . $arg[0], "usage");
}
} else {
if ($command === null) {
$command = $arg;
} elseif ($inputFile === null) {
$inputFile = $arg;
} elseif ($outputFile === null) {
if ($command !== 'convert') {
error("Too many arguments: " . $arg, "usage");
}
$outputFile = $arg;
} else {
error("Too many arguments: " . $arg, "usage");
}
}
}
switch ($command) {
case 'validate':
$errors = [];
$openApi = read_input($inputFile, $inputFormat);
$referenceContext = new ReferenceContext($openApi, $inputFile ? realpath($inputFile) : '');
$referenceContext->throwException = false;
$openApi->resolveReferences($referenceContext);
$openApi->setDocumentContext($openApi, new \cebe\openapi\json\JsonPointer(''));
// Validate
$openApi->validate();
$errors = array_merge($errors, $openApi->getErrors());
$validator = new JsonSchema\Validator;
$openApiData = $openApi->getSerializableData();
$validator->validate($openApiData, (object)['$ref' => 'file://' . dirname(__DIR__) . '/schemas/openapi-v3.0.json']);
if ($validator->isValid() && empty($errors)) {
if(!$silentMode) {
print_formatted("The supplied API Description \B\Gvalidates\C against the OpenAPI v3.0 schema.\n", STDERR);
}
exit(0);
}
if (!empty($errors)) {
if ($inputFile === null) {
print_formatted("\BErrors found while reading the API description from STDIN:\C\n", STDERR);
} else {
print_formatted("\BErrors found while reading the API description from {$inputFile}:\C\n", STDERR);
}
foreach ($errors as $error) {
if (($openPos = strpos($error, '[')) !== false && ($closePos = strpos($error, ']')) !== false && $openPos < $closePos) {
$error = escape_formatted(substr($error, 0, $openPos + 1)) . '\Y'
. escape_formatted(substr($error, $openPos + 1, $closePos - $openPos - 1)) . '\C'
. escape_formatted(substr($error, $closePos));
} else {
$error = escape_formatted($error);
}
print_formatted("- " . $error . "\n", STDERR);
}
}
if (!$validator->isValid()) {
print_formatted("\BOpenAPI v3.0 schema violations:\C\n", STDERR);
$errors = $validator->getErrors();
foreach ($errors as $error) {
// hide some errors triggered by other errors further down the path
if (strpos($error['message'], 'The property $ref is required') !== false && substr($error['property'], -4, 4) === '$ref') {
$hasErrorInPath = false;
foreach ($errors as $suberror) {
if ($suberror['property'] !== $error['property'] && strpos($suberror['property'], substr($error['property'], 0, -4)) === 0) {
$hasErrorInPath = true;
break;
}
}
if ($hasErrorInPath) {
continue;
}
}
if (strpos($error['message'], 'Failed to match exactly one schema') !== false) {
$hasErrorInPath = false;
foreach ($errors as $suberror) {
if (strpos($suberror['property'], $error['property'] . '.') === 0) {
$hasErrorInPath = true;
break;
}
}
if ($hasErrorInPath) {
continue;
}
}
print_formatted(sprintf("- [\Y%s\C] %s\n", escape_formatted($error['property']), escape_formatted($error['message'])), STDERR);
}
}
exit(2);
break;
case 'convert':
$openApi = read_input($inputFile, $inputFormat);
try {
$openApi->resolveReferences();
} catch (\cebe\openapi\exceptions\UnresolvableReferenceException $e) {
error("[\e[33m{$e->context}\e[0m] " . $e->getMessage());
}
if ($outputFile === null) {
if ($outputFormat === null) {
error("No output fromat specified, please specify --write-json or --write-yaml.", "usage");
} elseif ($outputFormat === 'json') {
fwrite(STDOUT, \cebe\openapi\Writer::writeToJson($openApi));
} else {
fwrite(STDOUT, \cebe\openapi\Writer::writeToYaml($openApi));
}
fclose(STDOUT);
exit(0);
}
if ($outputFormat === null) {
if (strtolower(substr($outputFile, -5, 5)) === '.json') {
$outputFormat = 'json';
} elseif (strtolower(substr($outputFile, -5, 5)) === '.yaml') {
$outputFormat = 'yaml';
} elseif (strtolower(substr($outputFile, -4, 4)) === '.yml') {
$outputFormat = 'yaml';
} else {
error("Failed to detect output format from file name, please specify --write-json or --write-yaml.", "usage");
}
}
if ($outputFormat === 'json') {
\cebe\openapi\Writer::writeToJsonFile($openApi, $outputFile);
} else {
\cebe\openapi\Writer::writeToYamlFile($openApi, $outputFile);
}
exit(0);
break;
case null:
error("No command specified.", "usage");
break;
default:
error("Unknown command " . $command, "usage");
}
// functions
function read_input($inputFile, $inputFormat)
{
try {
if ($inputFile === null) {
$fileContent = file_get_contents("php://stdin");
if ($inputFormat === null) {
$inputFormat = (ltrim($fileContent) === '{' && rtrim($fileContent) === '}') ? 'json' : 'yaml';
}
if ($inputFormat === 'json') {
$openApi = \cebe\openapi\Reader::readFromJson($fileContent);
} else {
$openApi = \cebe\openapi\Reader::readFromYaml($fileContent);
}
} else {
if (!file_exists($inputFile)) {
error("File does not exist: " . $inputFile);
}
if ($inputFormat === null) {
if (strtolower(substr($inputFile, -5, 5)) === '.json') {
$inputFormat = 'json';
} elseif (strtolower(substr($inputFile, -5, 5)) === '.yaml') {
$inputFormat = 'yaml';
} elseif (strtolower(substr($inputFile, -4, 4)) === '.yml') {
$inputFormat = 'yaml';
} else {
error("Failed to detect input format from file name, please specify --read-json or --read-yaml.", "usage");
}
}
if ($inputFormat === 'json') {
$openApi = \cebe\openapi\Reader::readFromJsonFile(realpath($inputFile), \cebe\openapi\spec\OpenApi::class, false);
} else {
$openApi = \cebe\openapi\Reader::readFromYamlFile(realpath($inputFile), \cebe\openapi\spec\OpenApi::class, false);
}
}
$openApi->setDocumentContext($openApi, new \cebe\openapi\json\JsonPointer(''));
} catch (Symfony\Component\Yaml\Exception\ParseException $e) {
error($e->getMessage());
exit(1);
} catch (cebe\openapi\exceptions\IOException $e) {
error($e->getMessage());
exit(1);
}
return $openApi;
}
/**
* Display usage information
*/
function usage() {
global $argv;
$cmd = basename($argv[0]);
print_formatted(<<<EOF
Usage:
$cmd \B<command>\C [\Y<options>\C] [\Ginput.yml\C|\Ginput.json\C] [\Goutput.yml\C|\Goutput.json\C]
The following commands are available:
\Bvalidate\C Validate the API Description in the specified \Ginput file\C against the OpenAPI v3.0 schema.
Note: the validation is performed in two steps. The results is composed of
(1) structural errors found while reading the API Description file, and
(2) violations of the OpenAPI v3.0 schema.
If no input file is specified input will be read from STDIN.
The tool will try to auto-detect the content type of the input, but may fail
to do so, you may specify \Y--read-yaml\C or \Y--read-json\C to force the file type.
Exits with code 2 on validation errors, 1 on other errors and 0 on success.
\Bconvert\C Convert a JSON or YAML input file to JSON or YAML output file.
References are being resolved so the output will be a single API Description file.
If no input file is specified input will be read from STDIN.
If no output file is specified output will be written to STDOUT.
The tool will try to auto-detect the content type of the input and output file, but may fail
to do so, you may specify \Y--read-yaml\C or \Y--read-json\C to force the input file type.
and \Y--write-yaml\C or \Y--write-json\C to force the output file type.
\Bhelp\C Shows this usage information.
Options:
\Y--read-json\C force reading input as JSON. Auto-detect if not specified.
\Y--read-yaml\C force reading input as YAML. Auto-detect if not specified.
\Y--write-json\C force writing output as JSON. Auto-detect if not specified.
\Y--write-yaml\C force writing output as YAML. Auto-detect if not specified.
\Y-s, --silent\C silent mode. Will hide all success/information messages and only print errors.
EOF
, STDERR
);
exit(1);
}
/**
* Send custom error message to stderr
* @param $message string
* @param $callback mixed called before script exit
* @return void
*/
function error($message, $callback = null) {
print_formatted("\B\RError\C: " . escape_formatted($message) . "\n", STDERR);
if (is_callable($callback)) {
call_user_func($callback);
}
exit(1);
}
function print_formatted($string, $stream) {
fwrite($stream, strtr($string, [
'\\Y' => "\033[33m", // yellow
'\\G' => "\033[32m", // green
'\\R' => "\033[31m", // red
'\\B' => "\033[1m", // bold
'\\C' => "\033[0m", // clear
'\\\\' => '\\',
]));
}
function escape_formatted($string) {
return strtr($string, ['\\' => '\\\\']);
}