Dependencies are:
- Cache::PRIORITY => (int) priority
- Cache::EXPIRATION => (timestamp) expiration
- Cache::SLIDING => (bool) use sliding expiration?
- Cache::TAGS => (array) tags
- Cache::FILES => (array|string) file names
- Cache::ITEMS => (array|string) cache items
- Cache::CONSTS => (array|string) cache items
/** * @param string $alias * @param \ReflectionClass $context * @return string * @throws Exception\NamespaceNotFoundException */ static function getClass($alias, \ReflectionClass $context) { if (!strlen($alias)) { return $alias; } if (strncmp($alias, '\\', 1) === 0) { return substr($alias, 1); } $file = $context->getFileName(); if (!isset(self::$map[$file])) { if (self::$cache === NULL) { $list = Parser::parse($file); } else { $key = self::C_FILE . $file; $list = self::$cache->load($key); if ($list === NULL) { $list = self::$cache->save($key, Parser::parse($file), array(NCache::FILES => array($file))); } } self::$map[$file] = $list; } $namespace = $context->getNamespaceName(); if (!isset(self::$map[$file][$namespace])) { throw new Exception\NamespaceNotFoundException("Namespace '{$namespace}' not found in '{$file}'."); } $parts = explode('\\', $alias); $first = array_shift($parts); if (!isset(self::$map[$file][$namespace][$first])) { return ltrim(trim($namespace, '\\') . '\\', '\\') . $alias; } $appendix = implode('\\', $parts); return self::$map[$file][$namespace][$first] . (strlen($appendix) ? '\\' . $appendix : ''); }
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); }
/** * @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; }
private function saveInLatLngCache(array $stop, $stopId) { $key = $this->getLatLngCacheKey($stop); if (is_string($key)) { $this->latLngCache->save($key, $stopId); } }
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()); }
/** * @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; }
/** * 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; }
/** * {@inheritdoc} */ public function isAllowed($role, $resource, $privilege) { if (NULL === ($allowed = $this->cache->load([$role, $resource, $privilege]))) { $allowed = $this->cache->save([$role, $resource, $privilege], function () use($role, $resource, $privilege) { return $this->authorizator->isAllowed($role, $resource, $privilege); }, [Cache::TAGS => ['role/' . serialize($role), 'resource/' . serialize($resource), 'privilege/' . serialize($privilege)]]); } return $allowed; }
/** * @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); }
/** * Create cached route list * @param null $module * @return ResourceRouteList */ private function createCached($module = NULL) { $files = array(); $presenterFiles = Finder::findFiles('*Presenter.php')->from($this->presentersRoot); foreach ($presenterFiles as $path => $splFile) { $files[] = $path; } $routeList = $this->routeListFactory->create($module); $this->cache->save(self::CACHE_NAME, $routeList, array(Cache::FILES => $files)); return $routeList; }
public function save($key, $data, array $options = []) { $netteOptions = []; foreach ($options as $type => $option) { if (!isset($this->options[$type])) { throw new \Exception("Unsupported cache option " . $type . "!"); } $netteOptions[$this->options[$type]] = $option; } $this->netteCache->save($key, $data, $netteOptions); }
public function __construct(\Nette\Database\Context $database, \Nette\DI\Container $context) { $this->database = $database; $this->cache = new \Nette\Caching\Cache($context->getService('cacheStorage'), "system"); $roles = $this->cache->load("PermissionsRoles"); $resources = $this->cache->load("PermissionsResources"); $this->init($roles, $resources); if ($roles === NULL || $resources === NULL) { $this->cache->save("PermissionsRoles", $this->getRoles()); $this->cache->save("PermissionsResources", $this->getResources()); } }
public function install() { /** @var $package \movi\Packages\Package */ foreach (array_values($this->manager->getPackages()) as $package) { $hash = sha1(Json::encode($package)); // Load cache if ($this->cache->load($package->name) === NULL || $this->cache->load($package->name) !== $hash) { $this->installPackage($package); $this->cache->save($package->name, $hash); } } }
/** * @param LanguageEntity $language */ public function onSet(LanguageEntity $language) { if ($this->cache->load($language->id) === NULL) { $file = sprintf('%s/%s.neon', $this->localeDir, $language->code); $translations = []; if (file_exists($file) && is_readable($file)) { $translations = Neon::decode(file_get_contents($file)); $this->process($translations); } $this->cache->save($language->id, $translations, [Cache::FILES => $file]); } $this->translations = $this->cache->load($language->id); }
/** * init the translator, build translation array * * @param string $path where to look for l10n files * @param string $lang language code * @param IStorage $storage */ public function __construct($path, $lang, $storage) { $this->lang = $lang; // try cached dictionary $this->cache = new Cache($storage, 'B4nan.Translator'); $dictionary = $this->cache->load('dictionary'); if ($dictionary === NULL) { $dictionary = $this->createDictionary($path); $dictionaries = glob("{$path}/*.neon"); // l10n files $this->cache->save('dictionary', $dictionary, [Cache::FILES => $dictionaries]); } $this->dictionary = $dictionary; }
/** * @param string $key * @return bool */ public function doesExist($key) : bool { $cacheKey = sprintf('doesExists_%s', $key); $result = $this->cache->load($cacheKey); if ($result === null) { if (!Strings::startsWith($key, 'fakturoid.account')) { $result = false; } else { $property = $this->getLastToken($key); $result = $property !== null && property_exists($this->getAccount(), $property); } $this->cache->save($cacheKey, $result, [Cache::EXPIRE => self::CACHE_EXPIRATION]); } return $result; }
/** * 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); }
/** * 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()); } }
/** * @param resource $stream * @return array */ public function merge($stream) { $items = []; $header = fgetcsv($stream); while (($data = fgetcsv($stream)) !== false) { $data = array_combine($header, $data); $currentId = $data['trip_id']; $newId = $this->uuidProvider->uuid4()->toString(); $data['trip_id'] = $newId; $data['route_id'] = $this->getRouteId($data['route_id']); $data['service_id'] = $this->getServiceId($data['service_id']); $this->idsCache->save($currentId, $newId); $items[] = $data; } return $items; }
/** * 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()); } }
/** * @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]); }
/** * Load data */ protected function loadDictonary() { if (!$this->loaded) { if (empty($this->files)) { throw new Nette\InvalidStateException('Language file(s) must be defined.'); } $dictionaryTmp = $this->cache->load('dictionary-' . $this->lang); if ($this->productionMode && $dictionaryTmp) { $this->dictionary = $dictionaryTmp; } else { $files = array(); foreach ($this->files as $identifier => $dir) { $path = "{$dir}/{$this->lang}.{$identifier}.mo"; if (file_exists($path)) { $this->parseFile($path, $identifier); $files[] = $path; } } if ($this->productionMode) { $this->cache->save('dictionary-' . $this->lang, $this->dictionary, array('expire' => time() * 60 * 60 * 2, 'files' => $files, 'tags' => array('dictionary-' . $this->lang))); } } $this->loaded = TRUE; } }
/** * @return Nette\Application\IRouter */ public function createRouter() { if ($this->debug || ($router = $this->cache->load('router')) === null) { $router = new RouteList(); $router[] = new Route('index.php', 'Front:Homepage:default', Route::ONE_WAY); $router[] = new Route('sign-in', 'Sign:in'); $router[] = new Route('logout', 'Sign:out'); $router[] = new Route('sitemap.xml', 'Sitemap:default'); $router[] = $module = new RouteList('Admin'); $module[] = new Route('admin/<presenter>/<action>[/<id>]', ['presenter' => 'Homepage', 'action' => 'default']); $router[] = $module = new RouteList('Front'); $module[] = new Route('<presenter>/<action>[/<id>]', ['presenter' => 'Homepage', 'action' => 'default']); $this->cache->save('router', $router); } return $router; }
/** * 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); } } }
protected function saveCacheState() { if ($this->observeCache === $this && $this->cache && !$this->sqlBuilder->getSelect() && $this->accessedColumns !== $this->previousAccessedColumns) { $this->cache->save($this->getGeneralCacheKey(), $this->accessedColumns); $this->previousAccessedColumns = NULL; } }
/** * Check for available domain. * * @return array */ private function loadDomains() { if ($this->cache->load(self::DOMAIN) !== NULL) { return $this->domains = $this->cache->load(self::DOMAIN); } $files = $match = $domains = array(); $find = Finder::findFiles('*.po'); foreach ($find->from($this->path) as $file) { /* @var $file SplFileInfo */ if (preg_match('/' . preg_quote($this->path, '/') . '(.*)(?:\\\\|\\/)/U', $file->getPath(), $match)) { $_dictionary = $file->getBasename('.po'); $domains[$match[1]][$_dictionary] = $_dictionary; $files[] = $file->getPathname(); } } $dictionary = $domains; foreach ($domains as $lang => $_domains) { unset($dictionary[$lang]); foreach ($dictionary as $value) { $diff = array_diff($_domains, $value); if ($diff) { throw new GettextException('For this language (' . $lang . ') you have one or more different dicitonaries: ' . implode('.mo, ', $diff) . '.mo'); } } } if (!isset($_domains)) { // @todo https://github.com/josscrowcroft/php.mo throw new GettextException('Let\'s generate *.mo files.'); } $data = array_combine($_domains, array_fill_keys($_domains, FALSE)); return $this->domains = $this->cache->save(self::DOMAIN, $data, array(Cache::FILES => $files)); }
public function isVariadic() : bool { $isNativelyVariadic = $this->reflection->isVariadic(); if (!$isNativelyVariadic && $this->reflection->getFileName() !== false) { $key = sprintf('variadic-function-%s-v2', $this->reflection->getName()); $cachedResult = $this->cache->load($key); if ($cachedResult === null) { $nodes = $this->parser->parseFile($this->reflection->getFileName()); $result = $this->callsFuncGetArgs($nodes); $this->cache->save($key, $result); return $result; } return $cachedResult; } return $isNativelyVariadic; }
private function setCacheIc($ic, \stdClass $address) { if (!$this->useCache()) { return; } $this->cache->save($ic, json_encode($address), [Caching\Cache::TAGS => ["ico"], Caching\Cache::EXPIRE => $this->timeout]); }