<?php
namespace App\Utils\HttpTransfer; class GuzzleRequestWithLogging { private $request = null; private $response = null; private $responseBody = null; private $logContext = []; public function getLastRequest(): \GuzzleHttp\Psr7\Request { return $this->request; } public function getLastResponse(): \GuzzleHttp\Psr7\Response { return $this->response; } public function getLastResponseBody(): string|null { return $this->responseBody; } public function getLogContext(): array { return $this->logContext; } protected function buildGuzzleSyncClient(): \GuzzleHttp\Client { $handlerStack = \GuzzleHttp\HandlerStack::create(); $handlerStack->push( \GuzzleHttp\Middleware::tap( function ($request, array $options) { $this->logContext = [ 'request' => new \Engine\Logger\Context\GuzzleTransfer($request, (string)$request->getBody()), 'response' => null, 'duration' => null, '_startTime' => microtime(true), ]; }, function ($request, array $options, $response) { $duration = microtime(true) - $this->logContext['_startTime']; unset($this->logContext['_startTime']); $exception = null; if ($response instanceof \GuzzleHttp\Promise\PromiseInterface) { try { $response = $response->wait(); } catch (\GuzzleHttp\Exception\GuzzleException $ex) { $exception = $ex; $response = null; } } $responseObj = null; $responseStr = null; if ($response) { if ($response instanceof \Psr\Http\Message\ResponseInterface) { $responseObj = $response; $responseStr = (string)$response->getBody(); } elseif ($response instanceof \GuzzleHttp\Exception\RequestException && $response->getResponse()) { $responseObj = $response->getResponse(); $responseStr = (string)$response->getResponse()->getBody(); } $this->logContext['response'] = new \Engine\Logger\Context\GuzzleTransfer($responseObj, $responseStr); } if ($exception) { $this->logContext['exception'] = new \Engine\Logger\Context\ExceptionAsHtml($exception); } $this->logContext['duration'] = $duration; $this->response = $responseObj; $this->responseBody = $responseStr; } ) ); return new \GuzzleHttp\Client([ 'handler' => $handlerStack, ]); } public function send($method, $url, $headers=[], $body=null, $options=[]): string|null { if (!isset($headers['User-Agent'])) { $headers['User-Agent'] = 'GuzzleRequestWithLogging'; } if (!isset($options['timeout'])) { $options['timeout'] = 10; } if (!isset($options['connect_timeout'])) { $options['connect_timeout'] = 5; } $this->request = new \GuzzleHttp\Psr7\Request($method, $url, $headers, $body); $this->response = $this->buildGuzzleSyncClient()->send($this->request, $options); return $this->responseBody; } } 