PHPackages                             methorz/openapi-generator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. methorz/openapi-generator

ActiveLibrary[API Development](/categories/api)

methorz/openapi-generator
=========================

Automatic OpenAPI 3.0 specification generator from routes and DTOs

v1.0.0(5mo ago)050MITPHPPHP ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0CI passing

Since Dec 1Pushed 5mo agoCompare

[ Source](https://github.com/MethorZ/openapi-generator)[ Packagist](https://packagist.org/packages/methorz/openapi-generator)[ RSS](/packages/methorz-openapi-generator/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (12)Versions (2)Used By (0)

MethorZ OpenAPI Generator
=========================

[](#methorz-openapi-generator)

**Automatic OpenAPI 3.0 specification generator from routes and DTOs**

[![CI](https://github.com/MethorZ/openapi-generator/actions/workflows/ci.yml/badge.svg)](https://github.com/MethorZ/openapi-generator/actions/workflows/ci.yml)[![codecov](https://camo.githubusercontent.com/af691924aeda5b549b36061c152e9477eb5f0879bd7d32f9693b9087a8748013/68747470733a2f2f636f6465636f762e696f2f67682f4d6574686f725a2f6f70656e6170692d67656e657261746f722f67726170682f62616467652e737667)](https://codecov.io/gh/MethorZ/openapi-generator)[![PHPStan](https://camo.githubusercontent.com/1bc07920f0d36e55c17e1d38b1caa132cc605f51a82b388c962870b9a747b898/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230392d627269676874677265656e2e737667)](https://phpstan.org/)[![PHP Version](https://camo.githubusercontent.com/c9f64f714c636ba27a3bba6dfd52f98426832db1262747efa54b212d16943651/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e322d626c7565)](https://php.net)[![License](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)](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
----------

[](#-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` 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
--------------

[](#-requirements)

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

PackagePurposeFramework 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
--------------

[](#-installation)

```
composer require methorz/openapi-generator
```

---

🚀 Quick Start
-------------

[](#-quick-start)

### 1. **Register the Command**

[](#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**

[](#2-generate-specification)

```
php bin/console openapi:generate
```

This will create:

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

---

📖 Usage
-------

[](#-usage)

### **Basic Configuration**

[](#basic-configuration)

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

### **Example Handler**

[](#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**

[](#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
---------------------------------

[](#-supported-validation-attributes)

The generator extracts constraints from Symfony Validator attributes:

AttributeOpenAPI 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
-------------------

[](#-advanced-features)

### **Enum Support**

[](#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**

[](#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**

[](#typed-collections)

Supports typed arrays using PHPDoc annotations:

```
/**
 * @param array $addresses
 * @param array $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**

[](#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
----------

[](#-features-1)

### **Route Detection**

[](#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**

[](#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**

[](#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
------------------

[](#-generated-output)

### **OpenAPI Structure**

[](#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
---------------

[](#-configuration)

### **Full Configuration Example**

[](#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
-----------------------------

[](#-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:

- [Swagger Editor](https://editor.swagger.io)
- [ReDoc](https://redocly.github.io/redoc/)

---

🧪 Testing
---------

[](#-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
--------------

[](#-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
---------

[](#-license)

MIT License. See [LICENSE](LICENSE) for details.

---

🔗 Related Packages
------------------

[](#-related-packages)

This package is part of the MethorZ HTTP middleware ecosystem:

PackageDescription**[methorz/http-dto](https://github.com/methorz/http-dto)**Automatic HTTP ↔ DTO conversion with validation**[methorz/http-problem-details](https://github.com/methorz/http-problem-details)**RFC 7807 error handling middleware**[methorz/http-cache-middleware](https://github.com/methorz/http-cache-middleware)**HTTP caching with ETag support**[methorz/http-request-logger](https://github.com/methorz/http-request-logger)**Structured logging with request tracking**[methorz/openapi-generator](https://github.com/methorz/openapi-generator)**Automatic OpenAPI spec generation (this package)These packages work together seamlessly in PSR-15 applications.

---

🙏 Acknowledgments
-----------------

[](#-acknowledgments)

Built with:

- [Symfony Console](https://symfony.com/doc/current/components/console.html)
- [Symfony YAML](https://symfony.com/doc/current/components/yaml.html)
- [Symfony Validator](https://symfony.com/doc/current/validation.html)

---

📞 Support
---------

[](#-support)

- **Issues**: [GitHub Issues](https://github.com/methorz/openapi-generator/issues)
- **Discussions**: [GitHub Discussions](https://github.com/methorz/openapi-generator/discussions)

---

🔗 Links
-------

[](#-links)

- [Changelog](CHANGELOG.md)
- [Contributing](CONTRIBUTING.md)
- [Security](SECURITY.md)

---

Made with ❤️ by [Thorsten Merz](https://github.com/methorz)

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance72

Regular maintenance activity

Popularity8

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

168d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b0233a9072fdc1746031fd96b487fce9b0d5f55c0124b70fc51ac2bb833bb906?d=identicon)[MethorZ](/maintainers/MethorZ)

---

Tags

api-documentationcode-generationcomposerframework-agnosticmiddlewareopenapiopenapi3packagistphpphp-attributesphp8psr-15swaggersymfony-validatorapidocumentationswaggeropenapigeneratorpsr-15dtoopenapi3

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/methorz-openapi-generator/health.svg)

```
[![Health](https://phpackages.com/badges/methorz-openapi-generator/health.svg)](https://phpackages.com/packages/methorz-openapi-generator)
```

###  Alternatives

[swagger-api/swagger-ui

 Swagger UI is a collection of HTML, Javascript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.

28.7k45.4M99](/packages/swagger-api-swagger-ui)[darkaonline/l5-swagger

OpenApi or Swagger integration to Laravel

2.9k34.0M112](/packages/darkaonline-l5-swagger)[darkaonline/swagger-lume

OpenApi or Swagger integration to Lumen

3372.3M3](/packages/darkaonline-swagger-lume)[wapmorgan/openapi-generator

OpenApi configuration generator directly from PHP code (PhpDoc, functions signature and type hints) and projects (for yii2, slim, laravel). Can be used with a large monolithic backend to maintain big API documentation

202.8k](/packages/wapmorgan-openapi-generator)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
