Always use the cache

If there is no cache available we will use the null cache. Which (you
guessed it) just doesn't do anything. This makes the code flow a bit
nicer and psalm a bit happier.

Signed-off-by: Roeland Jago Douma <roeland@famdouma.nl>
This commit is contained in:
Roeland Jago Douma 2021-02-11 11:48:52 +01:00
parent d5dea10517
commit bf4210aa8d
1 changed files with 18 additions and 23 deletions

View File

@ -72,9 +72,6 @@ class WeatherStatusService {
/** @var IAppManager */ /** @var IAppManager */
private $appManager; private $appManager;
/** @var ICacheFactory */
private $cacheFactory;
/** @var ICache */ /** @var ICache */
private $cache; private $cache;
@ -116,9 +113,7 @@ class WeatherStatusService {
$this->version = $appManager->getAppVersion(Application::APP_ID); $this->version = $appManager->getAppVersion(Application::APP_ID);
$this->clientService = $clientService; $this->clientService = $clientService;
$this->client = $clientService->newClient(); $this->client = $clientService->newClient();
if ($cacheFactory->isAvailable()) { $this->cache = $cacheFactory->createDistributed('weatherstatus');
$this->cache = $cacheFactory->createDistributed();
}
} }
/** /**
@ -397,12 +392,12 @@ class WeatherStatusService {
* @return array which contains the error message or the parsed JSON result * @return array which contains the error message or the parsed JSON result
*/ */
private function requestJSON(string $url, array $params = []): array { private function requestJSON(string $url, array $params = []): array {
if (isset($this->cache)) {
$cacheKey = $url . '|' . implode(',', $params) . '|' . implode(',', array_keys($params)); $cacheKey = $url . '|' . implode(',', $params) . '|' . implode(',', array_keys($params));
if ($this->cache->hasKey($cacheKey)) { $cacheValue = $this->cache->get($cacheKey);
return $this->cache->get($cacheKey); if ($cacheValue !== null) {
} return $cacheValue;
} }
try { try {
$options = [ $options = [
'headers' => [ 'headers' => [
@ -425,7 +420,7 @@ class WeatherStatusService {
return ['error' => $this->l10n->t('Error')]; return ['error' => $this->l10n->t('Error')];
} else { } else {
$json = json_decode($body, true); $json = json_decode($body, true);
if (isset($this->cache)) {
// default cache duration is one hour // default cache duration is one hour
$cacheDuration = 60 * 60; $cacheDuration = 60 * 60;
if (isset($headers['Expires']) && count($headers['Expires']) > 0) { if (isset($headers['Expires']) && count($headers['Expires']) > 0) {
@ -438,7 +433,7 @@ class WeatherStatusService {
} }
} }
$this->cache->set($cacheKey, $json, $cacheDuration); $this->cache->set($cacheKey, $json, $cacheDuration);
}
return $json; return $json;
} }
} catch (\Exception $e) { } catch (\Exception $e) {