承接 kentaroutakeda/laravel-openapi-validator 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

kentaroutakeda/laravel-openapi-validator

Composer 安装命令:

composer require kentaroutakeda/laravel-openapi-validator

包简介

Laravel OpenAPI Validator - Request and response validators based on the OpenAPI Specification.

README 文档

README

Request and response validators based on the OpenAPI Specification.

Summary

  • Validate any request and response with a pre-prepared OpenAPI Spec.
  • Automatically load specs from Laravel OpenAPI or L5 Swagger.
  • You can also load your own specs without using these libraries.
  • You can customize validation and error logging behavior on a per-route or application-wide basis.
  • Can display Swagger UI. You can view the documentation and test the API.

Requirements

  • PHP 8.1 or higher
  • Laravel 10.0 or higher

Installation

You can install the package via composer:

composer require kentaroutakeda/laravel-openapi-validator

Usage

  1. Configure OpenAPI Specification

    If you're using Laravel OpenAPI, you don't need to do anything.

    For L5 Swagger, the following settings are required:

    # .env
    OPENAPI_VALIDATOR_PROVIDER="l5-swagger"

    How to load your own schema without using these packages will be explained later.

  2. Register Middleware

    Route::get('/example', ExampleController::class)
        ->middleware(OpenApiValidator::class); // <- Add this line

    Routes with this setting will be validated for all requests including Feature Tests, and depending on the settings, responses as well.

    NOTE:
    This repository's ./e2e directory contains working examples for e2e testing. You can see middleware configuration examples in Routing, and actual validations and failures in Tests.

  3. (Optional) Customize Middleware

    If necessary, you can change Middleware behavior for each route.

    Route::get('/', ExampleController::class)
        ->middleware(OpenApiValidator::config(
            // // Provider name from config
            provider: 'my-provider',
            // For performance, skip response validation in production
            skipResponseValidation: app()->isProduction(),
        ));

    NOTE:
    Response validation for large amounts of data can take a long time. It would be a good idea to switch on/off validation depending on the route and APP_* environment variables.

  4. (Optional) Vite Dev Server

    When using Vite (npm run dev) with the L5 Swagger provider, L5SwaggerResolver calls generateDocs() which writes to storage/api-docs/api-docs.json on every request (when the openapi-validator:cache has not been generated). This file write triggers Vite's file watcher, causing an infinite full-page reload loop.

    To prevent this, add storage/api-docs to Vite's watch ignore list:

    // vite.config.js
    export default defineConfig({
        server: {
            watch: {
                ignored: ['**/storage/api-docs/**'],
            },
        },
        // ...
    });

    Alternatively, running php artisan openapi-validator:cache will bypass L5SwaggerResolver entirely, avoiding the file write.

  5. Deployment

    When deploying your application to production, you should make sure that you run the openapi-validator:cache Artisan command during your deployment process:

    php artisan openapi-validator:cache

    This command caches the OpenAPI Spec defined in your application. If you change the definition for development, you need to clear it as follows:

    php artisan openapi-validator:clear

    Alternatively, these commands are automatically executed when running Laravel's built-in optimization commands:

    php artisan optimize        # Includes openapi-validator:cache
    php artisan optimize:clear  # Includes openapi-validator:clear

(Optional) Swagger UI support

You can view the Swagger UI just by installing the package. No additional configuration is required.

  1. Install package.

    composer require --dev swagger-api/swagger-ui
  2. Display APP_URL/openapi-validator/documents in browser.

    open http://localhost:8000/openapi-validator/documents

NOTE:
By default, the Swagger UI can only be displayed when APP_DEBUG is enabled.

(Optional) Customization

Publish Configuration

You can publish the config file to change behavior.

php artisan openapi-validator:publish

Alternatively, most settings can be changed using environment variables. Check the comments in config/openapi-validator.php for details.

Your own schema providers

  1. If you want to use your own schema providers, first publish the config.

  2. Next, implement a class to retrieve the schema.

    class MyResolver implements ResolverInterface
    {
        public function getJson(array $options): string
        {
            // This example assumes that the schema exists in the root directory.
            return File::get(base_path('openapi.json'));
        }
    }
  3. Finally, set it in your config.

    return [
        // Set the provider name.
        'default' => 'my-resolver',
    
        'providers' => [
            // Set the provider name you created.
            'my-resolver' => [
                // Specify the class you created in the `resolver` parameter.
                'resolver' => MyResolver::class,
            ],
        ],
    ];

Error responses and customization

By default, it is formatted according to RFC 7807 - Problem Details for HTTP APIs.

Validation errors, stack traces and original response can also be included depending on your settings. For example, it might look like this:

{
  "title": "NoResponseCode",
  "detail": "OpenAPI spec contains no such operation [/,get,201]", // Error reason
  "status": 500, // Same as HTTP response code
  "originalResponse": { "status": "201" }, // Original response before validation
  "trace": [
    { "error": "...", "message": "...", "file": "...", "line": 42 },
    { "...": "..." }
  ]
}

Here's how to change to a different format:

  1. First, implement a class to generate a response. For example:

    class MyErrorRenderer implements ErrorRendererInterface
    {
        public function render(
            \Throwable $error,
            Request $request,
            ?Response $response = null,
        ): Response {
            return new Response(
                match ($response === null) {
                    ErrorType::Request => "Request Error: " . $error->getMessage(),
                    ErrorType::Response => "Response Error: " . $error->getMessage(),
                }
            );
        }
    }
  2. Next, register the class to the service container.

    // AppServiceProvider.php
    
    public function register(): void
    {
        $this->app->bind(
            ErrorRendererInterface::class,
            MyErrorRenderer::class
        );
    }

Events

If a validation error occurs, an event will be fired depending on the type of error.

  • ValidationFailedInterface - All errors
    • RequestValidationFailed - Request validation error
    • ResponseValidationFailed - Response validation error

Contributing and Development

Feel free to open an Issue or add a Pull request.

When adding a pull request, please refer to the following setup steps.

# Clone this repository and move to the directory.
git clone https://github.com/KentarouTakeda/laravel-openapi-validator.git
cd laravel-openapi-validator

# Install dependencies.
composer install

# (Optional) Install tools: The commit hook automatically formats the code.
npm install

# Run tests.
vendor/bin/phpunit

License

Laravel OpenAPI Validator is open-sourced software licensed under the MIT license.

kentaroutakeda/laravel-openapi-validator 适用场景与选型建议

kentaroutakeda/laravel-openapi-validator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 25.84k 次下载、GitHub Stars 达 9, 最近一次更新时间为 2023 年 12 月 29 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「documentation」 「rest」 「api」 「validator」 「validation」 「middleware」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 kentaroutakeda/laravel-openapi-validator 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 kentaroutakeda/laravel-openapi-validator 我们能提供哪些服务?
定制开发 / 二次开发

基于 kentaroutakeda/laravel-openapi-validator 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 25.84k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 9
  • 点击次数: 16
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 9
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-12-29