Passed
Push — main ( f2efe3...53dc0a )
by smiley
10:15
created

LoggingClient   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 16
dl 0
loc 37
rs 10
c 2
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A sendRequest() 0 21 3
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
	protected ClientInterface $http;
29
30
	/**
31
	 * LoggingClient constructor.
32
	 */
33
	public function __construct(ClientInterface $http, LoggerInterface $logger = null){
34
		$this->http            = $http;
35
		$this->logger          = $logger ?? new NullLogger;
36
	}
37
38
	/**
39
	 * @inheritDoc
40
	 */
41
	public function sendRequest(RequestInterface $request):ResponseInterface{
42
		$this->logger->debug("\n----HTTP-REQUEST----\n".message_to_string($request));
43
44
		try{
45
			$response = $this->http->sendRequest($request);
46
		}
47
		catch(Throwable $e){
48
			$this->logger->debug("\n----HTTP-ERROR------\n".message_to_string($request));
49
			$this->logger->error($e->getMessage());
50
			$this->logger->error($e->getTraceAsString());
51
52
			if(!$e instanceof ClientExceptionInterface){
53
				throw new ClientException('unexpected exception, does not implement "ClientExceptionInterface": '.get_class($e));  // @codeCoverageIgnore
54
			}
55
56
			throw $e;
57
		}
58
59
		$this->logger->debug("\n----HTTP-RESPONSE---\n".message_to_string($response));
60
61
		return $response;
62
	}
63
64
}
65