Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Swagger Php Laravel Package

zircote/swagger-php

Generate OpenAPI 3.0/3.1/3.2 docs from your PHP 8.2+ code using native attributes (preferred) or optional Doctrine annotations. Includes CLI and programmatic generation, parses phpdoc, provides helpful error reporting, and powers interactive API docs.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Native PHP Attribute Support: Aligns perfectly with modern Laravel (PHP 8.2+) and PHP’s attribute system, reducing boilerplate and improving IDE support (e.g., autocompletion, validation).
    • OpenAPI 3.0/3.1/3.2 Compliance: Ensures compatibility with modern API documentation standards and tooling (e.g., Swagger UI, Redoc).
    • Dual Usage Modes: Can be integrated programmatically (e.g., in Laravel’s boot() or service providers) or via CLI, offering flexibility.
    • Type Resolution: Leverages symfony/type-info for advanced type hints (e.g., generics, unions), reducing manual schema definitions in Laravel’s DTOs or request/response models.
    • Deprecation Path: Clear migration from annotations to attributes (deprecated in v6) simplifies long-term maintenance.
  • Cons:

    • Laravel-Specific Overhead: Requires manual integration with Laravel’s routing (e.g., Route::get()) to avoid duplication between route definitions and OpenAPI attributes.
    • Attribute Pollution: Overloading controllers/models with attributes may clutter codebase if not modularized (e.g., via traits or separate annotation classes).
    • Performance: Runtime generation of OpenAPI specs (vs. static files) may introduce overhead in high-traffic APIs. Mitigated by caching (e.g., Laravel’s cache() helper).

Integration Feasibility

  • Laravel Ecosystem Fit:

    • Routing: Attributes can mirror Laravel’s Route definitions (e.g., #[OAT\Get(path: '/api/users')] alongside Route::get('/api/users', ...)). Use route model binding or middleware to sync metadata.
    • Validation: Integrates with Laravel’s validation (e.g., #[OAT\RequestBody(content: new OAT\JsonContent(schema: new UserRequest()))]) to reuse request/response schemas.
    • Service Providers: Register a Generator instance in AppServiceProvider for programmatic access (e.g., app('openapi.generator')).
    • Artisan Commands: Extend Laravel’s CLI with a custom command to generate OpenAPI docs on demand (e.g., php artisan openapi:generate).
  • Dependencies:

    • Core: zircote/swagger-php (v6.x) + symfony/type-info (required for type resolution).
    • Optional: doctrine/annotations (legacy support; avoid unless migrating old code).
    • Tooling: rector/rector (for codebase modernization if adopting attributes).

Technical Risk

  • Migration Risk:
    • Attribute Adoption: Requires updating controllers/models to use PHP 8.2 attributes (low risk if already on PHP 8.2+).
    • Type Hinting: Complex generics (e.g., array<string, User>) may need explicit PHPDoc fallbacks if TypeInfoTypeResolver misbehaves.
    • Route Conflicts: Ensure path in #[OAT\Get] matches Laravel’s route definitions to avoid inconsistencies.
  • Tooling Risk:
    • IDE Support: Attributes may not be recognized immediately in older IDEs (e.g., PHPStorm < 2021.3). Use phpstan or psalm for validation.
    • CI/CD: Add tests for OpenAPI generation (e.g., validate output against a schema with openapi-linter).
  • Performance Risk:
    • Generation Overhead: Runtime generation adds ~50–200ms per request if not cached. Mitigate with:
      // Cache for 1 hour
      $openapi = Cache::remember('openapi-spec', 3600, fn() => $generator->generate());
      

Key Questions

  1. Attribute Strategy:
    • Will attributes be applied directly to controllers/models, or abstracted into traits/interfaces (e.g., #[AsOpenApi])?
  2. Versioning:
    • Should OpenAPI 3.2.0 be adopted now, or stick to 3.0/3.1 for broader tooling compatibility?
  3. CI/CD Integration:
    • How will OpenAPI specs be validated in CI? (e.g., openapi-linter, custom scripts).
  4. Caching:
    • Will specs be pre-generated (e.g., during deploy) or dynamically cached?
  5. Legacy Support:
    • Are there existing PHPDoc annotations to migrate to attributes?

Integration Approach

Stack Fit

  • Laravel Core:
    • Routing: Use #[OAT\Get], #[OAT\Post], etc., alongside Laravel’s Route:: methods. Example:
      #[OAT\Get(path: '/users/{id}', summary: 'Get user by ID')]
      public function show(User $user) { ... }
      
    • Validation: Reuse Laravel’s Request classes in #[OAT\RequestBody]:
      #[OAT\RequestBody(content: new OAT\JsonContent(schema: new OAT\Schema(ref: '#/components/schemas/UserRequest')))]
      
    • Middleware: Attach OpenAPI metadata to middleware (e.g., #[OAT\Security(scheme: 'bearer')]).
  • Tooling:
    • Swagger UI: Serve generated YAML/JSON via Laravel’s routes:
      Route::get('/api/docs', function () {
          return response($generator->generate(), 200, ['Content-Type' => 'application/yaml']);
      });
      
    • API Testing: Integrate with Pest/Laravel’s testing (e.g., assert OpenAPI compliance in tests).

Migration Path

  1. Assessment Phase:
    • Audit existing PHPDoc annotations and convert to attributes.
    • Identify controllers/models needing OpenAPI metadata.
  2. Incremental Adoption:
    • Start with non-critical endpoints (e.g., /health).
    • Use traits to avoid attribute pollution:
      trait OpenApiAttributes {
          #[OAT\Info(title: 'My API', version: '1.0')]
          public function __construct() {}
      }
      
  3. Tooling Setup:
    • Add zircote/swagger-php and symfony/type-info to composer.json.
    • Configure Generator in AppServiceProvider:
      $this->app->singleton('openapi.generator', fn() => new Generator());
      
  4. Validation:
    • Run php artisan openapi:generate locally and validate output with openapi-linter.
    • Add CI checks (e.g., GitHub Actions workflow).

Compatibility

  • Laravel Versions:
    • Requires Laravel 9+ (PHP 8.2+). For older versions, use swagger-php v5.x (but lose OpenAPI 3.2 support).
  • PHP Extensions:
    • No extensions required (unlike ext-json in v5.x).
  • Existing Code:
    • Minimal impact if using attributes; PHPDoc annotations may need manual migration.

Sequencing

  1. Phase 1: Set up Generator and basic attributes (e.g., Info, Get).
  2. Phase 2: Migrate validation schemas (e.g., Request, Response) to use Laravel’s Request classes.
  3. Phase 3: Integrate with Swagger UI and CI validation.
  4. Phase 4: Optimize caching and performance (e.g., pre-generate specs).

Operational Impact

Maintenance

  • Pros:
    • Self-Documenting Code: Attributes keep OpenAPI specs in sync with implementation.
    • Reduced Duplication: No separate swagger.yml to maintain.
    • IDE-Friendly: Attributes enable autocompletion and validation (e.g., #[OAT\Get(path: '/...')]).
  • Cons:
    • Attribute Bloat: Overuse may make controllers harder to read. Mitigate with:
      • Grouping attributes in traits.
      • Using separate annotation classes (e.g., #[ApiResource]).
    • Version Updates: Stay updated with swagger-php (e.g., OpenAPI 3.2 features).

Support

  • Debugging:
    • Use Generator::generate() with debug: true to surface issues:
      $generator->generate(['/app/Http/Controllers'], debug: true);
      
    • Leverage phpstan to catch attribute misconfigurations.
  • Community:
    • Active GitHub repo (5.3k stars, recent releases). Use issues/discussions for edge cases.
    • Laravel-specific questions can target laravel.io or r/laravelphp.

Scaling

  • Performance:
    • Dynamic Generation: Add caching (e.g., Laravel’s cache() or Redis) for high-traffic APIs.
    • Pre-Generation: Generate specs during deploy (e.g., via post-deploy hook) and serve static files
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope