/** * Set the cache value for given key. * * If existing key is provided then the previous value gets overridden * * @param String $key Unique key to identify the cache value * @param String $data Value to be stored in the cache * @param int $cacheTime Time after which cache expires * @param String $cachePath Path where cache needs to be stored */ public static function set($key, $data, $cacheTime = self::CACHE_TIME, $cachePath = null) { if ($cachePath == null) { $cachePath = __DIR__ . self::CACHE_PATH; } $cache = new SimpleCache(); $cache->cache_path = $cachePath; $cache->cache_time = $cacheTime; $cache->set_cache($key, json_encode($data)); }
/** * This method is used to extend an URL if a location header is set in the HTTP Headers * * The method takes the URL that should be extended as a paremter and firstly builds a cacheName by the URL, because * if caching is activated the library tries to get the result of the method from cache instead of requesting it * newly every time. If caching is activated the method get_cache of the caching class is used to try to get cache * data. If cached data is available it is returned. Otherwise a new request is made using the request method of Guzzle. * At this state it's possible that Exceptions are thrown due to HTTP Stauts codes so a Client and Server Exception * is caught and thrown again as URLExtenderException. If no exception is thrown and caching isn't activated * the location parameter (if present) is returned, otherwise the original URL. If caching is activated the location * is saved to cache and then returned * * @see SimpleCache::get_cache * @see SimpleCache::set_cache * @see MessageInterface::getHeaderline * @see ClientException * @see ServerException * * @param $url * @return bool|string * @throws URLExtenderException */ public function extendURL($url) { if (filter_var($url, FILTER_VALIDATE_URL) === false) { throw new URLExtenderException('Invalid URL'); } $cacheName = $this->getCacheName($url); if ($this->usingCache === true) { $location = $this->cache->get_cache($cacheName); if ($location !== false) { return $location; } } try { $result = $this->request($url); $location = $result->getHeaderLine('Location') !== '' ? $result->getHeaderLine('Location') : $url; if ($this->usingCache !== true) { return $location; } $this->cache->set_cache($cacheName, $location); return $location; } catch (ClientException $e) { throw new URLExtenderException($e->getMessage(), $e->getCode()); } catch (ServerException $e) { throw new URLExtenderException($e->getMessage(), $e->getCode()); } }
/** * Gets cached data * * @return $this * @throws DataNotLoadedException */ protected function withCache() { $this->type = 'fromCache'; $data = $this->cache->is_cached($this->label) ? $this->cache->get_cache($this->label) : false; $this->data = $data ? json_decode($data, true) : false; if (!$this->data) { $this->cache->set_cache($this->label, json_encode($this->withoutCache()->get())); } return $this; }