/** * Save item to cache * @param string $key * @param mixed $value * @param array $arr_options - Optional * Options: ttl => Overwrite configured ttl with set value. Reverts to configured ttl once completed */ public function setCacheItem($key, $value, $arr_options = array()) { //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 { /** * Overwrite ttl */ if (is_numeric($arr_options["ttl"])) { $old_ttl = $this->storageFactory->getOptions()->getTtl(); $this->storageFactory->getOptions()->setTtl((int) $arr_options["ttl"]); $this->storageFactory->setItem($key, $value); //reset ttl $this->storageFactory->getOptions()->setTtl($old_ttl); return; } //end if $this->storageFactory->setItem($key, $value); } catch (\Exception $e) { trigger_error($e->getMessage(), E_USER_WARNING); } //end catch }
/** * @param $entity * * @return mixed * @throws \InvalidArgumentException If the ResultSetPrototype is not Hydrating * @throws \InvalidArgumentException If a BaseEntity object is not provided */ public function persist($entity) { if (!$this->getResultSetPrototype() instanceof HydratingResultSet) { throw new \InvalidArgumentException('Result Set Prototype is not configured correctly'); } if (!$entity instanceof BaseEntity) { throw new \InvalidArgumentException('Can only persist object entities'); } $hydrator = $this->getResultSetPrototype()->getHydrator(); $data = $hydrator->extract($entity); $sql = $this->getSql(); $identifierName = $this->getIdentifierName(); $identifier = null; if (array_key_exists($identifierName, $data)) { $identifier = $data[$identifierName]; unset($data[$identifierName]); } array_walk($data, function (&$value) { if ($value instanceof \DateTime) { $value = $value->format('Y-m-d H:i:s'); } }); if (!empty($identifier)) { // UPDATE $data['lastModified'] = date('Y-m-d H:i:s'); $where = array(); $where[$identifierName] = $identifier; $statement = $sql->prepareStatementForSqlObject($sql->update()->set($data)->where($where)); $result = $statement->execute(); unset($statement, $result); // cleanup } else { // INSERT $data['createdDatetime'] = date('Y-m-d H:i:s'); $data['status'] = '1'; $data['lastModified'] = date('Y-m-d H:i:s'); $insert = $sql->insert(); $insert->values($data); $statement = $sql->prepareStatementForSqlObject($insert); $result = $statement->execute(); $identifier = $result->getGeneratedValue(); unset($statement, $result); // cleanup $where = array(); $where[$identifierName] = $identifier; } // refresh data $statement = $sql->prepareStatementForSqlObject($this->sql->select()->where($where)); $result = $statement->execute(); $rowData = $result->current(); unset($statement, $result); // cleanup $hydrator->hydrate($rowData, $entity); if ($this->cacheAdapter instanceof CacheAdapter) { $this->cacheAdapter->setItem($this->getCacheKeyHash($entity->getId()), $entity); } return $entity; }
/** * @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; }
/** * Cache Response for future requests * * @param MvcEvent $e * @return \Zend\Stdlib\ResponseInterface */ public function onFinish(MvcEvent $e) { $request = $e->getRequest(); if (!$request instanceof HttpRequest) { return; } if (!$request->isGet()) { return; } $response = $e->getResponse(); if ($response instanceof HttpResponse && !$response->isOk()) { return; } // Do not continue if weren't able to compose a key if (empty($this->cache_key)) { return; } if (!$this->cacheAdapter->hasItem($this->cache_key)) { $resourceIdentifier = $e->getRouteMatch()->getParam('resource'); $resource = call_user_func($this->getResourceLocatorService(), $resourceIdentifier); if (!$resource instanceof Resource || !$resource->isCacheable()) { return; } // Generate Response cache headers based on Resource CacheOptions $cacheOptions = $resource->getCacheOptions(); $cacheControl = new CacheControl(); $cacheControl->addDirective($cacheOptions->getAccess()); $cacheControl->addDirective('max-age', $cacheOptions->getMaxAge()); $cacheControl->addDirective('expires', $cacheOptions->getExpires()); $cacheControl->addDirective('must-revalidate'); $dateTime = new \DateTime(); $dateTime->modify('+ ' . $cacheOptions->getExpires() . 'seconds'); $expires = new Expires(); $expires->setDate($dateTime); $lastModified = new LastModified(); $lastModified->setDate(new \DateTime()); // Add Headers to Response Header $response->getHeaders()->addHeader($cacheControl); $response->getHeaders()->addHeader($expires); $response->getHeaders()->addHeaderLine('Pragma: ' . $cacheOptions->getAccess()); $response->getHeaders()->addHeader(Etag::fromString('Etag: ' . md5($response->getBody()))); $response->getHeaders()->addHeader($lastModified); // Set cache adapter's TTL using Resource cache expires value $this->cacheAdapter->getOptions()->setTtl($cacheOptions->getExpires()); $this->cacheAdapter->setItem($this->cache_key, $response); //return $response; } }
/** * 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()))); }
/** * 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; }
/** * Store an item. * * @param string $key * @param mixed $value * @return bool * @throws Exception\ExceptionInterface * * @triggers setItem.pre(PreEvent) * @triggers setItem.post(PostEvent) * @triggers setItem.exception(ExceptionEvent) */ public function setItem($key, $value) { $options = $this->getOptions(); if ($options->getWritable() && $options->getClearStatCache()) { clearstatcache(); } return parent::setItem($key, $value); }
/** * 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; }
/** * @param $token * @return void */ private function setTokenToCache($token) { $this->cache->setItem($this->getCacheKey(), $token); }
/** * Store an item. * * Options: * - namespace <string> optional * - The namespace to use (Default: namespace of object) * - tags <array> optional * - An array of tags * * @param string $key * @param mixed $value * @param array $options * @return boolean * @throws Exception\ExceptionInterface * * @triggers setItem.pre(PreEvent) * @triggers setItem.post(PostEvent) * @triggers setItem.exception(ExceptionEvent) */ public function setItem($key, $value, array $options = array()) { $baseOptions = $this->getOptions(); if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { clearstatcache(); } return parent::setItem($key, $value, $options); }
/** * @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); } }