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

check24/apitk-header-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require check24/apitk-header-bundle
    

    Ensure Check24\ApitkHeaderBundle\Check24ApitkHeaderBundle::class is registered in config/bundles.php.

  2. First Use Case: Inject HeaderInformation into a controller or service to add custom headers to API responses.

    use Check24\ApitkHeaderBundle\HeaderInformation;
    
    public function show(HeaderInformation $headerInformation): array
    {
        $headerInformation->add('api-version', 'v1.0');
        return ['data' => '...'];
    }
    

    This automatically appends x-apitk-api-version: v1.0 to the response.

  3. Where to Look First:

    • Service: HeaderInformation (autowired via Symfony DI).
    • Prefix: All headers are prefixed with x-apitk- by default (configurable via config/packages/check24_apitk_header.yaml).
    • Documentation: Focus on the HeaderInformation class methods (add(), addMultiple(), remove()).

Implementation Patterns

Core Workflows

  1. Dynamic Header Injection: Use HeaderInformation in controllers/services to dynamically set headers based on runtime logic (e.g., pagination metadata, API versioning).

    $headerInformation->add('total-records', $totalRecords);
    $headerInformation->addMultiple([
        'limit' => $limit,
        'offset' => $offset,
    ]);
    
  2. Conditional Headers: Add headers only under specific conditions (e.g., debug mode, feature flags).

    if (app()->environment('dev')) {
        $headerInformation->add('debug-mode', 'enabled');
    }
    
  3. Integration with API Platform: Combine with API Platform’s ApiPlatform\Core\Annotation\ApiResource to expose metadata headers.

    #[ApiResource(
        operations: [
            new Get(collection: true, normalizationContext: ['groups' => ['user:read']]),
        ],
    )]
    class UserEntity {}
    

    Then inject HeaderInformation into the controller handling Get operations.

  4. Event-Driven Headers: Use Symfony events (e.g., kernel.response) to modify headers globally.

    // src/EventListener/HeaderListener.php
    public function onKernelResponse(HeaderInformation $headerInformation, Request $request, Response $response)
    {
        $headerInformation->add('request-id', $request->get('X-Request-ID'));
    }
    
  5. Versioning: Leverage headers for API versioning (e.g., x-apitk-api-version: v2).

    $headerInformation->add('api-version', $this->version);
    

Integration Tips

  • Middleware: Use the bundle alongside middleware (e.g., Symfony\Component\HttpKernel\EventListener\ResponseListener) for cross-cutting header logic.
  • DTOs: Attach headers to DTOs (e.g., via SerializerContextBuilder) for consistent serialization.
  • Testing: Mock HeaderInformation in PHPUnit to verify headers in tests.
    $headerInformation = $this->createMock(HeaderInformation::class);
    $headerInformation->expects($this->once())->method('add')->with('test', 'value');
    

Gotchas and Tips

Pitfalls

  1. Header Prefix Collisions: The default x-apitk- prefix may conflict with other bundles. Override it in config:

    # config/packages/check24_apitk_header.yaml
    check24_apitk_header:
        prefix: 'x-custom-'
    
  2. Late Header Modification: Headers are added before the response is sent. Modifying HeaderInformation after the response is built (e.g., in a post-response event) will have no effect.

    • Fix: Use kernel.response event before the response is sent.
  3. Case Sensitivity: Header names are case-insensitive in HTTP but the bundle treats them as case-sensitive. Use consistent casing (e.g., X-Apitk-Users-Count).

  4. Performance: Avoid adding excessive headers in loops or heavy operations. Batch additions with addMultiple().

  5. Deprecation Bundle Dependency: The README mentions apitk-deprecation-bundle, but it’s a separate package. Ensure it’s installed if using deprecation features:

    composer require check24/apitk-deprecation-bundle
    

Debugging

  • Missing Headers: Verify HeaderInformation is injected correctly and the response isn’t being overridden (e.g., by a Response object returned directly).

    // Bad: Bypasses header injection
    return new Response(json_encode($data));
    
    // Good: Let Symfony handle headers
    return $this->json($data);
    
  • Header Not Showing: Check for typos in header names or prefix conflicts. Use browser dev tools (Network tab) to inspect raw headers.

  • Symfony Version Compatibility: The bundle was last updated in 2022 and may lack support for newer Symfony versions (e.g., 6.x). Test thoroughly or fork the package if needed.

Extension Points

  1. Custom Header Processor: Extend the bundle by creating a custom HeaderInformation service or decorator.

    // src/Service/CustomHeaderInformation.php
    class CustomHeaderInformation extends HeaderInformation
    {
        public function addTimestamp(string $name): void
        {
            $this->add($name, (new \DateTime())->format('c'));
        }
    }
    
  2. Event Subscribers: Subscribe to kernel.response to add headers dynamically based on request/response data.

    // src/EventSubscriber/HeaderSubscriber.php
    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::RESPONSE => 'onKernelResponse',
        ];
    }
    
    public function onKernelResponse(HeaderInformation $headerInformation, Request $request, Response $response)
    {
        $headerInformation->add('content-language', $request->getPreferredLanguage());
    }
    
  3. Configuration Overrides: Override default behavior via config (e.g., disable auto-prefixing):

    check24_apitk_header:
        prefix: null  # Disables prefixing
        headers:
            - 'x-custom-header'
    
  4. Testing Headers: Assert headers in tests using Response assertions:

    $client = static::createClient();
    $client->request('GET', '/api/users');
    $response = $client->getResponse();
    
    $this->assertEquals(
        '15',
        $response->headers->get('x-apitk-users-count')
    );
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui