Content validation for PSR-15 middleware.
Based on opis/json-schema
.
Install via composer.
composer require zfegg/content-validation
// config.php
return [
Opis\JsonSchema\Validator::class => [
'resolvers' => [
'protocolDir' => [
// foo-schema://host/foo.create.json => schema/dir/foo.create.json
['foo-schema', 'host', 'schema/dir'],
],
'protocol' => [
],
'prefix' => [
['prefix1', 'path/to/dir'],
['prefix2', 'path/to/dir'],
],
'file' => [
['SchemaFoo', 'path/to/file'],
['SchemaBar', 'path/to/file2'],
],
'raw' => [
['{"type":"object", ...}', 'schema id 1'],
['{"type":"object", ...}', 'schema id 2'],
]
],
'filters' => [
'foo-filter' => ['filter' => 'FilterFilterName', 'types' => ['integer']],
],
'filtersNS' => [
'foo-ns' => 'FilterResolverName',
],
]
]
Add ConfigProvider
in 'config.php'.
$aggregator = new ConfigAggregator(
[
// ...
\Zfegg\ContentValidation\ConfigProvider::class,
]
);
return $aggregator->getMergedConfig();
$app->post(
'/api/users',
[
\Zfegg\ContentValidation\ContentValidationMiddleware::class,
function (\Psr\Http\Message\ServerRequestInterface $request) {
$data = $request->getParsedBody(); // Get valid data.
}
], 'api.users.create')
->setOptions(['schema' => 'path-to-json-schema.json'])
//->setOptions([
// // or set json-schema object.
// 'schema' => (object) [
// 'type' => 'object',
// 'properties' => (object) [
// 'age' => (object) [
// 'type' => 'integer'
// ]
// ],
// 'required' => ['age']
// ]
// ])
;
Invalid request will response status 422.
curl "http://host/api/users" -d 'username=foo'
HTTP/1.1 422
{
"status": 422,
"detail": "Failed Validation",
"validation_messages": {
"age": [
"The required properties (age) are missing"
]
}
}
$app->post(
'/api/users',
function (\Psr\Http\Message\ServerRequestInterface $request) {
$data = $request->getParsedBody(); // Get valid data.
}
)
->add(\Zfegg\ContentValidation\ContentValidationMiddleware::class)
->setArgument('schema', 'path-to-json-schema.json')
;
DbalRecordExistsFilter
: Usedoctrine/dbal
to check record exists. The json-schema$filters
config:{ "$func": "dbal-exists", "$vars": { "db": "db", // Get DBAL object by container. "sql": "select ...", // Set custom SQL "table": "foo", // Table name "field": "key", // Field name "exists": true // Check record exists or not exists. Default: false } }
DoctrineRecordExistsFilter
: Usedoctrine/orm
to check record exists. The json-schema$filters
config:{ "$func": "orm-exists", "$vars": { "db": "orm.default", // Get ORM object by container. "dql": "select ...", // Set custom DQL "entity": "Foo", // Entity name "field": "key", // Field name "exists": true // Check record exists or not exists. Default: false } }
RecordExistsFilter
: UsePDO
to check record exists. The json-schema$filters
config:{ "$func": "db-exists", "$vars": { "db": "db", // Get DBAL object by container. "sql": "select ...", // Set custom SQL "table": "foo", // Table name "field": "key", // Field name "exists": true // Check record exists or not exists. Default: false } }