Skip to content

Commit

Permalink
Merge pull request #32 from ipinfo/uman/vsn-cache-keys
Browse files Browse the repository at this point in the history
Implement versioned cache keys.
  • Loading branch information
UmanShahzad authored Apr 22, 2021
2 parents 534131c + 8c8a892 commit 05798eb
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/IPinfo.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class IPinfo
const API_URL = 'https://ipinfo.io';
const CACHE_MAXSIZE = 4096;
const CACHE_TTL = 86400; // 24 hours as seconds
const CACHE_KEY_VSN = '1'; // update when cache vals change for same key.
const COUNTRIES_FILE_DEFAULT = __DIR__ . '/countries.json';
const REQUEST_TYPE_GET = 'GET';
const STATUS_CODE_QUOTA_EXCEEDED = 429;
Expand Down Expand Up @@ -97,8 +98,9 @@ public function formatDetailsObject($details = [])
*/
public function getRequestDetails(string $ip_address)
{
if ($this->cache->has($ip_address)) {
return $this->cache->get($ip_address);
$cachedRes = $this->cache->get($this->cacheKey($ip_address));
if ($cachedRes != null) {
return $cachedRes;
}

$url = self::API_URL;
Expand Down Expand Up @@ -127,7 +129,7 @@ public function getRequestDetails(string $ip_address)
}

$raw_details = json_decode($response->getBody(), true);
$this->cache->set($ip_address, $raw_details);
$this->cache->set($this->cacheKey($ip_address), $raw_details);

return $raw_details;
}
Expand Down Expand Up @@ -160,4 +162,14 @@ private function readCountryNames($countries_file)
$file_contents = file_get_contents($countries_file);
return json_decode($file_contents, true);
}

/**
* Returns a versioned cache key given a user-input key.
* @param string key to transform into a versioned cache key.
* @return string the versioned cache key.
*/
private function cacheKey($k)
{
return sprintf('%s:%s', $k, self::CACHE_KEY_VSN);
}
}

0 comments on commit 05798eb

Please sign in to comment.