|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Onlime\LaravelHttpClientGlobalLogger; |
| 4 | + |
| 5 | +use Exception; |
| 6 | +use Illuminate\Http\Client\Events\RequestSending; |
| 7 | +use Illuminate\Http\Client\Events\ResponseReceived; |
| 8 | +use Psr\Http\Message\RequestInterface; |
| 9 | +use Psr\Http\Message\ResponseInterface; |
| 10 | +use Saloon\HttpSender\HttpSender; |
| 11 | +use Saloon\Laravel\Events\SendingSaloonRequest; |
| 12 | +use Saloon\Laravel\Events\SentSaloonRequest; |
| 13 | + |
| 14 | +class EventHelper |
| 15 | +{ |
| 16 | + public static function shouldBeLogged(object $event): bool |
| 17 | + { |
| 18 | + // Do not log Saloon requests if Saloon is configured to use Laravel's HTTP Client (HttpSender) unless the |
| 19 | + // Saloon request is mocked (has a MockClient). Like this, we prevent duplicate logging of Saloon requests, |
| 20 | + // as we're also listening to Laravel's HTTP Client events RequestSending and ResponseReceived. |
| 21 | + if ($event instanceof SendingSaloonRequest || $event instanceof SentSaloonRequest) { |
| 22 | + $saloonUsesHttpSender = config('saloon.default_sender') === HttpSender::class; |
| 23 | + return $event->pendingRequest->hasMockClient() || ! $saloonUsesHttpSender; |
| 24 | + } |
| 25 | + |
| 26 | + return true; |
| 27 | + } |
| 28 | + |
| 29 | + public static function getPsrRequest(object $event): RequestInterface |
| 30 | + { |
| 31 | + return match (true) { |
| 32 | + $event instanceof RequestSending || $event instanceof ResponseReceived => $event->request->toPsrRequest(), |
| 33 | + $event instanceof SendingSaloonRequest || $event instanceof SentSaloonRequest => $event->pendingRequest->createPsrRequest(), |
| 34 | + default => throw new Exception('Can not get PSR Request from Event: '.get_class($event)), |
| 35 | + }; |
| 36 | + } |
| 37 | + |
| 38 | + public static function getPsrResponse(object $event): ResponseInterface |
| 39 | + { |
| 40 | + return match (true) { |
| 41 | + $event instanceof ResponseReceived => $event->response->toPsrResponse(), |
| 42 | + $event instanceof SentSaloonRequest => $event->response->getPsrResponse(), |
| 43 | + default => throw new Exception('Can not get PSR Response from Event: '.get_class($event)), |
| 44 | + }; |
| 45 | + } |
| 46 | +} |
0 commit comments