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

Apitk Deprecation Bundle Laravel Package

check24/apitk-deprecation-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require check24/apitk-deprecation-bundle
    

    Ensure check24/apitk-deprecation-bundle is added to config/bundles.php if using Symfony Flex.

  2. First Use Case: Mark an existing API endpoint as deprecated in your controller using the @Deprecated annotation:

    use Shopping\ApiTKDeprecationBundle\Annotation\Deprecated;
    
    

/**

  • @Rest\Get("/v1/old-endpoint")
  • @Deprecated(description="Use /v2/new-endpoint instead") */ public function oldEndpointAction() { // Existing logic }
    
    
  1. Verify:
    • Check the Swagger/OpenAPI documentation to confirm the deprecation notice appears.
    • Test the endpoint with a tool like Postman or cURL to verify the x-apitk-deprecated header is included in the response.

Implementation Patterns

Usage Patterns

  1. Gradual Deprecation Workflow:

    • Phase 1: Mark the old endpoint with @Deprecated(since="YYYY-MM-DD", description="...").
    • Phase 2: Update clients to use the new endpoint while keeping the old one functional.
    • Phase 3: Set removedAfter="YYYY-MM-DD" to inform clients of the final removal date.
    • Phase 4: Remove the old endpoint after the removedAfter date.
  2. Documentation Integration:

    • Use hideFromDocs=true to exclude deprecated endpoints from Swagger/OpenAPI docs while keeping them functional for existing clients.
    • Example:
      @Deprecated(hideFromDocs=true, description="Internal use only")
      
  3. Batch Deprecation:

    • Apply the @Deprecated annotation to multiple endpoints in a single controller or service class for consistency.
    • Example:
      /**
       * @Rest\Get("/v1/users/{id}")
       * @Deprecated(description="Use /v2/users/{id} instead")
       */
      public function getUserAction($id) { ... }
      
      /**
       * @Rest\Post("/v1/users")
       * @Deprecated(description="Use /v2/users instead")
       */
      public function createUserAction() { ... }
      
  4. Custom Deprecation Messages:

    • Override the default deprecated header value by providing a description in the annotation.
    • Example:
      @Deprecated(description="Endpoint retired. Contact support for migration assistance.")
      

Integration Tips

  1. API Versioning:

    • Combine with API versioning (e.g., /v1/, /v2/) to clearly separate deprecated and active endpoints.
    • Example:
      @Rest\Get("/v1/legacy-data")
      @Deprecated(removedAfter="2023-12-31", description="Use /v2/data instead")
      
  2. Automated Testing:

    • Write tests to verify the x-apitk-deprecated header is included in responses for deprecated endpoints.
    • Example (using PHPUnit):
      public function testDeprecatedEndpointHeaders()
      {
          $response = $this->client->request('GET', '/v1/old-endpoint');
          $this->assertEquals(
              'Use /v2/new-endpoint instead',
              $response->headers->get('x-apitk-deprecated')
          );
      }
      
  3. Logging Deprecation Warnings:

    • Log calls to deprecated endpoints to track adoption and plan removal:
      public function oldEndpointAction()
      {
          \Log::warning('Deprecated endpoint called: /v1/old-endpoint');
          // ...
      }
      
  4. Swagger UI Customization:

    • Customize the Swagger UI to highlight deprecated endpoints visually (e.g., using CSS or JavaScript).
    • Example: Add a filter to show only non-deprecated endpoints by default.

Gotchas and Tips

Pitfalls

  1. Annotation Parsing Issues:

    • Ensure the nelmio/api-doc-bundle or equivalent bundle is installed and configured to parse annotations like @Deprecated. Without it, the deprecation headers won’t be added.
    • Fix: Verify nelmio_api_doc is enabled in config/bundles.php and annotations are processed.
  2. Header Overrides:

    • Custom middleware or filters might override or remove the x-apitk-deprecated header. Ensure such middleware runs after the apitk-deprecation-bundle middleware.
    • Fix: Reorder middleware in kernel.php or AppKernel.php:
      $middleware->prepend(\Shopping\ApiTKDeprecationBundle\Middleware\DeprecationMiddleware::class);
      
  3. Date Format Strictness:

    • The since and removedAfter arguments must use the YYYY-MM-DD format. Invalid formats may cause parsing errors.
    • Fix: Validate dates before applying the annotation or handle exceptions in middleware.
  4. Caching Headers:

    • If your API uses caching (e.g., Varnish, Redis), ensure cached responses include the x-apitk-deprecated header. Otherwise, clients may not see deprecation notices.
    • Fix: Configure cache headers to preserve custom headers like x-apitk-deprecated.
  5. Annotation Placement:

    • The @Deprecated annotation must be placed above the method or class it applies to. Placing it inside the method body or on properties will have no effect.
    • Fix: Double-check annotation placement in your IDE (e.g., PHPStorm highlights invalid annotations).

Debugging

  1. Missing Headers:

    • If headers aren’t appearing, check:
      • The annotation is correctly applied.
      • The bundle is enabled in config/bundles.php.
      • No middleware is stripping custom headers.
    • Debug Tip: Temporarily add a dd() or var_dump() in the bundle’s middleware to confirm it’s being triggered.
  2. Swagger Docs Not Updating:

    • Clear the Swagger cache or regenerate the OpenAPI spec:
      php bin/console nelmio:apidoc:generate
      
    • Debug Tip: Check the generated openapi.yaml or swagger.json for deprecation tags.
  3. Deprecated Endpoint Still Accessible:

    • If the endpoint should be removed but isn’t, ensure:
      • The removedAfter date has passed.
      • No route or controller logic is bypassing the deprecation check.
    • Debug Tip: Temporarily add a throw new \RuntimeException('Deprecated endpoint called!'); to confirm the endpoint is still reachable.

Tips

  1. Consistent Naming:

    • Use a consistent naming convention for deprecated endpoints (e.g., /v1/old-*/v2/new-*). This makes it easier for clients to migrate.
  2. Deprecation Timeline:

    • Follow a standard deprecation timeline (e.g., 6 months notice, 3 months grace period) to give clients ample time to migrate.
  3. Client-Side Handling:

    • Provide client libraries or SDKs that automatically handle deprecation warnings (e.g., log warnings or redirect calls to new endpoints).
  4. Monitor Adoption:

    • Use analytics or logging to track how many clients are still using deprecated endpoints. This helps prioritize support and removal efforts.
  5. Extend the Bundle:

    • Override the bundle’s middleware or event listeners to add custom logic (e.g., send emails to clients using deprecated endpoints).
    • Example: Extend the DeprecationMiddleware to log IP addresses or user agents:
      namespace App\Middleware;
      
      use Shopping\ApiTKDeprecationBundle\Middleware\DeprecationMiddleware as BaseMiddleware;
      use Psr\Log\LoggerInterface;
      
      class CustomDeprecationMiddleware extends BaseMiddleware
      {
          protected $logger;
      
          public function __construct(LoggerInterface $logger)
          {
              $this->logger = $logger;
          }
      
          public function handle($request, \Closure $next)
          {
              $response = parent::handle($request, $next);
              if ($this->isDeprecated($request)) {
                  $this->logger->warning(
                      'Deprecated endpoint called by IP: ' . $request->getClientIp()
                  );
              }
              return $response;
          }
      }
      
  6. Deprecation in Tests:

    • Mock or stub deprecated endpoints in tests to avoid flaky tests due to deprecation headers.
    • Example (using PHPUnit):
      $this->client->getContainer()->get('apitk_deprecation.listener')->setDeprecatedEndpoints([]);
      
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