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

cethyworks/swagger-tools-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Prerequisites:

    • Install kleijnweb/swagger-bundle (this package depends on it).
    • Configure kleijnweb/swagger-bundle with a valid swagger.yml (or .json) file.
    • Ensure Doctrine ORM and Symfony’s routing system are set up.
  2. First Command:

    composer require cethyworks/swagger-tools-bundle
    php bin/console swagger:generate:entities swagger.yml YourBundleName
    

    Replace YourBundleName with your target bundle (e.g., ApiBundle).

  3. Verify Output:

    • Check src/YourBundleName/Entity/ for generated Doctrine entities with @ORM\ and @Assert\ annotations.
    • Entities will include UUID-based IDs by default (no relations yet).
  4. Generate Controllers:

    php bin/console swagger:generate:controllers swagger.yml YourBundleName
    
    • Outputs controllers in src/YourBundleName/Controller/ with matching routes and test classes in Tests/.

First Use Case: Rapid API Scaffolding

Use this to bootstrap a CRUD API from a Swagger spec:

  1. Define a swagger.yml with resources (e.g., users, products).
  2. Run the entity generator to create Doctrine models.
  3. Run the controller generator to create API endpoints.
  4. Integrate with kleijnweb/swagger-bundle for automatic route registration and OpenAPI docs.


Implementation Patterns

Workflow: Swagger-Driven Development

  1. Design-First Approach:

    • Write Swagger specs before coding entities/controllers.
    • Use tools like Swagger Editor to validate specs early.
  2. Entity Generation:

    • Input: Swagger definitions or components/schemas.
    • Output: Doctrine entities with:
      • UUID primary keys (@ORM\Id @ORM\GeneratedValue(strategy="UUID")).
      • Field types mapped from Swagger (e.g., integerint, stringstring).
      • Assertions (e.g., @Assert\NotBlank() for required: true).
    • Example:
      # swagger.yml
      definitions:
        User:
          properties:
            email:
              type: string
              format: email
            age:
              type: integer
              minimum: 18
      
      Generates:
      // src/YourBundle/Entity/User.php
      /**
       * @ORM\Entity
       */
      class User {
          /**
           * @ORM\Id
           * @ORM\GeneratedValue(strategy="UUID")
           * @ORM\Column(type="guid")
           */
          private $id;
      
          /**
           * @ORM\Column(type="string", length=255)
           * @Assert\NotBlank
           * @Assert\Email
           */
          private $email;
      
          /**
           * @ORM\Column(type="integer")
           * @Assert\GreaterThan(17)
           */
          private $age;
      }
      
  3. Controller Generation:

    • Input: Swagger paths (e.g., /users, /products).
    • Output: Controller classes with:
      • Methods for each action (GET /usersgetUsers(), POST /userscreateUser()).
      • Route annotations (@Route("/users", name="api_users_get")).
      • Dependency injection for services (e.g., UserRepository).
    • Example:
      # swagger.yml
      paths:
        /users:
          get:
            summary: List users
            responses:
              200:
                description: OK
      
      Generates:
      // src/YourBundle/Controller/UserController.php
      class UserController {
          /**
           * @Route("/users", name="api_users_get", methods={"GET"})
           */
          public function getUsers(UserRepository $repository) {
              return $repository->findAll();
          }
      }
      
  4. Testing:

    • Generates ControllerTest classes with PHPUnit tests for each action.
    • Tests use Client to hit generated routes (e.g., self::$client->request('GET', '/users')).

Integration Tips

  1. Customize Generation:

    • Override generated files by placing them in src/ before running commands.
    • Use --force to regenerate (e.g., swagger:generate:entities --force).
  2. Extend Entities:

    • Add custom methods/annotations after generation.
    • Use traits or inheritance for shared logic (e.g., Timestampable).
  3. Handle Relations Later:

    • The generator skips relations. Manually add @ORM\ManyToOne/@ORM\OneToMany after entities exist.
    • Example:
      /**
       * @ORM\ManyToOne(targetEntity="Product", inversedBy="users")
       */
      private $product;
      
  4. Swagger Bundle Sync:

    • Regenerate controllers after updating swagger.yml to keep routes in sync.
    • Clear cache if routes break:
      php bin/console cache:clear
      
  5. CI/CD Pipeline:

    • Add commands to your deployment script to regenerate files on spec changes:
      php bin/console swagger:generate:entities swagger.yml ApiBundle
      php bin/console swagger:generate:controllers swagger.yml ApiBundle
      


Gotchas and Tips

Pitfalls

  1. No Relation Support:

    • The generator ignores $ref fields in Swagger specs.
    • Workaround: Manually add relations post-generation or use a pre-processor to inline schemas.
  2. UUID Assumption:

    • All entities get UUID IDs. Override if you need auto-increment:
      @ORM\GeneratedValue(strategy="AUTO")
      
  3. Route Naming Conflicts:

    • Generated route names may clash with existing ones (e.g., api_users_get).
    • Fix: Customize route names in Swagger or rename manually.
  4. Swagger Bundle Dependency:

    • The swagger:generate:controllers command requires kleijnweb/swagger-bundle to be configured.
    • Error: No routes found → Ensure swagger-bundle is registered and routes are loaded.
  5. Assertion Limitations:

    • Complex assertions (e.g., custom validators) won’t generate.
    • Workaround: Add them manually or extend the generator (see "Extension Points").

Debugging

  1. Command Errors:

    • Run with -v for verbose output:
      php bin/console swagger:generate:entities swagger.yml ApiBundle -v
      
    • Common issues:
      • Invalid YAML → Validate with yamllint.
      • Missing definitions → Use components/schemas (OpenAPI 3.0).
  2. Generated Code Issues:

    • Check var/cache/dev for compiled routes if controllers fail to register.
    • Clear cache after manual route changes:
      php bin/console cache:pool:clear cache_route_annotation_reader
      
  3. Type Mismatches:

    • Swagger format: date-time → PHP DateTime (works).
    • Swagger type: array → PHP array (but nested objects may break).
    • Fix: Adjust Swagger spec or post-process entities.

Tips

  1. Partial Generation:

    • Generate only specific entities/controllers by filtering Swagger specs:
      # Use a tool like `yq` to extract subsets of swagger.yml
      yq '.definitions | select(.name | contains("User"))' swagger.yml > user-spec.yml
      php bin/console swagger:generate:entities user-spec.yml ApiBundle
      
  2. Custom Templates:

    • Override Twig templates for entities/controllers:
      • Copy from vendor/cethyworks/swagger-tools-bundle/Resources/views/ to templates/swagger-tools/ in your bundle.
      • Example: Customize UserController.php.twig.
  3. Extension Points:

    • Event Listeners: Extend generation via Symfony events (e.g., kernel.request).
    • Custom Annotations: Add logic to inject annotations (e.g., @ApiResource for API Platform):
      // Post-generation hook
      $entity->addAnnotation(new \Doctrine\Common\Annotations\Annotation('ApiResource'));
      
  4. Performance:

    • For large APIs, generate entities/controllers in separate commands to avoid memory issues.
  5. Documentation:

    • Use generated entities/controllers as a reference implementation for your API docs.
    • Sync Swagger specs with generated code to avoid drift:
      # Regenerate Swagger from entities (reverse engineering)
      php bin/console swagger:generate:openapi swagger.yml
      


Config Quirks

  1. Bundle Configuration:
    • No config.yml required, but ensure `kle
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware