Created
October 25, 2024 08:13
-
-
Save mortenscheel/29f42c5ac7284434aa39a89f83f2dc26 to your computer and use it in GitHub Desktop.
Laravel Http macro that records the raw HTTP request and response to a file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\Providers; | |
use GuzzleHttp\Middleware; | |
use GuzzleHttp\Promise\PromiseInterface; | |
use Illuminate\Http\Client\PendingRequest; | |
use Illuminate\Support\Facades\Http; | |
use Illuminate\Support\ServiceProvider; | |
use Psr\Http\Message\RequestInterface; | |
use Psr\Http\Message\ResponseInterface; | |
class CustomMacroServiceProvider extends ServiceProvider | |
{ | |
public function boot(): void | |
{ | |
Http::macro('recordToFile', function (string $path, bool $append = true): PendingRequest { | |
$middleware = Middleware::tap(after: function ( | |
RequestInterface $request, | |
array $options, | |
PromiseInterface $promise | |
) use ($path, $append) { | |
$fh = fopen($path, $append ? 'ab+' : 'wb'); | |
$record = fn (string $line, bool $newline = true) => fwrite($fh, $line . ($newline ? PHP_EOL : '')); | |
$record(\sprintf('%s %s HTTP/%s', $request->getMethod(), $request->getRequestTarget(), $request->getProtocolVersion())); | |
foreach ($request->getHeaders() as $name => $values) { | |
$record(\sprintf('%s: %s', $name, implode(', ', $values))); | |
} | |
$record(''); | |
$requestStream = $request->getBody(); | |
$requestStream->rewind(); | |
while ($requestStream->eof() !== true) { | |
$record($requestStream->read(1024), false); | |
} | |
$record("\n"); | |
/** @var ResponseInterface $response */ | |
$response = $promise->wait(); | |
$record(\sprintf('HTTP/%s %d %s', $response->getProtocolVersion(), $response->getStatusCode(), $response->getReasonPhrase())); | |
foreach ($response->getHeaders() as $name => $values) { | |
$record(\sprintf('%s: %s', $name, implode(', ', $values))); | |
} | |
$record(''); | |
$responseStream = $response->getBody(); | |
$responseStream->rewind(); | |
while ($responseStream->eof() !== true) { | |
$record($responseStream->read(1024), false); | |
} | |
$record("\n"); | |
fclose($fh); | |
$responseStream->rewind(); | |
$responseStream->rewind(); | |
}); | |
return $this->withMiddleware($middleware); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment