Completed
Pull Request — master (#9)
by Hugo
01:41
created

AbstractClient::getMessageFactory()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yproximite\Api\Client;
6
7
use Http\Client\HttpClient;
8
use Http\Discovery\MessageFactoryDiscovery;
9
use Http\Message\MessageFactory;
10
use Psr\Http\Message\RequestInterface;
11
use Psr\Http\Message\ResponseInterface;
12
use Yproximite\Api\Exception\AuthenticationException;
13
use Yproximite\Api\Exception\InvalidResponseException;
14
15
abstract class AbstractClient
16
{
17
    private $httpClient;
18
    private $messageFactory;
19
20
    public function __construct(HttpClient $httpClient = null, MessageFactory $messageFactory = null)
21
    {
22
        $this->httpClient     = $httpClient;
23
        $this->messageFactory = $messageFactory;
24
    }
25
26
    protected function getHttpClient(): HttpClient
27
    {
28
        if (null === $this->httpClient) {
29
            $this->httpClient = MessageFactoryDiscovery::find();
30
        }
31
32
        return $this->httpClient;
33
    }
34
35
    protected function getMessageFactory(): MessageFactory
36
    {
37
        if (null === $this->messageFactory) {
38
            $this->messageFactory = MessageFactoryDiscovery::find();
39
        }
40
41
        return $this->messageFactory;
42
    }
43
44
    protected function createRequest(string $method, string $url, array $headers = [], $body = null): RequestInterface
45
    {
46
        return $this->getMessageFactory()->createRequest($method, $url, $headers, $body);
47
    }
48
49
    /**
50
     * @throws AuthenticationException
51
     * @throws InvalidResponseException
52
     * @throws \Http\Client\Exception
53
     */
54
    protected function sendRequest(RequestInterface $request): ResponseInterface
55
    {
56
        $response = $this->getHttpClient()->sendRequest($request);
57
58
        if (401 === $response->getStatusCode()) {
59
            throw new AuthenticationException('Your API key is not valid.', $request, $response);
60
        }
61
62
        $this->extractJson($request, $response);
63
64
        return $response;
65
    }
66
67
    /**
68
     * @throws InvalidResponseException
69
     */
70
    protected function extractJson(RequestInterface $request, ResponseInterface $response): array
71
    {
72
        $body = (string) $response->getBody();
73
        $body = trim($body);
74
        $json = json_decode($body, true);
75
76
        if (!\in_array($body[0], ['{', '['], true) || JSON_ERROR_NONE !== json_last_error()) {
77
            throw new InvalidResponseException('Could not decode response.', $request, $response);
78
        }
79
80
        return $json;
81
    }
82
}
83