Client::createHttpRequest()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
1
<?php
2
3
namespace Viktoras\Scryfall\Client;
4
5
use Psr\Http\Client\ClientExceptionInterface;
6
use Psr\Http\Client\ClientInterface;
7
use Psr\Http\Message\RequestFactoryInterface;
8
use Psr\Http\Message\RequestInterface as HttpRequestInterface;
9
use Viktoras\Scryfall\Client\Request\RequestInterface;
10
use Viktoras\Scryfall\Client\Response\ErrorResponse;
11
use Viktoras\Scryfall\Client\Response\GenericResponse;
12
use Viktoras\Scryfall\Client\Response\ResponseInterface;
13
14
class Client
15
{
16
    /**
17
     * @var ClientInterface
18
     */
19
    private $client;
20
21
    /**
22
     * @var RequestFactoryInterface
23
     */
24
    private $requestFactory;
25
26
    /**
27
     * @var string
28
     */
29
    private $baseUrl;
30
31
    public function __construct(
32
        string $baseUrl,
33
        ClientInterface $client,
34
        RequestFactoryInterface $requestFactory
35
    ) {
36
        $this->baseUrl        = rtrim($baseUrl, '/') . '/';
37
        $this->client         = $client;
38
        $this->requestFactory = $requestFactory;
39
    }
40
41
    private function createHttpRequest(RequestInterface $request): HttpRequestInterface
42
    {
43
        return $this->requestFactory->createRequest(
44
            $request->getMethod(),
45
            $this->baseUrl . $request->getQuery()
46
        );
47
    }
48
49
    /**
50
     * @throws ClientExceptionInterface
51
     */
52
    public function request(RequestInterface $request): ResponseInterface
53
    {
54
        $response = $this->client->sendRequest(
55
            $this->createHttpRequest($request)
56
        );
57
58
        $body = $response->getBody()->getContents();
59
60
        if ($response->getStatusCode() !== 200) {
61
            return new ErrorResponse($body);
62
        }
63
64
        $responseClass = str_replace(
65
            __NAMESPACE__ . '\\Request\\',
66
            __NAMESPACE__ . '\\Response\\',
67
            get_class($request)
68
        );
69
70
        if (!class_exists($responseClass)) {
71
            return new GenericResponse($body);
72
        }
73
74
        /** @var ResponseInterface */
75
        return new $responseClass($body);
76
    }
77
}
78