Skip to content

Commit c80b538

Browse files
committed
Initial commit
0 parents  commit c80b538

24 files changed

+4203
-0
lines changed

.gitignore

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
composer.phar
2+
.DS_Store
3+
/vendor/
4+
5+
# Commit your application's lock file https://getcomposer.org/doc/01-basic-usage.md#commit-your-composer-lock-file-to-version-control
6+
# You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file
7+
# composer.lock

.php_cs

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
<?php
2+
3+
$finder = PhpCsFixer\Finder::create();
4+
5+
return PhpCsFixer\Config::create()
6+
->setRules([
7+
'@PSR2' => true,
8+
'@Symfony' => true,
9+
'align_multiline_comment' => true,
10+
'array_syntax' => ['syntax' => 'short'],
11+
'binary_operator_spaces' => [
12+
'default' => 'align_single_space_minimal',
13+
'operators' => [
14+
'=' =>'align_single_space_minimal',
15+
'=>' =>'align_single_space_minimal'
16+
]
17+
],
18+
'blank_line_after_namespace' => true,
19+
'blank_line_before_statement' => false,
20+
'braces' => true,
21+
'class_definition' => true,
22+
'class_keyword_remove' => true,
23+
'combine_consecutive_issets' => true,
24+
'combine_consecutive_unsets' => true,
25+
'concat_space' => true,
26+
'dir_constant' => true,
27+
'elseif' => true,
28+
'encoding' => true,
29+
'full_opening_tag' => true,
30+
'function_declaration' => true,
31+
'function_typehint_space' => true,
32+
'is_null' => true,
33+
'line_ending' => true,
34+
'lowercase_constants' => true,
35+
'lowercase_keywords' => true,
36+
'mb_str_functions' => true,
37+
'method_argument_space' => true,
38+
'method_separation' => true,
39+
'native_function_casing' => true,
40+
'no_alias_functions' => true,
41+
'no_blank_lines_after_class_opening' => true,
42+
'no_blank_lines_after_phpdoc' => true,
43+
'no_closing_tag' => true,
44+
'no_empty_comment' => true,
45+
'no_empty_statement' => true,
46+
'no_extra_consecutive_blank_lines' => true,
47+
'no_leading_namespace_whitespace' => true,
48+
'no_mixed_echo_print' => true,
49+
'no_multiline_whitespace_around_double_arrow' => true,
50+
'no_multiline_whitespace_before_semicolons' => true,
51+
'no_php4_constructor' => true,
52+
'no_singleline_whitespace_before_semicolons' => true,
53+
'no_superfluous_elseif' => true,
54+
'no_trailing_whitespace' => true,
55+
'no_trailing_whitespace_in_comment' => true,
56+
'no_unneeded_curly_braces' => true,
57+
'no_unused_imports' => true,
58+
'no_useless_else' => true,
59+
'no_useless_return' => true,
60+
'no_whitespace_before_comma_in_array' => true,
61+
'no_whitespace_in_blank_line' => true,
62+
'non_printable_character' => true,
63+
'object_operator_without_whitespace' => true,
64+
'ordered_class_elements' => true,
65+
'ordered_imports' => true,
66+
'phpdoc_align' => true,
67+
'phpdoc_order' => true,
68+
'phpdoc_scalar' => true,
69+
'protected_to_private' => true,
70+
'return_type_declaration' => ['space_before' => 'one'],
71+
'short_scalar_cast' => true,
72+
'single_blank_line_at_eof' => true,
73+
'single_blank_line_before_namespace' => true,
74+
'single_line_after_imports' => true,
75+
'single_quote' => true,
76+
'trim_array_spaces' => true,
77+
'whitespace_after_comma_in_array' => true,
78+
])
79+
->setFinder($finder);

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2018 Henrik Karlström
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
# OpenAPI Validation Middleware
2+
3+
PSR-7 and PSR-15 OpenAPI Validation Middleware
4+
5+
The middleware parses an OpenAPI definition document (openapi.json) and validates:
6+
* Request parameters (path, query)
7+
* Request body
8+
* Response body
9+
10+
The middleware can be used with any framework using [PSR-7](https://www.php-fig.org/psr/psr-7/) and [PSR-15](https://www.php-fig.org/psr/psr-15/) style middlewares.
11+
12+
All testing has been done using [Slim Framework](https://github.com/slimphp/Slim). The tests are done with a openapi.json file that is valid according to [Swagger/OpenAPI CLI](https://www.npmjs.com/package/swagger-cli)
13+
14+
15+
## Installation
16+
17+
It's recommended that you use [Composer](https://getcomposer.org/download) to install.
18+
```shell
19+
composer require hkarlstrom/openapi-reader
20+
```
21+
22+
23+
## Usage
24+
25+
Basic usage with Slim Framework.
26+
```php
27+
$app = new Slim\App;
28+
$app->add(new HKarlstrom\Middleware\OpenApiValidation('/path/to/openapi.json'));
29+
```
30+
31+
Basic usage with Zend Expressive.
32+
```php
33+
$app = $container->get(\Zend\Expressive\Application::class);
34+
$app->pipe(new HKarlstrom\Middleware\OpenApiValidation('/path/to/openapi.json'));
35+
```
36+
37+
### Options
38+
39+
The options array is passed to the middleware when it's constructed.
40+
```php
41+
$app = new Slim\App;
42+
$app->add(new HKarlstrom\Middleware\OpenApiValidation('/path/to/openapi.json'),[
43+
'additionalParameters' => true,
44+
'stripResponse' => true
45+
]);
46+
```
47+
48+
| type | format | default | description |
49+
| --------------------- | ----------| ------- | --- |
50+
| additionalParameters | bool | false | Allow additional parameters in query |
51+
| beforeHandler | callable | null | Instructions [below](README.md#beforehandler) |
52+
| errorHandler | callable | null | Instructions [below](README.md#errorhandler) |
53+
| exampleResponse | bool | false | Return example response from openapi.json if route implementation is empty |
54+
| missingFormatException| bool | true | Throw an exception if a format validator is missing |
55+
| pathNotFoundException | bool | true | Throw an exception if the path is not found in openapi.json |
56+
| setDefaultParameters | bool | false | Set the default parameter values for missing parameters and alter the request object |
57+
| stripResponse | bool | false | Strip additional parameters from response to prevent response validation error |
58+
| validateError | bool | false | Should the error response be validated |
59+
| validateRequest | bool | true | Should the request be validated |
60+
| validateResponse | bool | true | Should the response be validated |
61+
62+
63+
#### beforeHandler
64+
If defined, the function is called when the request validation fails before the next incoming middleware is called. You can use this to alter the request before passing it to the next incoming middleware in the stack. If it returns anything else than \Psr\Http\Message\ServerRequestInterface an exception will be thrown. The `array $errors` is an array containing all the validation errors.
65+
```php
66+
$options = [
67+
'beforeHandler' => function (\Psr\Http\Message\ServerRequestInterface $request, array $errors) : \Psr\Http\Message\ServerRequestInterface {
68+
// Alter request
69+
return $request
70+
}
71+
];
72+
```
73+
74+
#### errorHandler
75+
If defined, the function is called instead of the default error handler. If it returns anything else than Psr\Http\Message\ResponseInterface it will fallback to the default error handler.
76+
```php
77+
$options = [
78+
'errorHandler' => function (int $code, string $message, array $errors) : \Psr\Http\Message\ResponseInterface {
79+
// Alter request
80+
return $request
81+
}
82+
];
83+
```
84+
85+
## Formats
86+
87+
There are two ways to validate formats not defined in the [OAS](https://swagger.io/specification/#dataTypes) specification. You can implement a custom format validator and add it to the middleware, or use the build in support for the [Respect Validation](http://respect.github.io/Validation/) libray.
88+
89+
#### Custom validator
90+
```php
91+
class MyOwnFormat extends Opis\JsonSchema\IFormat {
92+
public function validate($data) : bool
93+
{
94+
// Validate data
95+
// $isValid = ...
96+
return $isValid;
97+
}
98+
}
99+
100+
$mw = new HKarlstrom\Middleware\OpenApiValidation('/path/to/openapi.json');
101+
$mw->addFormat('string','my-own-format',new MyOwnFormat());
102+
$app->add($mw);
103+
```
104+
105+
#### Respect Validation
106+
107+
You can use [all the validators](http://respect.github.io/Validation/docs/validators.html) just by setting the `format` property in your openapi.json file.
108+
```json
109+
"schema":{
110+
"type" : "string",
111+
"format": "country-code"
112+
}
113+
```
114+
The `country-code` value will resolve to the `v::countryCode()` validator.
115+
116+
You can also pass arguments to the validator defined in the format attribute:
117+
118+
```json
119+
"schema": {
120+
"type": "string",
121+
"format":"ends-with('@gmail.com')"
122+
}
123+
```
124+
or
125+
```json
126+
"schema": {
127+
"type": "integer",
128+
"format":"between(10, 20)"
129+
}
130+
```
131+
132+
## License
133+
134+
The OpenAPI Reader is licensed under the MIT license. See [License File](LICENSE) for more information.

composer.json

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
{
2+
"name": "hkarlstrom/openapi-validation-middleware",
3+
"type": "library",
4+
"description": "PSR-7 and PSR-15 OpenAPI Validation Middleware",
5+
"keywords": ["openapi", "validation", "middleware", "psr-7", "psr-15"],
6+
"license": "MIT",
7+
"authors": [
8+
{
9+
"name": "Henrik Karlstrom",
10+
"email": "[email protected]"
11+
}
12+
],
13+
"require": {
14+
"php": "^7.1",
15+
"hkarlstrom/openapi-reader": "^0.1.0",
16+
"opis/json-schema": "^1.0",
17+
"psr/http-message": "^1.0",
18+
"psr/http-server-middleware": "^1.0",
19+
"respect/validation": "^1.1",
20+
"tuupola/callable-handler": "^0.4.0",
21+
"tuupola/http-factory": "^0.4.2"
22+
},
23+
"require-dev": {
24+
"phpunit/phpunit": "^7.3",
25+
"slim/slim": "^3.11"
26+
},
27+
"autoload": {
28+
"psr-4": {
29+
"HKarlstrom\\Middleware\\": "src"
30+
}
31+
},
32+
"autoload-dev": {
33+
"psr-4": {
34+
"HKarlstrom\\Middleware\\OpenApiValidation\\": "tests"
35+
}
36+
},
37+
"config": {
38+
"sort-packages": true
39+
},
40+
"scripts": {
41+
"test": "./vendor/bin/phpunit"
42+
}
43+
}

0 commit comments

Comments
 (0)