Skip to content

Commit 5556556

Browse files
ProviderCache: Add option to separate cache between providers (#1045)
Add option to separate cache
1 parent dbddb18 commit 5556556

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

src/Provider/Cache/ProviderCache.php

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,16 +40,22 @@ class ProviderCache implements Provider
4040
*/
4141
protected $lifetime;
4242

43+
/**
44+
* If true, include the real provider name into the cache key
45+
*/
46+
private bool $separateCache;
47+
4348
/**
4449
* @param Provider $realProvider
4550
* @param CacheInterface $cache
4651
* @param int $lifetime
4752
*/
48-
final public function __construct(Provider $realProvider, CacheInterface $cache, int $lifetime = null)
53+
final public function __construct(Provider $realProvider, CacheInterface $cache, int $lifetime = null, bool $separateCache = false)
4954
{
5055
$this->realProvider = $realProvider;
5156
$this->cache = $cache;
5257
$this->lifetime = $lifetime;
58+
$this->separateCache = $separateCache;
5359
}
5460

5561
/**
@@ -104,7 +110,8 @@ final public function __call($method, $args)
104110
*/
105111
protected function getCacheKey($query): string
106112
{
107-
// Include the major version number of the geocoder to avoid issues unserializing.
108-
return 'v4'.sha1((string) $query);
113+
// Include the major version number of the geocoder to avoid issues unserializing
114+
// and real provider name if we want to separate cache
115+
return 'v4'.sha1((string) $query.($this->separateCache ? $this->realProvider->getName() : ''));
109116
}
110117
}

src/Provider/Cache/Tests/ProviderCacheTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,4 +157,33 @@ public function testReverseHit()
157157
$providerCache = new ProviderCache($this->providerMock, $this->cacheMock, $ttl);
158158
$providerCache->reverseQuery($query);
159159
}
160+
161+
public function testCacheSeparation()
162+
{
163+
$query = GeocodeQuery::create('foo');
164+
$ttl = 4711;
165+
166+
$this->providerMock->expects($this->any())
167+
->method('getName')
168+
->willReturn('foo');
169+
170+
$getCacheKey = self::getMethod('getCacheKey');
171+
172+
$providerCache = new ProviderCache($this->providerMock, $this->cacheMock, $ttl);
173+
$providerCacheWithSeparation = new ProviderCache($this->providerMock, $this->cacheMock, $ttl, true);
174+
175+
$this->assertNotEquals(
176+
$getCacheKey->invokeArgs($providerCache, [$query]),
177+
$getCacheKey->invokeArgs($providerCacheWithSeparation, [$query])
178+
);
179+
}
180+
181+
protected static function getMethod($name)
182+
{
183+
$class = new \ReflectionClass(ProviderCache::class);
184+
$method = $class->getMethod($name);
185+
$method->setAccessible(true);
186+
187+
return $method;
188+
}
160189
}

0 commit comments

Comments
 (0)