PHP Debug Bar Guzzle Integration

493 Views Asked by At

What would be the best way to log all guzzle requests to the php debugbar?

Normally there would be some type of event that is fired which I could listen for and pass the data to a collector for the debug bar. However, guzzle doesn't seem to have any events. Instead it is using middle ware and handlers which I don't quite understand how I would integrate with the debugbar to log requests and timeline, execution duration info to the debug bar.

1

There are 1 best solutions below

0
On

I think I have mostly figured this out.

I created my own middleware and registered it with the client.

Custom middleware.

use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Rocket\Cockpit\Facade\Container;
use Rocket\Moc\Debugbar\MocDebugBar;

class GuzzleHttpMiddleware {

    /** @var callable  */
    private $nextHandler;

    /**
     * @param callable $nextHandler Next handler to invoke.
     */
    public function __construct(callable $nextHandler) {
        $this->nextHandler = $nextHandler;
    }

    /**
     * @param RequestInterface $request
     * @param array            $options
     *
     * @return PromiseInterface
     */
    public function __invoke(RequestInterface $request, array $options)
    {
        $fn = $this->nextHandler;
        $debugbar = Container::get(MocDebugBar::class);

        $debugbar['rest']->addRequest($request);

        return $fn($request, $options)
            ->then(function (ResponseInterface $response) use ($request, $options) {

                return $response;

            });

    }

}

Registering custom middleware with handler stack – PHP League container used.

// Register http client.
$this->getContainer()->share(Client::class,function() {

    // In theory this "should" be available
    $config = load_class('Config');

    // Add debugbar middleware to handler stack.
    $stack = HandlerStack::create();
    $stack->after('prepare_body',function(callable $handler) {
        return new GuzzleHttpMiddleware($handler);
    },'debugbar');

    $client = new Client([
        'base_uri'=> $config->item('service_url'),
        'handler'=> $stack,
    ]);

    return $client;
},true);

I was having a difficult time understanding the workflow of the handlers and promises until I actually looked into the promise library alone. Once I did that everything made much more sense.