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

Guzzle History Middleware Laravel Package

csa/guzzle-history-middleware

Capture and inspect Guzzle HTTP request/response history with a middleware you can drop into your handler stack. Useful for testing, debugging, and logging, with upgrade notes and contribution guidelines included.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require csa/guzzle-history-middleware
    

    Add the middleware to your Guzzle client stack:

    use CSA\GuzzleHistoryMiddleware\HistoryMiddleware;
    use GuzzleHttp\HandlerStack;
    
    $stack = HandlerStack::create();
    $stack->push(HistoryMiddleware::history());
    $client = new Client(['handler' => $stack]);
    
  2. First Use Case: Track HTTP request history for debugging or auditing:

    $response = $client->get('https://api.example.com/data');
    $history = HistoryMiddleware::getHistory(); // Retrieve recorded requests/responses
    

Key Entry Points

  • Middleware Initialization: Use HistoryMiddleware::history() to create a recordable middleware.
  • History Retrieval: Call HistoryMiddleware::getHistory() to fetch stored requests/responses.
  • Clear History: Use HistoryMiddleware::clearHistory() to reset the history.

Implementation Patterns

Core Workflow

  1. Middleware Integration:

    $stack = HandlerStack::create();
    $stack->push(HistoryMiddleware::history(), 'history'); // Named middleware for easy removal
    
  2. Request/Response Logging: Automatically captures:

    • Request method, URI, headers, body.
    • Response status, headers, body.
    • Timestamps and duration.
  3. Laravel-Specific Integration:

    // In a Laravel service provider
    $this->app->singleton(GuzzleClient::class, function ($app) {
        $stack = HandlerStack::create();
        $stack->push(HistoryMiddleware::history());
        return new Client(['handler' => $stack]);
    });
    

Advanced Patterns

  • Conditional History:
    $middleware = HistoryMiddleware::history(['enabled' => request()->has('debug')]);
    
  • History Persistence: Store history in a service container or database:
    $history = HistoryMiddleware::getHistory();
    HistoryRepository::save($history);
    
  • Middleware Removal:
    $stack->remove('history'); // Disable history when no longer needed
    

Common Use Cases

  1. Debugging API Calls:
    $response = $client->post('/api/endpoint', ['json' => $data]);
    dd(HistoryMiddleware::getHistory()); // Inspect last request
    
  2. Testing: Verify requests/responses without mocking:
    $history = HistoryMiddleware::getHistory();
    $this->assertCount(1, $history);
    
  3. Audit Logging:
    event(new RequestLogged(HistoryMiddleware::getHistory()));
    

Gotchas and Tips

Pitfalls

  1. Thread Safety:

    • History is stored in static memory. Avoid concurrent requests in multi-threaded environments.
    • Fix: Use a singleton service or database-backed storage.
  2. Memory Leaks:

    • Unbounded history growth can bloat memory.
    • Fix: Limit history size or clear after use:
      HistoryMiddleware::clearHistory();
      
  3. Middleware Order:

    • Place history middleware before retry/redirect middleware to capture original requests.
    • Bad: [retry, history] → Retried requests may appear as separate entries.
    • Good: [history, retry].
  4. Sensitive Data:

    • History includes raw request/response bodies (e.g., passwords, tokens).
    • Fix: Sanitize data before logging:
      $middleware = HistoryMiddleware::history(['sanitize' => true]);
      

Debugging Tips

  • Empty History:

    • Ensure middleware is pushed to the stack before making requests.
    • Verify no other middleware is clearing the history.
  • Incomplete Requests:

    • If requests lack bodies, check if GuzzleHttp\Psr7\Stream objects are being converted to strings. Use:
      HistoryMiddleware::history(['stream_as_string' => true]);
      
  • Performance Overhead:

    • Disable in production:
      $middleware = HistoryMiddleware::history(['enabled' => app()->isLocal()]);
      

Extension Points

  1. Custom History Storage: Override the default static storage:

    HistoryMiddleware::setHistoryStorage(new ArrayHistoryStorage());
    
  2. Filtering History:

    $filtered = array_filter(HistoryMiddleware::getHistory(), function ($entry) {
        return str_contains($entry['request']['uri'], 'api/v1');
    });
    
  3. Event Dispatching: Trigger events on request completion:

    $middleware = HistoryMiddleware::history([
        'on_complete' => function ($history) {
            event(new RequestCompleted($history));
        }
    ]);
    

Laravel-Specific Quirks

  • Service Container Binding: Bind the client with history middleware in a provider:

    $this->app->bind(GuzzleClient::class, function ($app) {
        $stack = HandlerStack::create();
        $stack->push(HistoryMiddleware::history());
        return new Client(['handler' => $stack]);
    });
    
  • Queue Workers: History middleware may interfere with queued jobs. Clear history after processing:

    dispatch(new ProcessOrder($order))->after(function () {
        HistoryMiddleware::clearHistory();
    });
    
  • Testing: Reset history between tests:

    public function setUp(): void {
        parent::setUp();
        HistoryMiddleware::clearHistory();
    }
    
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity