1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace daib17\Model; |
4
|
|
|
|
5
|
|
|
use Anax\Commons\ContainerInjectableInterface; |
6
|
|
|
use Anax\Commons\ContainerInjectableTrait; |
7
|
|
|
|
8
|
|
|
class ForecastAPI implements ContainerInjectableInterface |
9
|
|
|
{ |
10
|
|
|
use ContainerInjectableTrait; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @var string $curl custom cURL |
14
|
|
|
* @var string $lat latitude |
15
|
|
|
* @var string $lon longitude |
16
|
|
|
*/ |
17
|
|
|
private $lat; |
18
|
|
|
private $lon; |
19
|
|
|
private $curl; |
20
|
|
|
|
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Constructor |
24
|
|
|
*/ |
25
|
5 |
|
public function __construct($curl, $lat, $lon) |
26
|
|
|
{ |
27
|
5 |
|
$this->curl = $curl; |
28
|
5 |
|
$this->lat = $lat; |
29
|
5 |
|
$this->lon = $lon; |
30
|
5 |
|
} |
31
|
|
|
|
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Make API request for the given period. |
35
|
|
|
* |
36
|
|
|
* @param string $period 0: this week, 1: last 30 days |
37
|
|
|
*/ |
38
|
5 |
|
public function request($period) |
39
|
|
|
{ |
40
|
5 |
|
if ($period == 0) { |
41
|
|
|
// This week |
42
|
4 |
|
$res = $this->curl->request('https://api.darksky.net/forecast/' . |
43
|
4 |
|
$this->getApiKey() . '/' . $this->lat . ',' . $this->lon . '?units=si'); |
44
|
|
|
} else { |
45
|
|
|
// Last 30 days |
46
|
1 |
|
$res = $this->multi(30); |
47
|
|
|
} |
48
|
|
|
|
49
|
5 |
|
return $res; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Multiple concurrent requests for the number of given days in the past. |
55
|
|
|
* |
56
|
|
|
* @param int $numDays number of days |
57
|
|
|
* |
58
|
|
|
* @return array Array containing results from multiple requests |
59
|
|
|
*/ |
60
|
1 |
|
public function multi($numDays) |
61
|
|
|
{ |
62
|
1 |
|
$urlArr = []; |
63
|
1 |
|
for ($i = 1; $i < $numDays + 1; $i++) { |
64
|
1 |
|
$time = date(strtotime("-" . $i . " days", time())); |
65
|
1 |
|
$urlArr[] = 'https://api.darksky.net/forecast/' . |
66
|
1 |
|
$this->getApiKey() . '/' . $this->lat . ',' . $this->lon . ',' . $time . '?units=auto'; |
67
|
|
|
} |
68
|
|
|
|
69
|
1 |
|
return $this->curl->multi($urlArr); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Check whether Latitude and Longitude are valid. |
75
|
|
|
* |
76
|
|
|
* @return boolean true if valid, false otherwise |
77
|
|
|
*/ |
78
|
2 |
|
public function isValid() |
79
|
|
|
{ |
80
|
2 |
|
return $this->lat >= -90 && $this->lat <= 90 && |
81
|
2 |
|
$this->lon >= -180 && $this->lon <= 180; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* Get API access key from configuration file. |
87
|
|
|
*/ |
88
|
5 |
|
public function getApiKey() |
89
|
|
|
{ |
90
|
5 |
|
$cfg = $this->di->get("configuration"); |
91
|
5 |
|
$config = $cfg->load("apikeys.php"); |
92
|
5 |
|
return $config["config"]["darksky"]; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|