friendship ended with social-app. php is my new best friend
1<?php 2/** 3 * Class LoggingClient 4 * 5 * @created 07.08.2019 6 * @author smiley <smiley@chillerlan.net> 7 * @copyright 2019 smiley 8 * @license MIT 9 */ 10declare(strict_types=1); 11 12namespace chillerlan\HTTP\Utils\Client; 13 14use chillerlan\HTTP\Utils\MessageUtil; 15use Psr\Http\Client\{ClientExceptionInterface, ClientInterface}; 16use Psr\Http\Message\{RequestInterface, ResponseInterface}; 17use Psr\Log\{LoggerInterface, NullLogger}; 18use RuntimeException, Throwable; 19use function sprintf; 20 21/** 22 * a silly logging wrapper (do not use in production!) 23 * 24 * @codeCoverageIgnore 25 */ 26class LoggingClient implements ClientInterface{ 27 28 protected ClientInterface $http; 29 protected LoggerInterface $logger; 30 31 /** 32 * LoggingClient constructor. 33 */ 34 public function __construct(ClientInterface $http, LoggerInterface $logger = new NullLogger){ 35 $this->http = $http; 36 $this->logger = $logger; 37 } 38 39 public function setLogger(LoggerInterface $logger):static{ 40 $this->logger = $logger; 41 42 return $this; 43 } 44 45 public function sendRequest(RequestInterface $request):ResponseInterface{ 46 47 try{ 48 $this->logger->debug(sprintf("\n----HTTP-REQUEST----\n%s", MessageUtil::toString($request))); 49 50 $response = $this->http->sendRequest($request); 51 52 $this->logger->debug(sprintf("\n----HTTP-RESPONSE---\n%s", MessageUtil::toString($response))); 53 } 54 catch(Throwable $e){ 55 $this->logger->error($e->getMessage()); 56 $this->logger->error($e->getTraceAsString()); 57 58 if(!$e instanceof ClientExceptionInterface){ 59 $msg = 'unexpected exception, does not implement "ClientExceptionInterface": "%s"'; 60 61 throw new RuntimeException(sprintf($msg, $e::class)); 62 } 63 64 throw $e; 65 } 66 67 return $response; 68 } 69 70}