-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathEmissions.php
executable file
·78 lines (62 loc) · 1.73 KB
/
Emissions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
namespace KateMorley\Grid\Data;
use KateMorley\Grid\Database;
/** Updates emissions data. */
class Emissions {
public const KEYS = [
'emissions'
];
/**
* Updates the emissions data.
*
* @param Database $database The database instance
*
* @throws DataException If the data was invalid
*/
public static function update(Database $database): void {
$rawData = @file_get_contents(
sprintf(
'https://api.carbonintensity.org.uk/intensity/%s/pt24h',
gmdate('Y-m-d\\TH:i:s\\Z')
)
);
if ($rawData === false) {
throw new DataException('Failed to read data');
}
$jsonData = json_decode($rawData, true);
if (!isset($jsonData['data']) || !is_array($jsonData['data'])) {
throw new DataException('Missing data');
}
$data = [];
foreach ($jsonData['data'] as $item) {
if (!is_array($item)) {
throw new DataException('Invalid item');
}
$data[] = self::getDatum($item);
}
$database->update(self::KEYS, $data);
}
/**
* Returns the datum for an item.
*
* @param array $item The item
*
* @throws DataException If the data was invalid
*/
private static function getDatum(array $item): array {
if (!isset($item['from'])) {
throw new DataException('Missing time');
}
if (
!isset($item['intensity']['actual'])
&& !isset($item['intensity']['forecast'])
) {
throw new DataException('Missing emissions value');
}
$emissions = $item['intensity']['actual'] ?? $item['intensity']['forecast'];
if (!is_int($emissions)) {
throw new DataException('Invalid emissions value: ' . $emissions);
}
return [Time::normalise($item['from'], 30), $emissions];
}
}