zfegg/content-validation

Content validation for PSR-15 middleware

6.0.0 2024-08-22 06:07 UTC

This package is auto-updated.

Last update: 2024-12-22 06:48:24 UTC


README

简体中文

GitHub Actions: Run tests Coverage Status Latest Stable Version

Content validation for PSR-15 middleware. Based on opis/json-schema.

Installation

Install via composer.

composer require zfegg/content-validation

Usage

Opis\JsonSchema\Validator factory config.

// 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',
        ],
    ]
]

Mezzio

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"
    ]
  }
}

Slim

$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')
;

Validators

  • DbalRecordExistsFilter: Use doctrine/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: Use doctrine/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: Use PDO 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
        }
    }