Last active
August 31, 2018 11:12
-
-
Save macghriogair/4d509c3645b324183f1483ebece7e732 to your computer and use it in GitHub Desktop.
[Geocoder] #laravel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @date 2017-09-26 | |
* @file CacheAwareGeocoder.php | |
* @author Patrick Mac Gregor <[email protected]> | |
*/ | |
namespace Dreipc\Geocoder; | |
use Carbon\Carbon; | |
use Illuminate\Contracts\Cache\Repository as CacheContract; | |
use Spatie\Geocoder\Geocoder; | |
/** | |
* Geocoder decorator that caches queries. | |
*/ | |
class CacheAwareGeocoder implements Geocoder | |
{ | |
const CACHE_KEY = 'geoqueries:'; | |
protected $originalGeocoder; | |
protected $cache; | |
protected $lifetimeDays; | |
public function __construct(Geocoder $originalGeocoder, CacheContract $cache, $lifetimeDays = null) | |
{ | |
$this->originalGeocoder = $originalGeocoder; | |
$this->cache = $cache; | |
$this->lifetimeDays = $lifetimeDays ?: 10; | |
} | |
public function getCoordinatesForQuery($query, $apiKey = null, $language = null, $region = null) | |
{ | |
$key = $this->toKey($query); | |
if ($this->cache->has($key)) { | |
return $this->cache->get($key); | |
} | |
// original query | |
$result = $this->originalGeocoder->getCoordinatesForQuery($query, $apiKey, $language, $region); | |
// cache successful queries only | |
if ($this->isValid($result)) { | |
$expires = $this->expires(); | |
$this->cache->put($key, $result, $expires); | |
} | |
return $result; | |
} | |
protected function toKey($query) : string | |
{ | |
return self::CACHE_KEY . md5($query); | |
} | |
protected function expires() : Carbon | |
{ | |
return Carbon::now()->addDays($this->lifetimeDays); | |
} | |
protected function isValid($result) : bool | |
{ | |
return ! empty($result) && Geocoder::RESULT_NOT_FOUND !== $result['formatted_address']; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment