@@ -15,6 +15,7 @@ class IPinfo
1515 const API_URL = 'https://ipinfo.io ' ;
1616 const CACHE_MAXSIZE = 4096 ;
1717 const CACHE_TTL = 86400 ; // 24 hours as seconds
18+ const CACHE_KEY_VSN = '1 ' ; // update when cache vals change for same key.
1819 const COUNTRIES_FILE_DEFAULT = __DIR__ . '/countries.json ' ;
1920 const REQUEST_TYPE_GET = 'GET ' ;
2021 const STATUS_CODE_QUOTA_EXCEEDED = 429 ;
@@ -97,8 +98,9 @@ public function formatDetailsObject($details = [])
9798 */
9899 public function getRequestDetails (string $ ip_address )
99100 {
100- if ($ this ->cache ->has ($ ip_address )) {
101- return $ this ->cache ->get ($ ip_address );
101+ $ cachedRes = $ this ->cache ->get ($ this ->cacheKey ($ ip_address ));
102+ if ($ cachedRes != null ) {
103+ return $ cachedRes ;
102104 }
103105
104106 $ url = self ::API_URL ;
@@ -127,7 +129,7 @@ public function getRequestDetails(string $ip_address)
127129 }
128130
129131 $ raw_details = json_decode ($ response ->getBody (), true );
130- $ this ->cache ->set ($ ip_address , $ raw_details );
132+ $ this ->cache ->set ($ this -> cacheKey ( $ ip_address) , $ raw_details );
131133
132134 return $ raw_details ;
133135 }
@@ -160,4 +162,14 @@ private function readCountryNames($countries_file)
160162 $ file_contents = file_get_contents ($ countries_file );
161163 return json_decode ($ file_contents , true );
162164 }
165+
166+ /**
167+ * Returns a versioned cache key given a user-input key.
168+ * @param string key to transform into a versioned cache key.
169+ * @return string the versioned cache key.
170+ */
171+ private function cacheKey ($ k )
172+ {
173+ return sprintf ('%s:%s ' , $ k , self ::CACHE_KEY_VSN );
174+ }
163175}
0 commit comments