1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Wolnosciowiec\WebProxy\Providers\Proxy; |
4
|
|
|
|
5
|
|
|
use Doctrine\Common\Cache\Cache; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Adds a cache layer to the proxy providers |
9
|
|
|
* ----------------------------------------- |
10
|
|
|
* |
11
|
|
|
* @codeCoverageIgnore |
12
|
|
|
* @package Wolnosciowiec\WebProxy\Providers\Proxy |
13
|
|
|
*/ |
14
|
|
|
class CachedProvider implements ProxyProviderInterface |
15
|
|
|
{ |
16
|
|
|
const CACHE_KEY = 'wolnosciowiec.webproxy.cache'; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var ProxyProviderInterface $provider |
20
|
|
|
*/ |
21
|
|
|
private $provider; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var Cache |
25
|
|
|
*/ |
26
|
|
|
private $cache; |
27
|
|
|
|
28
|
|
|
public function __construct(Cache $cache, ProxyProviderInterface $provider) |
29
|
|
|
{ |
30
|
|
|
if ($provider instanceof $this) { |
31
|
|
|
throw new \InvalidArgumentException('Cannot cache self'); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
$this->cache = $cache; |
35
|
|
|
$this->provider = $provider; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function collectAddresses(): array |
39
|
|
|
{ |
40
|
|
|
if ($this->cache->contains(self::CACHE_KEY)) { |
41
|
|
|
$addresses = $this->getFromCache(); |
42
|
|
|
|
43
|
|
|
if (!empty($addresses)) { |
44
|
|
|
return $addresses; |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$addresses = $this->provider->collectAddresses(); |
49
|
|
|
$this->cacheResult($addresses); |
50
|
|
|
|
51
|
|
|
return $addresses; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @return array |
56
|
|
|
*/ |
57
|
|
|
private function getFromCache(): array |
58
|
|
|
{ |
59
|
|
|
$data = unserialize($this->cache->fetch(self::CACHE_KEY)); |
60
|
|
|
|
61
|
|
|
if ($data['expiration'] <= time()) { |
62
|
|
|
return []; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return $data['data']; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
private function cacheResult(array $addresses) |
69
|
|
|
{ |
70
|
|
|
$this->cache->save(self::CACHE_KEY, serialize([ |
71
|
|
|
'data' => $addresses, |
72
|
|
|
'expiration' => time() + $this->getExpirationTime(), |
73
|
|
|
])); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @return int |
78
|
|
|
*/ |
79
|
|
|
protected function getExpirationTime(): int |
80
|
|
|
{ |
81
|
|
|
return 10 * 60; |
82
|
|
|
} |
83
|
|
|
} |