|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Server-side cache for recommendation provider API |
|
4
|
|
|
* |
|
5
|
|
|
* Author: National Research Council Canada |
|
6
|
|
|
* Website: http://www.nrc-cnrc.gc.ca/eng/rd/dt/ |
|
7
|
|
|
* |
|
8
|
|
|
* License: MIT |
|
9
|
|
|
* Copyright: Her Majesty the Queen in Right of Canada, as represented by |
|
10
|
|
|
* the Minister of National Research Council, 2019 |
|
11
|
|
|
*/ |
|
12
|
|
|
|
|
13
|
|
|
namespace NRC; |
|
14
|
|
|
|
|
15
|
|
|
class ApiCache { |
|
16
|
|
|
// Filename to store cache into |
|
17
|
|
|
private $cacheFile = NULL; |
|
18
|
|
|
|
|
19
|
|
|
// Location to store cache files |
|
20
|
|
|
private $cacheFolder = '/tmp/nrc-api-cache/'; |
|
21
|
|
|
|
|
22
|
|
|
// Number of seconds cache is valid |
|
23
|
|
|
private $cacheExpires = 3600; |
|
24
|
|
|
|
|
25
|
|
|
function __construct($signature) { |
|
26
|
|
|
$this->cacheFolder = sys_get_temp_dir() . '/nrc-api-cache/'; |
|
27
|
|
|
if (!file_exists($this->cacheFolder)) { |
|
28
|
|
|
mkdir($this->cacheFolder); |
|
29
|
|
|
} |
|
30
|
|
|
$filename = base64_encode(json_encode($signature)); |
|
31
|
|
|
$this->cacheFile = $this->cacheFolder . $filename; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
public function get($cb) { |
|
35
|
|
|
$cached = false; |
|
36
|
|
|
if (file_exists($this->cacheFile)) { |
|
37
|
|
|
$fp = fopen($this->cacheFile, 'r'); |
|
38
|
|
|
$cacheTime = (int)fgets($fp); |
|
39
|
|
|
if ($cacheTime < (time() + $this->cacheExpires)) { |
|
40
|
|
|
$cached = true; |
|
41
|
|
|
while (($buffer = fgets($fp)) !== false) { |
|
42
|
|
|
yield $buffer; |
|
43
|
|
|
} |
|
44
|
|
|
} |
|
45
|
|
|
fclose($fp); |
|
46
|
|
|
} |
|
47
|
|
|
if (!$cached) { |
|
48
|
|
|
$fp = fopen($this->cacheFile, 'w'); |
|
49
|
|
|
fwrite($fp, time() . "\n"); |
|
50
|
|
|
$data = $cb(); |
|
51
|
|
|
while ($data->valid()) { |
|
52
|
|
|
$output = $data->current(); |
|
53
|
|
|
fwrite($fp, $output . "\n"); |
|
54
|
|
|
yield $output; |
|
55
|
|
|
$data->next(); |
|
56
|
|
|
} |
|
57
|
|
|
fclose($fp); |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
} |