Completed
Push — master ( e222bd...a03528 )
by smiley
01:27
created

LoggingClient::sendRequest()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 23
rs 9.552
c 0
b 0
f 0
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