Base::getResult()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 2
dl 0
loc 23
rs 9.552
c 0
b 0
f 0
1
<?php
2
3
namespace Netgen\Bundle\OpenWeatherMapBundle\Core;
4
5
use Netgen\Bundle\OpenWeatherMapBundle\Cache\HandlerInterface;
6
use Netgen\Bundle\OpenWeatherMapBundle\Exception\NotAuthorizedException;
7
use Netgen\Bundle\OpenWeatherMapBundle\Exception\NotFoundException;
8
use Netgen\Bundle\OpenWeatherMapBundle\Http\HttpClientInterface;
9
10
abstract class Base
11
{
12
    /**
13
     * @var \Netgen\Bundle\OpenWeatherMapBundle\Cache\HandlerInterface
14
     */
15
    protected $cacheService;
16
17
    /**
18
     * @var string
19
     */
20
    protected $apiKey;
21
22
    /**
23
     * @var \Netgen\Bundle\OpenWeatherMapBundle\Http\HttpClientInterface
24
     */
25
    protected $client;
26
27
    /**
28
     * Weather constructor.
29
     *
30
     * @param \Netgen\Bundle\OpenWeatherMapBundle\Http\HttpClientInterface $client
31
     * @param string $apiKey
32
     * @param \Netgen\Bundle\OpenWeatherMapBundle\Cache\HandlerInterface $cacheService
33
     */
34
    public function __construct(HttpClientInterface $client, $apiKey, HandlerInterface $cacheService)
35
    {
36
        $this->apiKey = $apiKey;
37
        $this->cacheService = $cacheService;
38
        $this->client = $client;
39
    }
40
41
    /**
42
     * Helper method.
43
     *
44
     * @param string $baseUrl
45
     * @param string $queryPart
46
     *
47
     * @throws NotFoundException
48
     * @throws NotAuthorizedException
49
     *
50
     * @return mixed
51
     */
52
    protected function getResult($baseUrl, $queryPart)
53
    {
54
        $url = $baseUrl . $queryPart;
55
56
        $hash = md5($url);
57
58
        if ($this->cacheService->has($hash)) {
59
            return $this->cacheService->get($hash);
60
        }
61
        $response = $this->client->get($url);
62
63
        if (!$response->isAuthorized()) {
64
            throw new NotAuthorizedException($response->getMessage());
65
        }
66
67
        if (!$response->isOk()) {
68
            throw new NotFoundException($response->getMessage());
69
        }
70
71
        $this->cacheService->set($hash, (string) $response);
72
73
        return (string) $response;
74
    }
75
}
76