/** * Returns sizes array for photo identified by Flickr photo id * * @param int $photoId * @return array Array of photo size information */ public function getSizes($photoId) { $sizes = $this->adapter->getItem($photoId); if (is_null($sizes)) { $sizes = $this->flickr->getSizes($photoId); $this->adapter->addItem($photoId, $sizes); } return $sizes; }
public function testGetItemCallsInternalGetItem() { $this->_storage = $this->getMockForAbstractAdapter(array('internalGetItem')); $key = 'key1'; $result = 'value1'; $this->_storage->expects($this->once())->method('internalGetItem')->with($this->equalTo($key))->will($this->returnValue($result)); $rs = $this->_storage->getItem($key); $this->assertEquals($result, $rs); }
/** * @inheritdoc */ public function build() { if ($this->built) { return; } $key = 'assets-manager'; if ($this->cacheAdapter->hasItem($key)) { $data = $this->cacheAdapter->getItem($key); $assetManager = unserialize($data); if ($assetManager instanceof AssetManager) { $this->setAssetManager($assetManager); return; } } parent::build(); $this->cacheAdapter->setItem($key, serialize($this->getAssetManager())); $this->built = true; }
/** * Read an item from the cache * @param string $key * @param string $default_value * @return string|\Zend\Cache\Storage\Adapter\mixed */ public function readCacheItem($key, $default_value = FALSE) { //check if caching is enabled $arr_config = $this->getServiceLocator()->get("config"); if ($arr_config["front_end_application_config"]["cache_enabled"] == FALSE) { return FALSE; } //end if //adjust key $key = $this->setIdentifier($key); try { if (!$this->storageFactory->getItem($key)) { return $default_value; } //end if return $this->storageFactory->getItem($key); } catch (\Exception $e) { trigger_error($e->getMessage(), E_USER_WARNING); } //end catch return $default_value; }
/** * Intercept Dispatch and determine * if a cached response for this route * is available. * * Retrieve and return response if available * shortcutting to Finish event * * @param MvcEvent $e * @return mixed */ public function onDispatch(MvcEvent $e) { $request = $e->getRequest(); if (!$request instanceof HttpRequest) { return; } if (!$request->isGet()) { return; } $response = $e->getResponse(); if ($response instanceof HttpResponse && !$response->isOk()) { return; } $resourceIdentifier = $e->getRouteMatch()->getParam('resource'); $params = ArrayUtils::merge($e->getRouteMatch()->getParams(), $request->getQuery()->toArray()); $this->cache_key = $this->composeKey($params); // Do not continue if we cannot compose a key if (empty($this->cache_key)) { return; } if ($this->cacheAdapter->hasItem($this->cache_key)) { $cachedResponse = $this->cacheAdapter->getItem($this->cache_key); if ($cachedResponse instanceof HttpResponse) { $resource = call_user_func($this->getResourceLocatorService(), $resourceIdentifier); if (!$resource instanceof Resource) { return; } $modifiedSince = $request->getHeader('If-Modified-Since'); if ($modifiedSince instanceof IfModifiedSince) { $headers = $cachedResponse->getHeaders(); $lastModified = $headers->get('Last-Modified'); if (!$lastModified instanceof LastModified) { $lastModified = new LastModified(); $headers->addHeader($lastModified); } $age = $lastModified->date()->getTimestamp() - $modifiedSince->date()->getTimestamp(); $maxAge = $resource->getCacheOptions()->getMaxAge(); if ($age < $maxAge && $maxAge >= 1) { $lastModified->setDate($modifiedSince->date()); $cachedResponse->setStatusCode(HttpResponse::STATUS_CODE_304); $cachedResponse->setContent(null); return $cachedResponse; } } //return $cachedResponse; } } }
/** * Displays a list of the most recent feeds, reverse date order, to the user. * * It's intended as a starting off point to the rest of the application. * * @return array|ViewModel */ public function indexAction() { if (!is_null($this->_cache)) { if (!$this->_cache->hasItem(self::KEY_ALL_RESULTS)) { $resultset = $this->_feedTable->fetchMostRecentFeeds(self::DEFAULT_FEED_COUNT); $this->_cache->setItem(self::KEY_ALL_RESULTS, $resultset->toArray()); } else { $resultset = $this->_cache->getItem(self::KEY_ALL_RESULTS); } } else { $resultset = $this->_feedTable->fetchMostRecentFeeds(self::DEFAULT_FEED_COUNT); } $paginator = $this->getPaginator($resultset); $paginator->setCurrentPageNumber($this->params()->fromRoute('page', self::DEFAULT_PAGE)); $paginator->setItemCountPerPage($this->params()->fromRoute('perPage', self::DEFAULT_RECORDS_PER_PAGE)); return new ViewModel(array('paginator' => $paginator, 'feedCount' => self::DEFAULT_FEED_COUNT, 'messages' => array('info' => $this->flashMessenger()->hasInfoMessages(), 'error' => $this->flashMessenger()->hasErrorMessages()))); }
/** * @param $id * * @return array|\ArrayObject|bool|null */ public function getEntityByIdentifier($id) { if ($this->cacheAdapter instanceof CacheAdapter) { if ($this->cacheAdapter->hasItem($this->getCacheKeyHash($id))) { $entity = $this->cacheAdapter->getItem($this->getCacheKeyHash($id)); return $entity; } } $rowset = $this->select(array($this->getIdentifierName() => $id)); $entity = $rowset->current(); if (!$entity) { return false; } if ($this->cacheAdapter instanceof CacheAdapter) { $this->cacheAdapter->setItem($this->getCacheKeyHash($id), $entity); } return $entity; }
/** * @param string $request Request uri * @throws \RuntimeException * @return \Zend\Http\PhpEnvironment\Response */ public function dispatch($request) { if (!$this->getResolver()) { throw new \RuntimeException("No resolver setted"); } $asset = $this->resolver->resolve($request); $content = null; $responseCode = 404; $headers = Headers::fromString("Content-Type: text/plain"); if ($asset) { $headers = $this->getHeaders($asset->getFile(), $asset->getMime()); if ($this->browserCached($asset->getFile())) { $responseCode = 304; $headers->addHeader(Connection::fromString("Connection: close")); } else { $responseCode = 200; $cacheKey = "assets-cache-" . md5($request); if ($this->cache) { $content = $this->cache->getItem($cacheKey); } if (!$content) { $content = $asset->getContent(); $assetName = end(explode('\\', get_class($asset))); if (array_key_exists($assetName, $this->filters)) { foreach ($this->filters[$assetName] as $filter) { $content = $filter->filter($content); } } if ($this->cache) { $this->cache->addItem($cacheKey, $content); } } } } else { $content = "Asset not found!"; } $response = new Response(); $response->setStatusCode($responseCode); $response->setContent($content); $response->setHeaders($headers); return $response; }
/** * Compile to file. If destination is not specified return CSS. * * @param string $source * @param string|null $destination * @param array|string|null $include Include path(s) to use * @throws \Exception on compilation error * @return string Compiled CSS */ public function compile($source, $destination = null, $include = null) { $include = array_merge($this->includes, (array) $include); $useCache = null == $destination && null !== $this->cache; if ($useCache) { if ($this->cache->hasItem($source)) { return $this->cache->getItem($source); } } $arguments = implode(' ', array_map('escapeshellarg', $this->arguments)); $arguments .= ' ' . $this->getCommandArguments($source, $destination, $include); $command = "{$this->compiler} {$arguments}" . ' 2>&1'; $result = exec($command, $output, $exitCode); if ($exitCode != 0) { throw new \Exception(sprintf('Error compiling CSS "%s": %s', $source, implode(PHP_EOL, $output))); } $css = implode(PHP_EOL, $output); if ($useCache) { $this->cache->setItem($source, $css); } return $css; }
/** * Get an item. * * @param string $key * @param bool $success * @param mixed $casToken * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface * * @triggers getItem.pre(PreEvent) * @triggers getItem.post(PostEvent) * @triggers getItem.exception(ExceptionEvent) */ public function getItem($key, &$success = null, &$casToken = null) { $options = $this->getOptions(); if ($options->getReadable() && $options->getClearStatCache()) { clearstatcache(); } $argn = func_num_args(); if ($argn > 2) { return parent::getItem($key, $success, $casToken); } elseif ($argn > 1) { return parent::getItem($key, $success); } return parent::getItem($key); }
/** * Obtain the authentication to use with the EDS API from cache if it exists. If * not, then generate a new one. * * @param bool $isInvalid whether or not the the current token is invalid * * @return string */ protected function getAuthenticationToken($isInvalid = false) { $token = null; if ($this->ipAuth) { return $token; } if ($isInvalid) { $this->cache->setItem('edsAuthenticationToken', null); } $authTokenData = $this->cache->getItem('edsAuthenticationToken'); if (isset($authTokenData)) { $currentToken = isset($authTokenData['token']) ? $authTokenData['token'] : ''; $expirationTime = isset($authTokenData['expiration']) ? $authTokenData['expiration'] : 0; $this->debugPrint('Cached Authentication data: ' . "{$currentToken}, expiration time: {$expirationTime}"); // Check to see if the token expiration time is greater than the current // time. If the token is expired or within 5 minutes of expiring, // generate a new one. if (!empty($currentToken) && time() <= $expirationTime - 60 * 5) { return $currentToken; } } $username = $this->userName; $password = $this->password; $orgId = $this->orgId; if (!empty($username) && !empty($password)) { $this->debugPrint('Calling Authenticate with username: '******'AuthToken']; $timeout = $results['AuthTimeout'] + time(); $authTokenData = ['token' => $token, 'expiration' => $timeout]; $this->cache->setItem('edsAuthenticationToken', $authTokenData); } return $token; }
/** * @return mixed */ private function getTokenFromCache() { return $this->cache->getItem($this->getCacheKey()); }
/** * Get an item. * * Options: * - ttl <int> optional * - The time-to-life (Default: ttl of object) * - namespace <string> optional * - The namespace to use (Default: namespace of object) * - ignore_missing_items <boolean> optional * - Throw exception on missing item or return false * * @param string $key * @param array $options * @return mixed Data on success and false on failure * @throws Exception\ExceptionInterface * * @triggers getItem.pre(PreEvent) * @triggers getItem.post(PostEvent) * @triggers getItem.exception(ExceptionEvent) */ public function getItem($key, array $options = array()) { $baseOptions = $this->getOptions(); if ($baseOptions->getReadable() && $baseOptions->getClearStatCache()) { clearstatcache(); } return parent::getItem($key, $options); }
/** * Get an item. * * Options: * - ttl <int> optional * - The time-to-life (Default: ttl of object) * - namespace <string> optional * - The namespace to use (Default: namespace of object) * * @param string $key * @param array $options * @param boolean $success * @param mixed $casToken * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface * * @triggers getItem.pre(PreEvent) * @triggers getItem.post(PostEvent) * @triggers getItem.exception(ExceptionEvent) */ public function getItem($key, array $options = array(), & $success = null, & $casToken = null) { $baseOptions = $this->getOptions(); if ($baseOptions->getReadable() && $baseOptions->getClearStatCache()) { clearstatcache(); } return parent::getItem($key, $options, $success, $casToken); }
/** * @return mixed * @throws \Exception * @throws null * * Generic request */ public function request() { if ($this->method == null || empty($this->method)) { throw new \Exception('METHOD is not defined'); } if ($this->uri == null || empty($this->uri)) { throw new \Exception('URI is not defined'); } // return debug information if debug is enabled if ($this->debug) { return $this->debugInfo(); } try { // cache key $cacheKey = $this->generateCacheKey(); // cache if ($this->useCache) { // if cached response is found, return it formatted if ($this->cache->hasItem($cacheKey)) { $response = $this->cache->getItem($cacheKey); return $this->formatResponseToReturn($response); } } // log time (START) $timeStart = microtime(true); // return seeds if present if ($seeds = $this->findSeeds()) { return $seeds; } $request = (new ArtaxRequest())->setUri($this->uri)->setMethod($this->method)->setAllHeaders($this->headers); if ($this->params != null) { $request->setBody(json_encode($this->params)); } // make the request (first attempt) $ampResponse = $this->doRequest($request); // return response if it's not an ArtaxResponse (it could be a string cached in local file) if (!$ampResponse instanceof ArtaxResponse) { return $ampResponse; } // log time (END) $timeEnd = microtime(true); if ($this->config['newrelic'] === true && extension_loaded('newrelic')) { newrelic_custom_metric('Custom/Artax/Load_time', round($timeEnd - $timeStart)); } // code and body $response['code'] = (int) $ampResponse->getStatus(); $response['body'] = json_decode($ampResponse->getBody(), true); // optional headers foreach ($this->headersToReturn as $headerToReturn) { if ($ampResponse->hasHeader($headerToReturn)) { $response['headers'][$headerToReturn] = $ampResponse->getHeader($headerToReturn)[0]; } } // store response in cache if ($this->useCache) { $this->cache->setItem($cacheKey, $response); // TODO cache ttl (set timeout on specific cache key) if ($this->cacheTtl) { } } // seeds $this->writeSeeds($response); // reformat response return $this->formatResponseToReturn($response); } catch (\Exception $error) { throw new \Exception($error); } }