public function save() { // New and changed keys $changed = array_diff_assoc($this->data, $this->original); $insertValues = array(); foreach ($changed as $name => $value) { if (!array_key_exists($name, $this->original)) { $insertValues[] = array('conf_name' => $name, 'conf_value' => $value); unset($changed[$name]); } } if (!empty($insertValues)) { $this->database->table('config')->insert($insertValues); } foreach ($changed as $name => $value) { $this->database->table('config')->where('conf_name', '=', $name)->update(array('conf_value' => $value)); } // Deleted keys $deletedKeys = array_keys(array_diff_key($this->original, $this->data)); if (!empty($deletedKeys)) { $this->database->table('config')->whereIn('conf_name', $deletedKeys)->delete(); } // No need to cache old values anymore $this->original = $this->data; // Delete the cache so that it will be regenerated on the next request $this->cache->forget('fluxbb.config'); }
/** * Get info from a specify url and cache that using laravel cache manager. * * @param string $url * @param null|array $options * @return mixed */ public function cache($url, array $options = null) { $lifetime = array_get($options, 'lifetime', 60); array_forget($options, 'lifetime'); $self = $this; return $this->cache->remember($url, $lifetime, function () use($self, $url, $options) { return $self->get($url, $options); }); }
/** * Cache the key value till 12am * * @param string $key * @param mixed $value * @return void */ public static function put($key, $value) { $today = strtotime(date('Ymd')); $key = "{$today}.{$key}"; $minutes = (int) date('i'); $total_minutes_today = date('G') * 60 + $minutes; $minutes_till_midnight = 1440 - $total_minutes_today; static::$cache->put($key, $value, $minutes_till_midnight); }
/** * {@inheritdoc} */ protected function format($string) { if (!$this->watch) { $key = 'js.' . sha1($string); $string = $this->cache->rememberForever($key, function () use($string) { return $this->minify($string); }); } return $string . ";\n"; }
/** * Returns the cached content if NOT running locally. * * @param string $key * @param mixed $value * @param int $time * @return mixed */ private function cached($key, $value, $time = 5) { if (App::environment('local') === false) { return $this->cache->remember($key, $time, function () use($value) { return $value; }); } else { return $value; } }
/** * To get all columns on caching * * @param \Illuminate\Database\Eloquent\Model $model * @return array */ protected function getColumnsOnCache(Model $model) { /** * In normal scenario tables and columns often is not changed. * Therefore every time it is not need to access the database for knowing * columns name. We don't want make preoccupy/busy to the database. */ $fullKey = $this->getFullName($model); return $this->cache->remember($fullKey, $this->getRememberTime(), function () use($model) { return $this->builder->getColumnListing($model->getTable()); }); }
/** * Handles authenticating that a user/character is still valid. * * @return \Illuminate\Http\JsonResponse */ public function postAuthorized() { // Get the neccessary headers from the request. $service = $this->request->header('service', false); $username = $this->request->header('username', ''); $character = $this->request->header('character', ''); $this->log->info('A service is attempting to validate a user.', ['username' => $username, 'character' => $character, 'service' => $service]); // Verify that the external service exists in the configuration. if (!$service || !$this->config->get("addon.auth.{$service}")) { $this->log->info(self::ERROR_INVALID_EXTERNAL_SERVICE, ['service' => $service]); return $this->failure(self::ERRNO_INVALID_EXTERNAL_SERVICE, self::ERROR_INVALID_EXTERNAL_SERVICE); } // Check the cache first so the api isn't hammered too badly. $key = 'auth:session:' . sha1("{$service}:{$username}"); if ($this->cache->has($key)) { $this->log->info('Returning the cached authorization result.'); return $this->cache->get($key); } // Attempt to find the requested user. $identifier = filter_var($username, FILTER_VALIDATE_EMAIL) ? 'email' : 'name'; $user = $this->users->where($identifier, $username)->first() ?: false; if (!$user) { $this->log->info(self::ERROR_USER_NOT_FOUND); return $this->failure(self::ERRNO_USER_NOT_FOUND, self::ERROR_USER_NOT_FOUND); } // Get and cache the response for 15 minutes. $response = $this->getLoginResult($user, $service, $character); $this->cache->put($key, $response, $this->carbon->now()->addMinutes(15)); return $response; }
/** * Handle the form. * * @param Repository $cache * @param Redirector $redirect * @param $key * @return \Symfony\Component\HttpFoundation\Response */ public function handle(Repository $cache, Redirector $redirect, $key) { $parameters = $cache->get('form::' . $key); $criteria = $this->dispatch(new GetFormCriteria($parameters)); /* @var FormBuilder $builder */ $builder = $criteria->builder(); $response = $builder->build()->post()->getFormResponse(); $builder->flash(); if ($response && $response->getStatusCode() !== 200) { return $response; } if ($builder->hasFormErrors()) { return $redirect->back(); } return $response ?: $redirect->back(); }
/** * Retrieve an item from the cache by key. If the item is about to expire soon, * extend the existing cache entry (for other requests) before returning the item * * @param string $key * @param mixed $default * @return mixed */ public function get($key, $default = null) { while ($this->cacheFlagExists($key)) { sleep($this->sleep); } return parent::get($key, $default); }
/** * {@inheritdoc} */ public function save($key, CacheEntry $data) { try { $lifeTime = $data->getTTL(); if ($lifeTime === 0) { return $this->cache->forever($key, serialize($data)); } else { if ($lifeTime > 0) { return $this->cache->add($key, serialize($data), $lifeTime); } } } catch (\Exception $ignored) { // No fail if we can't save it the storage } return false; }
/** * Get the page sub title * * @param string $page * @return string */ public function getSubTitle($page) { $pageFile = $this->getDocumentationPath() . "/{$page}.md"; return $this->cache->rememberForever("doc_page_{$pageFile}_sub-title", function () use($pageFile) { $data = $this->parser->parse($this->finder->get($pageFile)); return $data->get('subtitle'); }); }
/** * Retrives the installed themes from the cache. * * If the cahce entry doesn't exist then it is created. * * @return array */ public function getInstalledThemes() { $installed = $this->cache->get($this->cacheKey); if ($installed !== null) { return $installed; } return $this->findAndInstallThemes(); }
/** * make a cache key * * @param string $key * @param string $prefix * @return string */ private function makeCacheKey($key, $prefix = '') { $key = md5($prefix . $key); $keys = $this->cache->get(self::CACHE_KEYS_KEY, []); $keys[$key] = $key; $this->cache->forever(self::CACHE_KEYS_KEY, $keys); return $key; }
public function testShouldReturnNullFlushRecord() { $this->repository->add('memcached-testing', 'couchbase', 60); $this->repository->decrement('memcached-testing-decrement', 100); $this->repository->increment('memcached-testing-increment', 100); $this->repository->flush(); $this->assertNull($this->repository->get('memcached-testing')); $this->assertNull($this->repository->get('memcached-testing-decrement')); $this->assertNull($this->repository->get('memcached-testing-increment')); }
public function search(Repository $cache, $search = 'enchantment') { $client = new Client(config('algolia.connections.main.id'), config('algolia.connections.main.key')); //if ($cache->has('origins.'. $search)) { // $cards = $cache->get($search); //} else { $index = $client->initIndex(config('algolia.index')); $index->setSettings(['attributesForFaceting' => ['colors', 'multiverseid']]); $cards = $index->search($search, ['facets' => '*', 'facetFilters' => 'colors:Green'])['hits']; foreach ($cards as $index => $card) { if (isset($card['manaCost'])) { $cards[$index]['manaCost'] = preg_replace('/{(.)}/', '<img src="/images/blank.png" id="$1" />', $card['manaCost']); } } $cache->forever($search, $cards); //} $this->setJavascriptData(compact('cards')); }
/** * @return Realm */ public function getRealmData() { $that = $this; return $this->cache->get('ekko:static:realm', function () use($that) { $data = $this->ekko->data()->getRealm(); $that->cache->add('ekko:static:realm', $data, 60 * 24 * 7); return $data; }); }
/** * Save a cached view if caching is enabled. * * @param \Illuminate\Http\Response $response * @return void */ protected function saveCachedView(Response $response) { if (config('sitemap.cache_enabled')) { $key = $this->getCacheKey(); $content = $response->getOriginalContent()->render(); if (!$this->cache->get($key)) { $this->cache->put($key, $content, config('sitemap.cache_length')); } } }
/** * @param $matchId * * @return Match */ public function getMatch($matchId) { $that = $this; $cachKey = 'match:' . $matchId; return $this->cache->get($cachKey, function () use($that, $cachKey, $matchId) { $match = $that->ekko->matches()->getMatch($matchId, true); $match = $that->setStaticData($match); $that->cache->put('match:' . $matchId, $match, 3600); return $match; }); }
public function replaceVersion($path) { $version = $this->cache->get('laravel-asset-versioning.version'); $file = explode('.', $path); $extension = $file[count($file) - 1]; $types = $this->config->get('assets.types.' . $extension); if (isset($types['origin_dir'])) { $types = [$types]; } foreach ((array) $types as $type) { if (!$type) { continue; } if (!preg_match("#^\\/?" . $type['origin_dir'] . "#", $path)) { continue; } $resource = str_replace($type['origin_dir'], $type['dist_dir'] . '/' . $version, $path); $this->addHTTP2Link($resource, $extension); return $resource; } return $path; }
/** * Flush the cache for this Model Object instance * * @param Model $model * @return void */ public function flush(Model $model) { // Assemble Cache Keys $keys[] = $this->resourceName . '.hash.' . $model->hash; $keys[] = $this->resourceName . '.id.' . $model->id; // Some keys will not be available on all models $referenceColumn = $this->referenceIdColumnName(); if ($this->model->isFillable($referenceColumn)) { $keys[] = $this->resourceName . '.' . $referenceColumn . '.' . $model->{$referenceColumn}; } // Clear the cache for the given keys foreach ($keys as $key) { $this->cache->forget($key); } }
/** * Generate thumbnail. * * @param $src * @param $width * @param $height * * @throws \RuntimeException * @return Thumbnail */ public function make($src, $width, $height) { if ($src === null || $width === null && $height === null) { throw new \RuntimeException(); } $key = md5($src . 'w' . $width . 'h' . $height); if (!($image = $this->cache->get($key))) { $image = $this->image->make($src); $image->resize($width, $height, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }); if ($width === null) { $width = $image->getWidth(); } if ($height === null) { $height = $image->getHeight(); } $image->resizeCanvas($width, $height, 'center', false, 'ffffff'); $image = (string) $image->encode('jpg'); $this->cache->put($key, $image, $this->lifetime); } return new Thumbnail($key, $image, $this->expires(), 'image/jpeg'); }
/** * Forget settings cache. * * @return bool */ public function forget() { return $this->cache->forget(self::CACHE_KEY); }
/** * Remove an item from the cache. * * @param mixed $key * @return bool */ public function forget($key) { if (is_array($key)) { return $this->forgetMany($key); } return parent::forget($key); }
/** * Clear the cache for this Repositories' Entity * @return bool */ public function clearCache() { return $this->cache->tags($this->entityName)->flush(); }
/** * Create a new cache repository with the given implementation. * * @param \Illuminate\Contracts\Cache\Store $store * @return \Illuminate\Cache\Repository */ public function repository(Store $store) { $repository = new Repository($store); if ($this->app->bound('Illuminate\\Contracts\\Events\\Dispatcher')) { $repository->setEventDispatcher($this->app['Illuminate\\Contracts\\Events\\Dispatcher']); } return $repository; }
/** * {@inheritDoc} */ public function destroy($sessionId) { return $this->cache->forget($sessionId); }
Illuminate\Container\Container::setInstance($app); if (file_exists($configFile = __DIR__ . '/../config.php')) { $app->instance('flarum.config', include $configFile); } date_default_timezone_set('UTC'); $app->instance('config', $config = new ConfigRepository(['view' => ['paths' => [realpath(base_path('resources/views'))], 'compiled' => realpath(storage_path() . '/framework/views')], 'mail' => ['driver' => 'mail'], 'cache' => ['default' => 'file', 'stores' => ['file' => ['driver' => 'file', 'path' => storage_path() . '/framework/cache']], 'prefix' => 'flarum'], 'filesystems' => ['default' => 'local', 'cloud' => 's3', 'disks' => ['flarum-avatars' => ['driver' => 'local', 'root' => public_path('assets/avatars')]]]])); $logger = new Monolog\Logger($app->environment()); $logPath = $app->storagePath() . '/logs/flarum.log'; $handler = new \Monolog\Handler\StreamHandler($logPath, Monolog\Logger::DEBUG); $handler->setFormatter(new \Monolog\Formatter\LineFormatter(null, null, true, true)); $logger->pushHandler($handler); $app->instance('log', $logger); $app->alias('log', 'Psr\\Log\\LoggerInterface'); $app->singleton('cache', function ($app) { $store = new FileStore(new Filesystem(), storage_path('framework/cache')); $repository = new Repository($store); $repository->setEventDispatcher($app->make('events')); return $repository; }); $app->alias('cache', 'Illuminate\\Contracts\\Cache\\Repository'); $serviceProviders = ['Flarum\\Core\\DatabaseServiceProvider', 'Flarum\\Core\\Settings\\SettingsServiceProvider', 'Flarum\\Locale\\LocaleServiceProvider', 'Illuminate\\Bus\\BusServiceProvider', 'Illuminate\\Filesystem\\FilesystemServiceProvider', 'Illuminate\\Hashing\\HashServiceProvider', 'Illuminate\\Mail\\MailServiceProvider', 'Illuminate\\View\\ViewServiceProvider', 'Illuminate\\Events\\EventServiceProvider', 'Illuminate\\Validation\\ValidationServiceProvider']; foreach ($serviceProviders as $provider) { $app->register(new $provider($app)); } if (Core::isInstalled()) { $settings = $app->make('Flarum\\Core\\Settings\\SettingsRepository'); $app->register(new \Flarum\Core\CoreServiceProvider($app)); $config->set('mail.driver', Core::config('mail_driver')); $config->set('mail.host', Core::config('mail_host')); $config->set('mail.port', Core::config('mail_port')); $config->set('mail.from.address', Core::config('mail_from'));
public function flush() { $this->cache->flush(); }
/** * Dynamically handle calls to the class. * * @param string $method * @param array $parameters * @return mixed * @throws \BadMethodCallException * @static */ public static function macroCall($method, $parameters) { return \Illuminate\Cache\Repository::macroCall($method, $parameters); }
/** * To get all lang models on the cache driver * * @return \Illuminate\Database\Eloquent\Collection */ protected function getCachedLangModels() { $key = $this->getKeyOfCachedLangModel($this->getMainModel()->langModels()->getRelated()); return $this->cache->remember($key, $this->getRememberTime(), function () { return $this->getAllLangModels()->getRelated()->all(); }); }