beblife/schema-validation-laravel

使用JSON-schema对象验证HTTP请求

v0.4.0 2022-09-05 19:16 UTC

This package is auto-updated.

Last update: 2024-09-16 00:20:11 UTC


README

使用OpenAPI规范文件或JSON-schema对象在Laravel中验证HTTP请求。

Latest Version on Packagist PHP from Packagist CI

安装

此包可以通过Composer安装

composer require beblife/schema-validation-laravel

之后可以使用以下命令发布配置文件

php artisan vendor:publish --provider="Beblife\SchemaValidation\SchemaValidationServiceProvider"

发布后,您将有一个类似这样的 config/schema-validation.php 文件

return [
    'spec_path' => env('SCHEMA_VALIDATION_SPEC_PATH', ''),

    'response' => [
        'status' => 400,
    ],
];

您可以将规范路径定义为 .env 变量,或者在配置文件本身中硬编码绝对路径。当抛出验证异常时的状态码也可以在这里自定义。

用法

验证请求

此包在 Illumnite\Http\Request::class 上提供了一个宏,用于验证请求的规范。

use Illuminate\Http\Request;

class UserRegistrationRequestHandler extends Controller
{
    public function __invoke(Request $request)
    {
        $request = $request->validateSchema();

        // Validate any additional rules (if any) with $request->validate(...)

        // Process the valid request ...
    }
}

当调用 validateSchema() 方法时,包将搜索在配置的OpenAPI规范文件中定义的匹配路径,并验证请求是否符合规范。

在验证过程中可能发生两种异常

UnableToValidateSchema

当在规范文件中找不到路径时,将抛出此异常。

InvalidSchema

当请求与规范文件中定义的规范不匹配时,将抛出此异常。此异常扩展了Laravel的 ValidationException,导致返回 400 : Bad Request,格式如下

{
    "message": "The given data is invalid.",
    "errors": {
        "property": [
            "The validation message",
        ]
    }
}

该包还提供了一个可以添加到表单请求中用于验证规范的特质。在幕后,这个特质通过钩入 prepareForValidation() 方法开始验证请求的规范。之后,Laravel框架将处理在 rules() 方法中定义的任何额外验证。

use Beblife\SchemaValidation\ValidateSchema;
use Illuminate\Foundation\Http\FormRequest;

class UserRegistrationRequest extends FormRequest
{
    use ValidateSchema;

    public function rules(): array
    {
        return [
            // Your other validation rules ...
        ];
    }
}

用于验证的规范将从配置的OpenAPI规范文件中自动解析。这可以通过在 FormRequest::class 上定义 schema() 来覆盖。

use Beblife\SchemaValidation\Schema;
use Beblife\SchemaValidation\ValidateSchema;
use Illuminate\Foundation\Http\FormRequest;

class UserRegistrationRequest extends FormRequest
{
    use ValidateSchema;

    public function schema(): Schema
    {
        return // Your custom defined schema ...
    }

    public function rules(): array
    {
        return [
            // Your other validation rules ...
        ];
    }
}

定义规范

默认情况下,包将使用配置规范中定义的规范来验证请求。还有选项可以使用提供的外观将 Beblife\SchemaValidation\Schema::class 传递给 validateSchema() 方法。

从数组

$schema = Beblife\SchemaValidation\Facades\Schema::fromArray([
    'type' => 'object',
    'properties' => [
        'field' => [
            'type' => 'string',
            'enum' => [
                'option 1',
                'option 2',
            ]
        ]
    ]
]);

从文件

// from a JSON-file
$schema = Beblife\SchemaValidation\Facades\Schema::fromFile('/path/to/a/schema/file.json'));
// from a YAML-file
$schema = Beblife\SchemaValidation\Facades\Schema::fromFile('/path/to/a/schema/file.yaml'));

从类

use Beblife\SchemaValidation\Schema;

class MyCustomSchema implements Schema
{
    public function toArray(): array
    {
        return [
            'type' => 'object',
            'properties' => [
                // ...
            ]
        ];
    }
}

许可证

MIT许可证(MIT)。有关更多信息,请参阅 许可证文件