-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProviderCache.php
110 lines (93 loc) · 2.53 KB
/
ProviderCache.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
declare(strict_types=1);
/*
* This file is part of the Geocoder package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
namespace Geocoder\Provider\Cache;
use Geocoder\Collection;
use Geocoder\Query\GeocodeQuery;
use Geocoder\Query\ReverseQuery;
use Geocoder\Provider\Provider;
use Psr\SimpleCache\CacheInterface;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class ProviderCache implements Provider
{
/**
* @var Provider
*/
protected $realProvider;
/**
* @var CacheInterface
*/
protected $cache;
/**
* How long a result is going to be cached.
*
* @var int|null
*/
protected $lifetime;
/**
* @param Provider $realProvider
* @param CacheInterface $cache
* @param int $lifetime
*/
final public function __construct(Provider $realProvider, CacheInterface $cache, int $lifetime = null)
{
$this->realProvider = $realProvider;
$this->cache = $cache;
$this->lifetime = $lifetime;
}
/**
* {@inheritdoc}
*/
final public function geocodeQuery(GeocodeQuery $query): Collection
{
$cacheKey = $this->getCacheKey($query);
if (null !== $result = $this->cache->get($cacheKey)) {
return $result;
}
$result = $this->realProvider->geocodeQuery($query);
$this->cache->set($cacheKey, $result, $this->lifetime);
return $result;
}
/**
* {@inheritdoc}
*/
final public function reverseQuery(ReverseQuery $query): Collection
{
$cacheKey = $this->getCacheKey($query);
if (null !== $result = $this->cache->get($cacheKey)) {
return $result;
}
$result = $this->realProvider->reverseQuery($query);
$this->cache->set($cacheKey, $result, $this->lifetime);
return $result;
}
/**
* {@inheritdoc}
*/
public function getName(): string
{
return sprintf('%s (cache)', $this->realProvider->getName());
}
final public function __call($method, $args)
{
return call_user_func_array([$this->realProvider, $method], $args);
}
/**
* @param GeocodeQuery|ReverseQuery $query
*
* @return string
*/
protected function getCacheKey($query): string
{
// Include the major version number of the geocoder to avoid issues unserializing.
return 'v4'.sha1((string) $query);
}
}