Completed
Push — master ( 988ea9...868c80 )
by smiley
07:26
created

LoggingClient   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
dl 0
loc 45
rs 10
c 0
b 0
f 0
wmc 4
lcom 1
cbo 6
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 Psr\Http\Client\{ClientExceptionInterface, ClientInterface};
18
use Psr\Http\Message\{RequestInterface, ResponseInterface};
19
use Psr\Log\{LoggerAwareInterface, LoggerAwareTrait, LoggerInterface, NullLogger};
20
use Throwable;
21
22
use function chillerlan\HTTP\Psr7\message_to_string;
23
use function get_class;
24
25
class LoggingClient implements ClientInterface, LoggerAwareInterface{
26
	use LoggerAwareTrait;
27
28
	/** @var \Psr\Http\Client\ClientInterface */
29
	protected ClientInterface $http;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
30
31
	/**
32
	 * LoggingClient constructor.
33
	 *
34
	 * @param \Psr\Http\Client\ClientInterface                $http
35
	 * @param \Psr\Log\LoggerInterface|null                   $logger
36
	 */
37
	public function __construct(ClientInterface $http, LoggerInterface $logger = null){
38
		$this->http            = $http;
39
		$this->logger          = $logger ?? new NullLogger;
40
	}
41
42
	/**
43
	 * @inheritDoc
44
	 */
45
	public function sendRequest(RequestInterface $request):ResponseInterface{
46
		$this->logger->debug("\n----HTTP-REQUEST----\n".message_to_string($request));
47
48
		try{
49
			$response = $this->http->sendRequest($request);
50
		}
51
		catch(Throwable $e){
52
			$this->logger->debug("\n----HTTP-ERROR------\n".message_to_string($request));
53
			$this->logger->error($e->getMessage());
54
			$this->logger->error($e->getTraceAsString());
55
56
			if(!$e instanceof ClientExceptionInterface){
57
				throw new ClientException('unexpected exception, does not implement "ClientExceptionInterface": '.get_class($e));  // @codeCoverageIgnore
58
			}
59
60
			/** @noinspection PhpUnhandledExceptionInspection */
61
			throw $e;
62
		}
63
64
		$this->logger->debug("\n----HTTP-RESPONSE---\n".message_to_string($response));
65
66
		return $response;
67
	}
68
69
}
70