methorz/openapi-generator 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

methorz/openapi-generator

Composer 安装命令:

composer require methorz/openapi-generator

包简介

Automatic OpenAPI 3.0 specification generator from routes and DTOs

README 文档

README

Automatic OpenAPI 3.0 specification generator from routes and DTOs

CI codecov PHPStan PHP Version License

Automatically generates OpenAPI specifications by analyzing your application's routes and Data Transfer Objects (DTOs). Perfect for Mezzio, Laminas, and any PSR-15 application.

✨ Features

  • 🚀 Automatic Generation: Scans routes and DTOs to generate complete OpenAPI specs
  • 📝 DTO Analysis: Extracts request/response schemas from PHP DTOs with property promotion
  • Validation Integration: Reads Symfony Validator attributes for schema constraints
  • 🎯 Handler Detection: Automatically finds request and response DTOs in handlers
  • 📦 Multiple Formats: Generates both YAML and JSON outputs
  • 🔧 Zero Configuration: Works out-of-the-box with sensible defaults
  • 🎨 Customizable: Configure via application config
  • 🔗 Nested DTOs: Automatically generates schemas for nested DTO references
  • 📚 Collections: Supports typed arrays with @param array<Type> PHPDoc
  • 🎲 Enums: Full support for backed and unit enums (PHP 8.1+)
  • 🔀 Union Types: Generates oneOf schemas for union types (PHP 8.0+)
  • Performance: Schema caching for efficient generation

📋 Requirements

This package requires PHP 8.2+ and uses the following runtime dependencies:

Package Purpose Framework Required?
psr/container PSR-11 Container Interface ❌ No
symfony/console CLI command handling ❌ No (standalone utility)
symfony/yaml YAML file parsing/writing ❌ No (standalone utility)

Note: The Symfony packages used are standalone utility libraries, not framework components. They work independently without the Symfony framework and are used by many non-Symfony projects (Composer, PHPStan, PHPUnit, etc.).

📦 Installation

composer require methorz/openapi-generator

🚀 Quick Start

1. Register the Command

Add to your application's command configuration:

// config/autoload/dependencies.global.php
use Methorz\OpenApi\Command\GenerateOpenApiCommand;

return [
    'dependencies' => [
        'factories' => [
            GenerateOpenApiCommand::class => function ($container) {
                return new GenerateOpenApiCommand($container);
            },
        ],
    ],
];

2. Generate Specification

php bin/console openapi:generate

This will create:

  • public/openapi.yaml - YAML format
  • public/openapi.json - JSON format

📖 Usage

Basic Configuration

// config/autoload/openapi.global.php
return [
    'openapi' => [
        'title' => 'My API',
        'version' => '1.0.0',
    ],
];

Example Handler

The generator automatically analyzes your handlers:

namespace App\Handler;

use App\Request\CreateItemRequest;
use App\Response\ItemResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

final class CreateItemHandler implements RequestHandlerInterface
{
    public function handle(
        ServerRequestInterface $request,
        CreateItemRequest $dto // ← Request DTO detected
    ): ItemResponse {           // ← Response DTO detected
        // Handler logic...
    }
}

Example Request DTO

namespace App\Request;

use Symfony\Component\Validator\Constraints as Assert;

final readonly class CreateItemRequest
{
    public function __construct(
        #[Assert\NotBlank]
        #[Assert\Length(min: 3, max: 100)]
        public string $name,

        #[Assert\NotBlank]
        #[Assert\Length(min: 10, max: 500)]
        public string $description,

        #[Assert\Email]
        public string $email,
    ) {}
}

Generated Schema:

components:
  schemas:
    CreateItemRequest:
      type: object
      required:
        - name
        - description
        - email
      properties:
        name:
          type: string
          minLength: 3
          maxLength: 100
        description:
          type: string
          minLength: 10
          maxLength: 500
        email:
          type: string
          format: email

📋 Supported Validation Attributes

The generator extracts constraints from Symfony Validator attributes:

Attribute OpenAPI Property
@Assert\NotBlank required: true
@Assert\Length(min, max) minLength, maxLength
@Assert\Range(min, max) minimum, maximum
@Assert\Email format: email
@Assert\Url format: uri
@Assert\Uuid format: uuid

🚀 Advanced Features

Enum Support

Generates enum schemas from PHP 8.1+ backed enums:

enum StatusEnum: string
{
    case DRAFT = 'draft';
    case ACTIVE = 'active';
    case ARCHIVED = 'archived';
}

final readonly class CreateItemRequest
{
    public function __construct(
        public StatusEnum $status,
    ) {}
}

Generated Schema:

CreateItemRequest:
  type: object
  properties:
    status:
      type: string
      enum: ['draft', 'active', 'archived']

Nested DTOs

Automatically generates schemas for nested DTO objects:

final readonly class AddressDto
{
    public function __construct(
        #[Assert\NotBlank]
        public string $street,

        #[Assert\NotBlank]
        public string $city,

        public ?string $country = null,
    ) {}
}

final readonly class CreateUserRequest
{
    public function __construct(
        public string $name,
        public AddressDto $address,              // ← Nested DTO
        public ?AddressDto $billingAddress = null, // ← Nullable nested DTO
    ) {}
}

Generated Schema:

CreateUserRequest:
  type: object
  required: ['name', 'address']
  properties:
    name:
      type: string
    address:
      $ref: '#/components/schemas/AddressDto'
    billingAddress:
      $ref: '#/components/schemas/AddressDto'
      nullable: true

AddressDto:
  type: object
  required: ['street', 'city']
  properties:
    street:
      type: string
    city:
      type: string
    country:
      type: string
      nullable: true

Typed Collections

Supports typed arrays using PHPDoc annotations:

/**
 * @param array<int, AddressDto> $addresses
 * @param array<string> $tags
 */
final readonly class CreateOrderRequest
{
    public function __construct(
        public string $orderId,
        public array $addresses,
        public array $tags,
    ) {}
}

Generated Schema:

CreateOrderRequest:
  type: object
  properties:
    orderId:
      type: string
    addresses:
      type: array
      items:
        $ref: '#/components/schemas/AddressDto'
    tags:
      type: array
      items:
        type: string

Union Types

Generates oneOf schemas for union types:

final readonly class FlexibleRequest
{
    public function __construct(
        public string|int $identifier,  // ← Union type
    ) {}
}

Generated Schema:

FlexibleRequest:
  type: object
  properties:
    identifier:
      oneOf:
        - type: string
        - type: integer

🎯 Features

Route Detection

Scans your application's route configuration:

// config/autoload/routes.global.php
return [
    'routes' => [
        [
            'path' => '/api/v1/items',
            'middleware' => [CreateItemHandler::class],
            'allowed_methods' => ['POST'],
        ],
    ],
];

Automatic Operation Generation

Creates OpenAPI operations with:

  • HTTP method (GET, POST, PUT, DELETE, etc.)
  • Path parameters (extracted from {id} patterns)
  • Request body (for POST/PUT/PATCH)
  • Response schemas
  • Summary and operationId
  • Tags (from module namespace)

Path Parameters

Automatically detects and types path parameters:

'/api/v1/items/{id}' → parameter: id (format: uuid)
'/api/v1/users/{userId}' → parameter: userId (type: integer)

📂 Generated Output

OpenAPI Structure

openapi: 3.0.0
info:
  title: My API
  version: 1.0.0
  description: Automatically generated from routes and DTOs
servers:
  - url: http://localhost:8080
    description: Local development
paths:
  /api/v1/items:
    post:
      operationId: createItem
      summary: create item
      tags:
        - Items
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateItemRequest'
      responses:
        201:
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ItemResponse'
        400:
          description: Bad Request
        404:
          description: Not Found
components:
  schemas:
    CreateItemRequest:
      # ... schema definition
    ItemResponse:
      # ... schema definition

🔧 Configuration

Full Configuration Example

// config/autoload/openapi.global.php
return [
    'openapi' => [
        'title' => 'My API',
        'version' => '1.0.0',
        'description' => 'API for managing items',
        'servers' => [
            [
                'url' => 'https://api.example.com',
                'description' => 'Production',
            ],
            [
                'url' => 'http://localhost:8080',
                'description' => 'Development',
            ],
        ],
    ],
];

📊 Integration with Swagger UI

View your generated OpenAPI specification:

# Install Swagger UI
composer require swagger-api/swagger-ui

# Access at:
http://localhost:8080/swagger-ui

Or use online tools:

🧪 Testing

# Run all tests
composer test

# Run with coverage
composer test:coverage

# Code style check
composer cs-check

# Fix code style
composer cs-fix

# Static analysis
composer analyze

# All quality checks
composer quality

🤝 Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Write tests for new features
  4. Ensure all quality checks pass (composer quality)
  5. Submit a pull request

📄 License

MIT License. See LICENSE for details.

🔗 Related Packages

This package is part of the MethorZ HTTP middleware ecosystem:

Package Description
methorz/http-dto Automatic HTTP ↔ DTO conversion with validation
methorz/http-problem-details RFC 7807 error handling middleware
methorz/http-cache-middleware HTTP caching with ETag support
methorz/http-request-logger Structured logging with request tracking
methorz/openapi-generator Automatic OpenAPI spec generation (this package)

These packages work together seamlessly in PSR-15 applications.

🙏 Acknowledgments

Built with:

📞 Support

🔗 Links

Made with ❤️ by Thorsten Merz

methorz/openapi-generator 适用场景与选型建议

methorz/openapi-generator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 50 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 11 月 27 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 50
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 21
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-11-27