/** * Starts the output cache. Returns Nette\Caching\OutputHelper object if buffering was started. * @param Nette\Caching\IStorage * @param string * @param Nette\Caching\OutputHelper[] * @param array * @return Nette\Caching\OutputHelper */ public static function createCache(Nette\Caching\IStorage $cacheStorage, $key, &$parents, array $args = NULL) { if ($args) { if (array_key_exists('if', $args) && !$args['if']) { return $parents[] = new \stdClass(); } $key = array_merge([$key], array_intersect_key($args, range(0, count($args)))); } if ($parents) { end($parents)->dependencies[Nette\Caching\Cache::ITEMS][] = $key; } $cache = new Nette\Caching\Cache($cacheStorage, 'Nette.Templating.Cache'); if ($helper = $cache->start($key)) { if (isset($args['dependencies'])) { $args += call_user_func($args['dependencies']); } if (isset($args['expire'])) { $args['expiration'] = $args['expire']; // back compatibility } $helper->dependencies = [Nette\Caching\Cache::TAGS => isset($args['tags']) ? $args['tags'] : NULL, Nette\Caching\Cache::EXPIRATION => isset($args['expiration']) ? $args['expiration'] : '+ 7 days']; $parents[] = $helper; } return $helper; }
private function loadNavigationFromCache($navigationId) { return $this->cache->load("nav-{$navigationId}", function (&$dependencies) use($navigationId) { $nodes = $this->navigationReader->getEntireNavigation($navigationId); return $this->treeBuilder->buildTree($nodes); }); }
public function import() { $projects = $this->projectEntity->fetchPairs("name", null); $statusNewRow = $this->lstErrorStatus->findOneBy(array("status" => "New")); foreach ($projects as $projectName => $index) { $fileList = $this->dataSource->getFileList("{$projectName}/exception"); foreach ($fileList as $file) { if (pathinfo($file->name, PATHINFO_EXTENSION) != "html") { continue; } $errorRow = $this->errorEntity->findOneBy(array("source_file" => $file->name)); if (!$errorRow) { try { $errorFileContent = $this->dataSource->getFileContent($file->name); $archiveFilePath = $this->dataSource->moveToArchive($file->name); $this->exceptionParser->parse($errorFileContent); $errorMessage = $this->exceptionParser->getMessage(); $title = $this->exceptionParser->getTitle(); $errorRow = $this->errorEntity->insert(array("project_id" => $projects[$projectName]->id, "error_status_id" => $statusNewRow->id, "title" => $title, "message" => $this->exceptionParser->getMessage(), "source_file" => $this->exceptionParser->getSourceFile(), "remote_file" => $archiveFilePath, "error_dt" => $file->lastModified, "ins_process_id" => __METHOD__)); $link = "http://" . $_SERVER["HTTP_HOST"] . "/error-list/display/" . $errorRow->id; $this->hipChat->sendMessage("<b>{$projectName}</b> - {$title} - {$errorMessage} <a href=\"{$link}\">Show!</a>"); } catch (InvalidArgumentException $e) { // file does not exists in source, how it can happen? That's the question, he? } } } } $this->cache->save("lastUpdate", new \DateTime()); }
public function loadEntityConfig($entity, $mergeWithLabelExtensions = TRUE) { $cacheKey = $entity; $cache = new Cache($this->context->cacheStorage, self::CACHE_NAMESPACE); $val = $cache->load($cacheKey); if ($val === NULL) { $params = $this->context->getParameters(); $configFile = $params['projectDir'] . '/config/entities/' . $entity . '.neon'; if (!is_file($configFile)) { throw new \Nette\FileNotFoundException("Entity config file '{$configFile}' was not found"); } $loader = new Nette\Config\Loader(); $entityConfig = $loader->load($configFile); if ($mergeWithLabelExtensions) { $labelProperties = $this->loadLabelExtentsionProperties(); array_walk($entityConfig['properties'], function (&$item) use($labelProperties) { // if entity params contains reference to ext, expand it if (isset($item['extName'])) { if (isset($labelProperties['properties'][$item['extName']])) { $extParam = $labelProperties['properties'][$item['extName']]; $item = array_merge($extParam, $item); } } }); } $dp = array(Cache::FILES => array($configFile, CONFIG_DIR . '/labels/labelExtensions.neon', $params['projectDir'] . '/config/labels/labelExtensions.neon')); $cache->save($cacheKey, $entityConfig, $dp); $val = $entityConfig; } return $val; }
public function actionDefault() { $cache = new Cache($this->context->cacheStorage, 'Homepage'); $counts = $cache->load('homepagecounts'); if ($counts === NULL) { $subjectsCount = $this->context->createServicePlaces()->fetchVisible()->count(); $eventsCount = $this->context->createServiceTimes()->fetchPublic()->group('event_time.event_id')->count(); $categoriesCount = $this->context->createServiceCategories()->where('subject', '1')->count(); $counts = array('sc' => $subjectsCount, 'ec' => $eventsCount, 'cc' => $categoriesCount); $cache->save('homepagecounts', $counts, array(Cache::EXPIRE => '1 hour', Cache::SLIDING => true, Cache::TAGS => array('event', 'events', 'places', 'place'))); } $this->template->subjectsCount = $counts['sc']; $this->template->eventsCount = $counts['ec']; $this->template->categoriesCount = $counts['cc']; $def = $cache->load('homepagecities'); if ($def === NULL) { $res = Model\Subjects::fetchLocalitiesToCities(); $cnt = 0; foreach ($res as $r) { $cnt = $cnt + $r['cnt']; } $def = array($res, $cnt); $cache->save('homepagecities', $def, array('expire' => 100000, 'tags' => 'cities')); } $this->template->cities = $def[0]; $this->template->citiesCount = $def[1]; $this->template->circles = $this->context->createServiceCircles()->order('shift')->where('visible', 1)->limit(4); }
/** * Search configuration files. * @param mixed * @param mixed */ public function addFindConfig($dirs, $exclude = NULL) { $cache = new Caching\Cache(new Caching\Storages\FileStorage($this->getCacheDirectory()), self::Caching); // Search will be started only when the cache does not exist. if (!$cache->load(self::Caching)) { // Search configuration files. foreach (Utils\Finder::findFiles('*.neon')->from($dirs)->exclude($exclude) as $row) { $data[] = $row->getPathname(); } foreach ($data as $row) { $name[] = basename($row); } // Sort found files by number and put into the cache. array_multisort($name, SORT_NUMERIC, $data); if (isset($data)) { $cache->save(self::Caching, $data); } } // Loads the data from the cache. if ($cache->load(self::Caching)) { foreach ($cache->load(self::Caching) as $files) { $this->addConfig($files); } } }
public function load($key, $callback) { return $this->cache->load($key, function (&$dependencies) use($callback) { $dependencies = $this->dependencies; return call_user_func($callback); }); }
public function findEventsByType($logTypeID) { return $this->cache->load('logEvents-' . $logTypeID, function (&$dependencies) use($logTypeID) { return array_column($this->em->createQuery('SELECT e.id, e.name FROM ' . EventLog::class . ' e INDEX BY e.id WHERE e.logType = :typeID')->setParameter('typeID', $logTypeID)->getArrayResult(), 'name', 'id'); }); }
/** * @param Url $oldUrl * @param Url $newUrl * @return void * @throws \Exception */ public function linkUrls(Url $oldUrl, Url $newUrl) { if ($oldUrl->getId() === null or $newUrl->getId() === null) { throw new UrlNotPersistedException(); } try { $this->em->beginTransaction(); $alreadyRedirectedUrls = $this->findByActualUrl($oldUrl->getId()); /** @var Url $url */ foreach ($alreadyRedirectedUrls as $url) { $url->setRedirectTo($newUrl); $this->em->persist($url); $this->cache->clean([Cache::TAGS => [$url->getCacheKey()]]); } $oldUrl->setRedirectTo($newUrl); $this->em->persist($oldUrl); $this->cache->clean([Cache::TAGS => [$oldUrl->getCacheKey()]]); $this->em->flush(); $this->em->commit(); } catch (\Exception $e) { $this->em->rollback(); $this->em->close(); throw $e; } }
/** * @param \Nette\DI\Container $dic * @throws MemberAccessException * @internal */ public function injectComponentFactories(Nette\DI\Container $dic) { if (!$this instanceof Nette\Application\UI\PresenterComponent && !$this instanceof Nette\Application\UI\Component) { throw new MemberAccessException('Trait ' . __TRAIT__ . ' can be used only in descendants of PresenterComponent.'); } $this->autowireComponentFactoriesLocator = $dic; $storage = $dic->hasService('autowired.cacheStorage') ? $dic->getService('autowired.cacheStorage') : $dic->getByType('Nette\\Caching\\IStorage'); $cache = new Nette\Caching\Cache($storage, 'Kdyby.Autowired.AutowireComponentFactories'); if ($cache->load($presenterClass = get_class($this)) !== NULL) { return; } $ignore = class_parents('Nette\\Application\\UI\\Presenter') + ['ui' => 'Nette\\Application\\UI\\Presenter']; $rc = new ClassType($this); foreach ($rc->getMethods() as $method) { if (in_array($method->getDeclaringClass()->getName(), $ignore, TRUE) || !Strings::startsWith($method->getName(), 'createComponent')) { continue; } foreach ($method->getParameters() as $parameter) { if (!($class = $parameter->getClassName())) { // has object type hint continue; } if (!$this->findByTypeForFactory($class) && !$parameter->allowsNull()) { throw new MissingServiceException("No service of type {$class} found. Make sure the type hint in {$method} is written correctly and service of this type is registered."); } } } $files = array_map(function ($class) { return ClassType::from($class)->getFileName(); }, array_diff(array_values(class_parents($presenterClass) + ['me' => $presenterClass]), $ignore)); $files[] = ClassType::from($this->autowireComponentFactoriesLocator)->getFileName(); $cache->save($presenterClass, TRUE, [$cache::FILES => $files]); }
/** * Renders template to output. * @return void */ public function render() { if ($this->file == NULL) { // intentionally == throw new \InvalidStateException("Template file name was not specified."); } $this->__set('template', $this); $shortName = str_replace(dirname(dirname($this->file)), '', $this->file); $cache = new Cache($this->getCacheStorage(), 'Nette.FileTemplate'); $key = trim(strtr($shortName, '\\/@', '.._'), '.') . '-' . md5($this->file); $cached = $content = $cache[$key]; if ($content === NULL) { if (!$this->getFilters()) { $this->onPrepareFilters($this); } if (!$this->getFilters()) { LimitedScope::load($this->file, $this->getParams()); return; } $content = $this->compile(file_get_contents($this->file), "file …{$shortName}"); $cache->save($key, $content, array(Cache::FILES => $this->file, Cache::EXPIRE => self::$cacheExpire, Cache::CONSTS => 'Nette\\Framework::REVISION')); $cache->release(); $cached = $cache[$key]; } if ($cached !== NULL && self::$cacheStorage instanceof TemplateCacheStorage) { LimitedScope::load($cached['file'], $this->getParams()); fclose($cached['handle']); } else { LimitedScope::evaluate($content, $this->getParams()); } }
/** * Renders template to output. * @return void */ public function render() { if ($this->file == NULL) { // intentionally == throw new Nette\InvalidStateException('Template file name was not specified.'); } if (!$this->getFilters()) { $this->onPrepareFilters($this); } if ($latte = $this->getLatte()) { return $latte->setLoader(new Latte\Loaders\FileLoader())->render($this->file, $this->getParameters()); } $cache = new Caching\Cache($storage = $this->getCacheStorage(), 'Nette.FileTemplate'); if ($storage instanceof Caching\Storages\PhpFileStorage) { $storage->hint = str_replace(dirname(dirname($this->file)), '', $this->file); } $cached = $compiled = $cache->load($this->file); if ($compiled === NULL) { try { $compiled = "<?php\n\n// source file: {$this->file}\n\n?>" . $this->compile(); } catch (FilterException $e) { throw $e->setSource(file_get_contents($this->file), $e->sourceLine, $this->file); } $cache->save($this->file, $compiled, array(Caching\Cache::FILES => $this->file, Caching\Cache::CONSTS => 'Nette\\Framework::REVISION')); $cached = $cache->load($this->file); } $isFile = $cached !== NULL && $storage instanceof Caching\Storages\PhpFileStorage; self::load($isFile ? $cached['file'] : $compiled, $this->getParameters(), $isFile); }
/** * @param string * @return ClassMetadata * @throws \Nette\InvalidStateException */ public function getClassMetadata($class) { $lower = strtolower($class); if (isset($this->metas[$lower])) { return $this->metas[$lower]; } if ($this->cache && $this->cache[$lower]) { return $this->metas[$lower] = $this->cache[$lower]; } if (!class_exists($lower)) { throw new \Nette\InvalidArgumentException("Class '$class' not exist"); } $metadata = new ClassMetadata($class); foreach ($this->parsers as $parser) { $parser->parse($metadata); } if ($this->cache) { $this->cache->save($lower, $metadata, array( Cache::FILES => array($metadata->getReflection()->getFileName()) )); } return $this->metas[$lower] = $metadata; }
/** * @param string $name * @return string */ public function link($name) { $path = $this->cache->load([$name, $this->debugMode]); $files = $this->files[$name]; $files = is_string($files) ? [$files] : $files; if ($path === NULL) { $unpackedFiles = $this->unpack($name, $files); $time = $this->getModifyTime($unpackedFiles); $path = $this->genDir . '/' . $this->getOutputFilename($name, $unpackedFiles, $time, $this->debugMode); $this->cache->save([$name, $this->debugMode], $path); } $genFile = "{$this->wwwDir}/{$path}"; if (!file_exists($genFile) || $this->debugMode && filemtime($genFile) < (isset($time) ? $time : ($time = $this->getModifyTime($this->unpack($name, $files))))) { $start = microtime(TRUE); $parsedFiles = $this->compile($this->unpack($name, $files), $genFile); if ($this->debugMode) { $this->statistics[$name]['time'] = microtime(TRUE) - $start; $this->statistics[$name]['parsedFiles'] = $parsedFiles; } } if ($this->debugMode) { $unpackedFiles = $this->unpack($name, $files); $this->statistics[$name]['size'] = filesize($genFile); $this->statistics[$name]['file'] = count($unpackedFiles) > 1 ? $unpackedFiles : reset($unpackedFiles); $this->statistics[$name]['date'] = isset($time) ? $time : ($time = $this->getModifyTime($unpackedFiles)); $this->statistics[$name]['path'] = $path; } return $path; }
/** * @param Translator $translator * @param MessageCatalogueInterface[] $availableCatalogues * @param string $locale * @throws InvalidArgumentException * @return MessageCatalogueInterface|NULL */ public function compile(Translator $translator, array &$availableCatalogues, $locale) { if (empty($locale)) { throw new InvalidArgumentException("Invalid locale."); } if (isset($availableCatalogues[$locale])) { return $availableCatalogues; } $cacheKey = array($locale, $translator->getFallbackLocales()); $storage = $this->cache->getStorage(); if (!$storage instanceof Kdyby\Translation\Caching\PhpFileStorage) { if (($messages = $this->cache->load($cacheKey)) !== NULL) { $availableCatalogues[$locale] = new MessageCatalogue($locale, $messages); return $availableCatalogues; } $this->catalogueFactory->createCatalogue($translator, $availableCatalogues, $locale); $this->cache->save($cacheKey, $availableCatalogues[$locale]->all()); return $availableCatalogues; } $storage->hint = $locale; $cached = $compiled = $this->cache->load($cacheKey); if ($compiled === NULL) { $this->catalogueFactory->createCatalogue($translator, $availableCatalogues, $locale); $this->cache->save($cacheKey, $compiled = $this->compilePhpCache($translator, $availableCatalogues, $locale)); $cached = $this->cache->load($cacheKey); } $availableCatalogues[$locale] = self::load($cached['file']); return $availableCatalogues; }
/** * Renders template to output. * * @return void */ public function render() { if ($this->file == null) { // intentionally == throw new Nette\InvalidStateException("Template file name was not specified."); } $cache = new Caching\Cache($storage = $this->getCacheStorage(), 'Nette.FileTemplate'); if ($storage instanceof Caching\Storages\PhpFileStorage) { $storage->hint = str_replace(dirname(dirname($this->file)), '', $this->file); } $cached = $compiled = $cache->load($this->file); if ($compiled === null) { try { $compiled = "<?php\n\n// source file: {$this->file}\n\n?>" . $this->compile(); } catch (FilterException $e) { $e->setSourceFile($this->file); throw $e; } $cache->save($this->file, $compiled, array(Caching\Cache::FILES => $this->file, Caching\Cache::CONSTS => 'Nette\\Framework::REVISION')); $cached = $cache->load($this->file); } if ($cached !== null && $storage instanceof Caching\Storages\PhpFileStorage) { Nette\Utils\LimitedScope::load($cached['file'], $this->getParameters()); } else { Nette\Utils\LimitedScope::evaluate($compiled, $this->getParameters()); } }
/** * Adds support for FQN annotations * @param $entityClass * @return Orm\MetaData */ public static function createMetaData($entityClass) { $cache = new Cache(self::$metaDataStorage, __CLASS__); return $cache->load($entityClass, function () use($entityClass) { return AnnotationMetaData::getMetaData($entityClass); }); }
/** * Renders template to output. * @return void */ public function render() { if ($this->file == NULL) { // intentionally == throw new \InvalidStateException("Template file name was not specified."); } $this->__set('template', $this); $cache = new Cache($storage = $this->getCacheStorage(), 'Nette.FileTemplate'); if ($storage instanceof TemplateCacheStorage) { $storage->hint = str_replace(dirname(dirname($this->file)), '', $this->file); } $cached = $content = $cache[$this->file]; if ($content === NULL) { try { $content = $this->compile(file_get_contents($this->file)); $content = "<?php\n\n// source file: {$this->file}\n\n?>{$content}"; } catch (TemplateException $e) { $e->setSourceFile($this->file); throw $e; } $cache->save($this->file, $content, array(Cache::FILES => $this->file, Cache::CONSTS => 'Nette\\Framework::REVISION')); $cache->release(); $cached = $cache[$this->file]; } if ($cached !== NULL && $storage instanceof TemplateCacheStorage) { LimitedScope::load($cached['file'], $this->getParams()); flock($cached['handle'], LOCK_UN); fclose($cached['handle']); } else { LimitedScope::evaluate($content, $this->getParams()); } }
/** * @param \Nette\DI\Container $dic * @throws MemberAccessException * @throws MissingServiceException * @throws InvalidStateException * @throws UnexpectedValueException */ public function injectProperties(Nette\DI\Container $dic) { if (!$this instanceof Nette\Application\UI\PresenterComponent && !$this instanceof Nette\Application\UI\Component) { throw new MemberAccessException('Trait ' . __TRAIT__ . ' can be used only in descendants of PresenterComponent.'); } $this->autowirePropertiesLocator = $dic; $storage = $dic->hasService('autowired.cacheStorage') ? $dic->getService('autowired.cacheStorage') : $dic->getByType('Nette\\Caching\\IStorage'); $cache = new Nette\Caching\Cache($storage, 'Kdyby.Autowired.AutowireProperties'); $containerFileName = ClassType::from($this->autowirePropertiesLocator)->getFileName(); $cacheKey = [$presenterClass = get_class($this), $containerFileName]; if (is_array($this->autowireProperties = $cache->load($cacheKey))) { foreach ($this->autowireProperties as $propName => $tmp) { unset($this->{$propName}); } return; } $this->autowireProperties = []; $ignore = class_parents('Nette\\Application\\UI\\Presenter') + ['ui' => 'Nette\\Application\\UI\\Presenter']; $rc = new ClassType($this); foreach ($rc->getProperties() as $prop) { if (!$this->validateProperty($prop, $ignore)) { continue; } $this->resolveProperty($prop); } $files = array_map(function ($class) { return ClassType::from($class)->getFileName(); }, array_diff(array_values(class_parents($presenterClass) + ['me' => $presenterClass]), $ignore)); $files[] = $containerFileName; $cache->save($cacheKey, $this->autowireProperties, [$cache::FILES => $files]); }
/** * @param $class * @param array $types * @return string * @throws \Nette\InvalidArgumentException */ public function prepareType($class, array $types = array()) { $class = trim($class, '\\'); $key = serialize(array('class' => $class, 'types' => $types)); if (!isset($this->loaded[$key])) { $newClass = $this->prepareClassName($class, $types); if ($this->storage) { $cache = new Cache($this->storage, 'Venne.Generics'); $data = $cache->load($key); if (!$data) { $data = $this->prepareClassTemplate($class, $newClass, $types); $cache->save($key, $data); $data = $cache->load($key); } if ($this->storage instanceof PhpFileStorage) { \Nette\Utils\LimitedScope::load($data['file']); } else { \Nette\Utils\LimitedScope::evaluate($data); } } else { $data = $this->prepareClassTemplate($class, $newClass, $types); \Nette\Utils\LimitedScope::evaluate($data); } $this->loaded[$key] = $newClass; } return $this->loaded[$key]; }
/** * @param string * @return mixed|NULL */ public function load($key) { $cached = $this->cache->load($key); if (!is_array($cached) || $cached[1] !== $this->expire) { return NULL; } return $cached[0]; }
/** * Create resources route list * @param string|null $module * @return ResourceRouteList */ public function create($module = NULL) { $routeList = $this->cache->load(self::CACHE_NAME); if ($routeList !== NULL) { return $routeList; } return $this->createCached($module); }
/** * @param string $oldAgencyId * @return string */ private function getAgencyId($oldAgencyId) { $newId = $this->agencyIdsCache->load($oldAgencyId); if ($newId === null) { throw new InvalidStateException('Unknown agency ID: ' . $oldAgencyId); } return $newId; }
/** * @param string $oldStopId * @return string */ private function getStopId($oldStopId) { $newId = $this->stopsIdsCache->load($oldStopId); if ($newId === null) { throw new InvalidStateException('Unknown stop ID: ' . $oldStopId); } return $newId; }
public function handleLoadExceptions() { $this->importService->import(); $this->template->lastUpdate = $this->cache->load("lastUpdate", function () { return null; }); $this->redrawControl(); }
/** * Stops and saves the cache. * @param array dependencies * @return void */ public function end(array $dependencies = NULL) { if ($this->cache === NULL) { throw new Nette\InvalidStateException('Output cache has already been saved.'); } $this->cache->save($this->key, ob_get_flush(), (array) $dependencies + (array) $this->dependencies); $this->cache = NULL; }
/** * @return mixed */ public function createMenu() { $neon = $this->cache->load('menu'); if ($neon === NULL) { $neon = Neon::decode(file_get_contents($this->filename)); $this->cache->save('menu', $neon, array(Cache::FILES => $this->filename)); } return $neon; }
/** * Save data into cache * * @param string $key * @param mixed $callback * @param array|NULL $params * @return mixed|NULL */ public function storeValue($key, $callback, array $params = NULL) { // load from cache $savedData = $this->cache->load($key); if (!empty($savedData)) { return $savedData; } return $this->cache->save($key, $callback, $params); }
/** * @param Page $page */ private function removePageUrl(Page $page) { /** @var Url $url */ $url = $this->urlFacade->getByPath($page->getUrlPath()); if ($url !== null) { $this->cache->clean([Cache::TAGS => $url->getCacheKey()]); $this->em->remove($url); } }
public function __invoke($url, string $directory = NULL, string $parameter = NULL) : string { $arguments = [$url, $directory ?: $this->directory, $parameter ?: $this->parameter]; return $this->cache ? $this->cache->load($arguments, function (&$dependencies) use($arguments) { $dependencies[Nette\Caching\Cache::EXPIRE] = $this->expire; $arguments[] =& $dependencies; return $this->process(...$arguments); }) : $this->process(...$arguments); }