|
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
|
|
|
|