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 Bundle Laravel Package

cm2-tech/swagger-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require cm2-tech/swagger-bundle:^1.0
    

    Symfony Flex auto-enables the bundle. If not, add to config/bundles.php:

    CM2\SwaggerBundle\CM2SwaggerBundle::class => ['all' => true],
    
  2. Configure .env:

    SWAGGER_TOKEN=your_secure_token_here
    

    (Critical: Protects /_swagger endpoint.)

  3. Update services.yaml:

    services:
      CM2\SwaggerBundle\Controller\SwaggerController:
        arguments:
          $sources:
            - '%kernel.project_dir%/src/Controller'
            - '%kernel.project_dir%/src/Entity'
        tags: ['controller.service_arguments']
    
  4. First Use Case: Access /_swagger?token=your_secure_token_here to generate swagger.json from annotated controllers/entities.


Where to Look First

  • Annotations: Focus on zircote/swagger-php annotations (e.g., @OA\Info, @OA\Tag, @OA\PathItem).
  • Controller/Entity Files: Ensure paths in $sources match your project structure.
  • Debugging: Check Symfony’s profiler (/_profiler) for annotation parsing errors.

Implementation Patterns

Core Workflow

  1. Annotate Controllers:
    use OpenApi\Annotations as OA;
    
    

/**

  • @OA\Info(title="My API", version="1.0") / #[Route('/api/users', name: 'get_users')] class UserController extends AbstractController { /*
    • @OA\Get(
    • path="/api/users",
      
    • @OA\Response(response="200", description="List of users")
      
    • ) */ public function index(): Response { ... } }
    
    
  1. Generate & Serve:

    • Access /_swagger?token=... to auto-generate swagger.json.
    • Integrate with tools like Swagger UI or Redoc via:
      # config/packages/swagger_ui.yaml (if using symfony/swagger-ui-bundle)
      swagger_ui:
        urls:
          - { url: '/_swagger', name: 'My API' }
      
  2. Extend with Entities:

    /**
     * @OA\Schema(
     *     schema="User",
     *     @OA\Property(property="name", type="string")
     * )
     */
    #[ORM\Entity]
    class User { ... }
    

Integration Tips

  • Caching: Cache swagger.json in production (e.g., via Symfony’s HTTP cache or a reverse proxy).
    # config/packages/framework.yaml
    framework:
      http_cache:
        cache_control:
          rules:
            - path: ^/_swagger
              max_age: 3600
    
  • Dynamic Tokens: Use Symfony’s ParameterBag to fetch SWAGGER_TOKEN securely:
    $token = $this->getParameter('swagger_token');
    
  • Validation: Pair with NelmioApiDocBundle for enhanced validation:
    composer require nelmio/api-doc-bundle
    

Gotchas and Tips

Pitfalls

  1. Token Mismatch:

    • Error: 403 Forbidden if SWAGGER_TOKEN in .env doesn’t match the request.
    • Fix: Double-check .env and URL params (?_swagger?token=...).
  2. Annotation Parsing Failures:

    • Symptom: Empty swagger.json or errors in Symfony logs.
    • Debug:
      • Verify zircote/swagger-php annotations are correctly imported.
      • Check src/Controller and src/Entity paths in services.yaml.
      • Run php bin/console debug:container CM2\SwaggerBundle\Controller\SwaggerController to validate service config.
  3. PHP Version:

    • Error: PHP 8.1 required (or higher). Use:
      php -v  # Verify version
      composer require php:^8.1
      

Debugging Tips

  • Log Annotations: Add a temporary dump in SwaggerController to inspect parsed annotations:
    public function index(Swagger $swagger, string $token): Response
    {
        file_put_contents(
            'var/log/swagger_annotations.log',
            print_r($swagger->toArray(), true)
        );
        // ...
    }
    
  • Symfony Profiler: Use the Annotations tab in _profiler to validate parsed metadata.

Extension Points

  1. Custom Sources: Extend $sources in services.yaml to include:

    $sources:
      - '%kernel.project_dir%/src/DTO'
      - '%kernel.project_dir%/config/swagger'
    
  2. Post-Processing: Override SwaggerController to modify the OpenAPI object before JSON serialization:

    use CM2\SwaggerBundle\Controller\SwaggerController as BaseController;
    
    class CustomSwaggerController extends BaseController
    {
        public function index(Swagger $swagger, string $token): Response
        {
            $swagger->info->title = 'Custom API Title';
            return parent::index($swagger, $token);
        }
    }
    

    Update services.yaml to use your custom controller.

  3. Security:

    • Restrict /_swagger to specific IPs or roles:
      # config/packages/security.yaml
      access_control:
        - { path: ^/_swagger, roles: ROLE_SWAGGER }
      
    • Use Symfony’s Voter for dynamic token validation.

Config Quirks

  • Case Sensitivity: Ensure SWAGGER_TOKEN in .env matches the case in the request (e.g., ?token=AbC123 vs .env value).
  • Path Traversal: Avoid wildcards in $sources (e.g., */src/**) to prevent unintended file scanning. Stick to explicit paths.
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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