BaseApi::callApiUrl()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 11
cts 11
cp 1
rs 9.6
c 0
b 0
f 0
cc 3
nc 4
nop 2
crap 3
1
<?php
2
3
namespace LoLApi\Api;
4
5
use GuzzleHttp\Exception\ClientException;
6
use Psr\Http\Message\ResponseInterface;
7
use LoLApi\ApiClient;
8
use LoLApi\Handler\ClientExceptionHandler;
9
use LoLApi\Result\ApiResult;
10
11
/**
12
 * Class BaseApi
13
 *
14
 * @package LoLApi\Api
15
 */
16
abstract class BaseApi
17
{
18
    /**
19
     * @var ApiClient
20
     */
21
    protected $apiClient;
22
23
    /**
24
     * @param ApiClient $apiClient
25
     */
26 46
    public function __construct(ApiClient $apiClient)
27
    {
28 46
        $this->apiClient = $apiClient;
29 46
    }
30
31
    /**
32
     * @param string $url
33
     * @param array  $queryParameters
34
     *
35
     * @return ApiResult
36
     * @throws \LoLApi\Exception\AbstractRateLimitException
37
     */
38
    protected function callApiUrl($url, array $queryParameters = [])
39
    {
40 48
        $queryParameters = array_merge(['api_key' => $this->apiClient->getApiKey()], $queryParameters);
41
        $fullUrl         = $this->buildUri($url, $queryParameters);
42 48
43 48
        $cacheKey = md5($fullUrl);
44 48
        $item     = $this->apiClient->getCacheProvider()->getItem($cacheKey);
45 48
46
        if ($item->isHit()) {
47 48
            return $this->buildApiResult($fullUrl, json_decode($item->get(), true), true);
48 1
        }
49
50
        try {
51
            $response = $this->apiClient->getHttpClient()->get($fullUrl);
52 47
53
            return $this->buildApiResult($fullUrl, json_decode((string) $response->getBody(), true), false, $response);
54 46
        } catch (ClientException $e) {
55 1
            throw (new ClientExceptionHandler())->handleClientException($e);
56 1
        }
57
    }
58
59
    /**
60
     * @param string $url
61
     * @param array  $queryParameters
62
     *
63
     * @return string
64
     */
65
    protected function buildUri($url, array $queryParameters)
66
    {
67 46
        $baseUrl = $this->apiClient->getBaseUrl();
68
69 46
        return $baseUrl.$url.'?'.http_build_query($queryParameters);
70
    }
71 46
72
    /**
73
     * @param string                 $fullUrl
74
     * @param mixed                  $result
75
     * @param bool                   $fetchedFromCache
76
     * @param ResponseInterface|null $response
77
     *
78
     * @return ApiResult
79
     */
80
    protected function buildApiResult($fullUrl, $result, $fetchedFromCache, ResponseInterface $response = null)
81
    {
82 46
        return (new ApiResult())
83
            ->setResult($result)
84 46
            ->setUrl($fullUrl)
85 46
            ->setHttpResponse($response)
86 46
            ->setFetchedFromCache($fetchedFromCache)
87 46
        ;
88 46
    }
89
}
90