1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Class LoggingClient |
4
|
|
|
* |
5
|
|
|
* a silly logging wrapper (do not use in production!) |
6
|
|
|
* |
7
|
|
|
* @filesource LoggingClient.php |
8
|
|
|
* @created 07.08.2019 |
9
|
|
|
* @package chillerlan\HTTP\Psr18 |
10
|
|
|
* @author smiley <[email protected]> |
11
|
|
|
* @copyright 2019 smiley |
12
|
|
|
* @license MIT |
13
|
|
|
*/ |
14
|
|
|
|
15
|
|
|
namespace chillerlan\HTTP\Psr18; |
16
|
|
|
|
17
|
|
|
use chillerlan\HTTP\Psr17\ResponseFactory; |
18
|
|
|
use Psr\Http\Client\{ClientExceptionInterface, ClientInterface}; |
19
|
|
|
use Psr\Http\Message\{RequestInterface, ResponseFactoryInterface, ResponseInterface}; |
20
|
|
|
use Psr\Log\{LoggerAwareInterface, LoggerAwareTrait, LoggerInterface, NullLogger}; |
21
|
|
|
use Throwable; |
22
|
|
|
|
23
|
|
|
use function chillerlan\HTTP\Psr7\message_to_string; |
24
|
|
|
use function get_class; |
25
|
|
|
|
26
|
|
|
class LoggingClient implements ClientInterface, LoggerAwareInterface{ |
27
|
|
|
use LoggerAwareTrait; |
28
|
|
|
|
29
|
|
|
/** @var \Psr\Http\Client\ClientInterface */ |
30
|
|
|
protected $http; |
31
|
|
|
/** @var \Psr\Http\Message\ResponseFactoryInterface|null */ |
32
|
|
|
protected $responseFactory; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* LoggingClient constructor. |
36
|
|
|
* |
37
|
|
|
* @param \Psr\Http\Client\ClientInterface $http |
38
|
|
|
* @param \Psr\Log\LoggerInterface|null $logger |
39
|
|
|
* @param \Psr\Http\Message\ResponseFactoryInterface|null $responseFactory |
40
|
|
|
*/ |
41
|
|
|
public function __construct(ClientInterface $http, LoggerInterface $logger = null, ResponseFactoryInterface $responseFactory = null){ |
42
|
|
|
$this->http = $http; |
43
|
|
|
$this->logger = $logger ?? new NullLogger; |
44
|
|
|
$this->responseFactory = $responseFactory ?? new ResponseFactory; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @inheritDoc |
49
|
|
|
*/ |
50
|
|
|
public function sendRequest(RequestInterface $request):ResponseInterface{ |
51
|
|
|
$this->logger->debug("\n----HTTP-REQUEST----\n".message_to_string($request)); |
52
|
|
|
|
53
|
|
|
try{ |
54
|
|
|
$response = $this->http->sendRequest($request); |
55
|
|
|
} |
56
|
|
|
catch(Throwable $e){ |
57
|
|
|
$this->logger->debug("\n----HTTP-ERROR------\n".message_to_string($request)); |
58
|
|
|
$this->logger->error($e->getMessage()); |
59
|
|
|
$this->logger->error($e->getTraceAsString()); |
60
|
|
|
|
61
|
|
|
if(!$e instanceof ClientExceptionInterface){ |
62
|
|
|
throw new ClientException('unexpected exception, does not implement "ClientExceptionInterface": '.get_class($e)); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** @noinspection PhpUnhandledExceptionInspection */ |
66
|
|
|
throw $e; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
$this->logger->debug("\n----HTTP-RESPONSE---\n".message_to_string($response)); |
70
|
|
|
|
71
|
|
|
return $response; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
} |
75
|
|
|
|