public function run() { Yii::beginProfile("NavigationWidget for " . $this->rootId); $items = null; $cacheKey = implode(':', ['Navigation', $this->rootId, $this->depth, $this->viewFile]); if ($this->useCache) { if (false === ($items = \Yii::$app->cache->get($cacheKey))) { $items = null; } } if (null === $items) { $root = Navigation::find()->where(['id' => $this->rootId])->with('children')->orderBy(['sort_order' => SORT_ASC])->one(); $items = []; if ($this->depth > 0) { foreach ($root->children as $child) { $items[] = self::getTree($child, $this->depth - 1); } } if (count($items) > 0) { \Yii::$app->cache->set($cacheKey, $items, 86400, new TagDependency(['tags' => [\devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag(Navigation::className())]])); } } $items = ArrayHelper::merge((array) $this->prependItems, $items, (array) $this->appendItems); $currentUri = Yii::$app->request->url; array_walk($items, function (&$item) use($currentUri) { if ($item['url'] === $currentUri) { $item['active'] = true; } }); $result = $this->render($this->viewFile, ['widget' => $this->widget, 'items' => $items, 'options' => $this->options, 'linkTemplate' => $this->linkTemplate, 'submenuTemplate' => $this->submenuTemplate]); Yii::endProfile("NavigationWidget for " . $this->rootId); return $result; }
/** * @param $modelName * @param $id * @param bool $createIfEmptyId * @param bool $useCache * @param int $cacheLifetime * @param bool $throwException * @return ActiveRecord|null * @throws NotFoundHttpException */ public static function loadModel($modelName, $id, $createIfEmptyId = false, $useCache = true, $cacheLifetime = 3600, $throwException = true) { $model = null; if (empty($id)) { if ($createIfEmptyId === true) { $model = new $modelName(); } else { if ($throwException) { throw new NotFoundHttpException(); } else { return null; } } } if ($useCache === true && $model === null) { $model = Yii::$app->cache->get($modelName::className() . ":" . $id); } if (!is_object($model)) { $model = $modelName::findOne($id); if (is_object($model) && $useCache === true) { Yii::$app->cache->set($modelName::className() . ":" . $id, $model, $cacheLifetime, new TagDependency(['tags' => ActiveRecordHelper::getCommonTag($modelName::className())])); } } if (!is_object($model)) { if ($throwException) { throw new NotFoundHttpException(); } else { return null; } } return $model; }
public function run() { $query = Category::find(); $query->andWhere([Category::tableName() . '.active' => 1]); if ($this->root_category_id !== null) { $query->andWhere([Category::tableName() . '.parent_id' => $this->root_category_id]); } if ($this->category_group_id !== null) { $query->andWhere([Category::tableName() . '.category_group_id' => $this->category_group_id]); } $query->groupBy(Category::tableName() . ".id"); $query->orderBy($this->sort); if ($this->limit !== null) { $query->limit($this->limit); } $object = Object::getForClass(Category::className()); \app\properties\PropertiesHelper::appendPropertiesFilters($object, $query, $this->values_by_property_id, []); $sql = $query->createCommand()->getRawSql(); $cacheKey = "FilteredCategoriesWidget:" . md5($sql); $result = Yii::$app->cache->get($cacheKey); if ($result === false) { $categories = Category::findBySql($sql)->all(); $result = $this->render($this->viewFile, ['categories' => $categories]); Yii::$app->cache->set($cacheKey, $result, 86400, new \yii\caching\TagDependency(['tags' => ActiveRecordHelper::getCommonTag(Category::tableName())])); } return $result; }
/** * Handle decoration * @param \yii\base\Controller $controller * @param string $viewFile * @param array $params * @return void */ public function decorate($controller, $viewFile, $params) { if (isset($controller->view->blocks['content'])) { $dependency = new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(app\modules\core\models\ContentBlock::className()), ActiveRecordHelper::getCommonTag(get_class($params['model']))]]); $controller->view->blocks['content'] = ContentBlockHelper::compileContentString($controller->view->blocks['content'], get_class($params['model']) . ':' . $params['model']->id, $dependency); } }
/** * @return string */ public function run() { parent::run(); if (null === $this->rootCategory) { return ''; } $cacheKey = $this->className() . ':' . implode('_', [$this->viewFile, $this->rootCategory, null === $this->depth ? 'null' : intval($this->depth), intval($this->includeRoot), intval($this->fetchModels), intval($this->onlyNonEmpty), implode(',', $this->excludedCategories), \Yii::$app->request->url]) . ':' . json_encode($this->additional); if (false !== ($cache = \Yii::$app->cache->get($cacheKey))) { return $cache; } /** @var array|Category[] $tree */ $tree = Category::getMenuItems(intval($this->rootCategory), $this->depth, boolval($this->fetchModels)); if (true === $this->includeRoot) { if (null !== ($_root = Category::findById(intval($this->rootCategory)))) { $tree = [['label' => $_root->name, 'url' => Url::toRoute(['@category', 'category_group_id' => $_root->category_group_id, 'last_category_id' => $_root->id]), 'id' => $_root->id, 'model' => $this->fetchModels ? $_root : null, 'items' => $tree]]; } } if (true === $this->onlyNonEmpty) { $_sq1 = (new Query())->select('main_category_id')->distinct()->from(Product::tableName()); $_sq2 = (new Query())->select('category_id')->distinct()->from('{{%product_category}}'); $_query = (new Query())->select('id')->from(Category::tableName())->andWhere(['not in', 'id', $_sq1])->andWhere(['not in', 'id', $_sq2])->all(); $this->excludedCategories = array_merge($this->excludedCategories, array_column($_query, 'id')); } $tree = $this->filterTree($tree); $cache = $this->render($this->viewFile, ['tree' => $tree, 'fetchModels' => $this->fetchModels, 'additional' => $this->additional, 'activeClass' => $this->activeClass, 'activateParents' => $this->activateParents]); \Yii::$app->cache->set($cacheKey, $cache, 0, new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(Category::className()), ActiveRecordHelper::getCommonTag(Product::className())]])); return $cache; }
public function down() { $tbl = '{{%backend_menu}}'; $this->update($tbl, ['route' => '/shop/backend-order/index'], ['route' => 'shop/backend-order/index']); $this->update($tbl, ['route' => '/shop/backend-customer/index'], ['route' => 'shop/backend-customer/index']); $this->update($tbl, ['route' => '/shop/backend-contragent/index'], ['route' => 'shop/backend-contragent/index']); \yii\caching\TagDependency::invalidate(Yii::$app->cache, [\devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag(\app\backend\models\BackendMenu::className())]); }
/** * Returns array of ID of all active warehouses * @return integer[] * @throws \Exception */ public static function activeWarehousesIds() { if (static::$activeWarehousesIds === null) { static::$activeWarehousesIds = Warehouse::getDb()->cache(function ($db) { return Warehouse::find()->where('is_active=1')->select('id')->orderBy(['sort_order' => SORT_ASC, 'id' => SORT_ASC])->asArray()->column($db); }, 86400, new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(Warehouse::className())]])); } return static::$activeWarehousesIds; }
/** * @param string $type * @return SpecialPriceList[]|array */ public static function getModelsByKey($type) { $cacheKey = static::className() . '_' . $type; if (false === ($results = Yii::$app->cache->get($cacheKey))) { $results = self::find()->where(['type' => $type])->all(); Yii::$app->cache->set($cacheKey, $results, 86400, new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(static::className())]])); } return $results; }
/** * Retrieves all decorators from db, using cache and static variable caching * @return ContentDecorator[] * @throws \Exception */ public static function getAllDecorators() { if (static::$allDecorators === null) { static::$allDecorators = self::getDb()->cache(function ($db) { return self::find()->orderBy(['sort_order' => SORT_ASC])->all($db); }, 86400, new TagDependency(['tags' => ActiveRecordHelper::getCommonTag(self::className())])); } return static::$allDecorators; }
public function down() { $this->dropTable('{{%addon}}'); $this->dropTable('{{%addon_category}}'); $this->dropTable('{{%addon_bindings}}'); $this->delete('{{%object}}', ['name' => 'Addon']); $this->delete('{{%backend_menu}}', ['name' => 'Addons']); \yii\caching\TagDependency::invalidate(Yii::$app->cache, [\devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag(\app\backend\models\BackendMenu::className())]); $this->dropColumn('{{%order_item}}', 'addon_id'); }
public static function availableAddons($id) { $cacheKey = 'Addons4' . $id; $addons = Yii::$app->cache->get($cacheKey); if ($addons === false) { $addons = Addon::findAll(['addon_category_id' => $id]); Yii::$app->cache->set($cacheKey, $addons, 86400, new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(Addon::className()), ActiveRecordHelper::getCommonTag(AddonCategory::className())]])); } return $addons; }
protected function getManagersList() { $managers = Yii::$app->cache->get('ManagersList'); if ($managers === false) { $managers = User::find()->join('INNER JOIN', '{{%auth_assignment}}', '{{%auth_assignment}}.user_id = ' . User::tableName() . '.id')->where(['{{%auth_assignment}}.item_name' => 'manager'])->all(); $managers = ArrayHelper::map($managers, 'id', 'username'); Yii::$app->cache->set('ManagersList', $managers, 86400, new TagDependency(['tags' => [\devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag(User::className())]])); } return $managers; }
/** * @inheritdoc * @return string */ public function run() { $cacheKey = "PlainCategoriesWidget:" . $this->root_category_id . ":" . $this->viewFile; $result = Yii::$app->cache->get($cacheKey); if ($result === false) { $categories = Category::getByParentId($this->root_category_id); $result = $this->render($this->viewFile, ['categories' => $categories]); Yii::$app->cache->set($cacheKey, $result, 86400, new \yii\caching\TagDependency(['tags' => ActiveRecordHelper::getCommonTag(Category::className())])); } return $result; }
/** * @return ActiveRecord[] */ public function getChildren() { $cacheKey = 'TreeChildren:' . $this->owner->className() . ':' . $this->owner->{$this->idAttribute}; $children = Yii::$app->cache->get($cacheKey); if ($children === false) { /** @var $className ActiveRecord */ $className = $this->owner->className(); $children = $className::find()->where([$this->parentIdAttribute => $this->owner->{$this->idAttribute}])->orderBy($this->sortOrder)->all(); Yii::$app->cache->set($cacheKey, $children, 86400, new TagDependency(['tags' => [\devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag($className)]])); } return $children; }
/** * Returns all enabled sorts as array of rows * Caches through cache and static variable * @return array */ public static function enabledSorts() { if (static::$_cachedRows === null) { $cacheKey = "ProductListingSorts:all:arrayOfRows"; static::$_cachedRows = Yii::$app->cache->get($cacheKey); if (!is_array(static::$_cachedRows)) { static::$_cachedRows = ProductListingSort::find()->where(['enabled' => 1])->orderBy('sort_order ASC')->indexBy('id')->asArray()->all(); Yii::$app->cache->set($cacheKey, static::$_cachedRows, 86400, new TagDependency(['tags' => [\devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag(static::className())]])); } } return static::$_cachedRows; }
/** * Returns all db-stored variations in array representation * * @param bool $force True if you want to refresh static-variable cache * @return array */ public static function getAllVariations($force = false) { if (static::$allVariations === null || $force === true) { $cacheKey = 'AllThemeVariations'; static::$allVariations = Yii::$app->cache->get($cacheKey); if (static::$allVariations === false) { static::$allVariations = ThemeVariation::find()->orderBy(['exclusive' => SORT_DESC])->asArray()->all(); Yii::$app->cache->set($cacheKey, static::$allVariations, 86400, new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(ThemeVariation::className())]])); } } return static::$allVariations; }
/** * Get measure by id. * @param int $id * @return Measure */ public static function findById($id) { $cacheKey = 'Measure: ' . $id; $measure = Yii::$app->cache->get($cacheKey); if ($measure === false) { $measure = self::findOne($id); if (is_null($measure)) { return null; } Yii::$app->cache->set($cacheKey, $measure, 86400, new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(self::className()), ActiveRecordHelper::getObjectTag(self::className(), $id)]])); } return $measure; }
/** * @return string */ public function run() { parent::run(); if (!$this->product instanceof Product) { return ''; } $cacheKey = 'RelatedProduct:' . implode('_', [$this->viewFile, $this->product, json_encode($this->additional)]); if (false !== ($cache = \Yii::$app->cache->get($cacheKey))) { return $cache; } $result = $this->render($this->viewFile, ['model' => $this->product, 'products' => $this->product->relatedProducts, 'additional' => $this->additional]); \Yii::$app->cache->set($cacheKey, $result, 0, new TagDependency(['tags' => [ActiveRecordHelper::getObjectTag(Product::className(), $this->product->id), ActiveRecordHelper::getCommonTag(\app\modules\shop\models\RelatedProduct::className())]])); return $result; }
/** * @param $categoryId * @return FilterSets[] */ public static function getForCategoryId($categoryId) { Yii::beginProfile('FilterSets.GetForCategory ' . $categoryId); $category = Category::findById($categoryId); if ($category === null) { return []; } $categoryIds = $category->getParentIds(); $filter_sets = Yii::$app->db->cache(function ($db) use($categoryIds, $category) { return FilterSets::find()->where(['in', 'category_id', $categoryIds])->andWhere(['delegate_to_children' => 1])->orWhere(['category_id' => $category->id])->orderBy(['sort_order' => SORT_ASC])->all(); }, 86400, new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(static::className())]])); Yii::endProfile('FilterSets.GetForCategory ' . $categoryId); return $filter_sets; }
public function run() { $cacheKey = md5(__METHOD__); if (false === ($items = \Yii::$app->cache->get($cacheKey))) { $parents = ArrayHelper::map(PostMeta::find()->where(['parent' => null])->orWhere(['parent' => 0])->orderBy(['order' => SORT_ASC])->all(), 'id', 'name'); foreach ($parents as $key => $value) { $nodes[$value] = PostMeta::find()->where(['parent' => $key])->asArray()->all(); } $items = $nodes; //一天缓存 \Yii::$app->cache->set($cacheKey, $items, 86400, new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(PostMeta::className())]])); } return $this->render('node', ['nodes' => $items]); }
/** * Get all model records as array key => value. * @param string $className * @param string $keyAttribute * @param string $valueAttribute * @param bool $useCache * @return array */ public static function getModelMap($className, $keyAttribute, $valueAttribute, $useCache = true) { /** @var ActiveRecord $className */ $cacheKey = 'Map: ' . $className::tableName() . ':' . $keyAttribute . ':' . $valueAttribute; if (isset(Helper::$modelMaps[$cacheKey]) === false) { Helper::$modelMaps[$cacheKey] = $useCache ? Yii::$app->cache->get($cacheKey) : false; if (Helper::$modelMaps[$cacheKey] === false) { Helper::$modelMaps[$cacheKey] = ArrayHelper::map($className::find()->asArray()->all(), $keyAttribute, $valueAttribute); if ($useCache === true) { Yii::$app->cache->set($cacheKey, Helper::$modelMaps[$cacheKey], 86400, new TagDependency(['tags' => [\devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag($className)]])); } } } return Helper::$modelMaps[$cacheKey]; }
/** * Handle decoration * @param \yii\base\Controller $controller * @param string $viewFile * @param array $params * @return void */ public function decorate($controller, $viewFile, $params) { if (!Yii::$app->getModule("backend")->isBackend()) { $baseContentKey = get_class($params['model']) . ':' . (isset($params['model']->id) ? $params['model']->id : '') . ':'; $view = $controller->view; $dependency = new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(app\modules\core\models\ContentBlock::className()), ActiveRecordHelper::getCommonTag(get_class($params['model']))]]); $view->title = $this->processChunks($view->title, $baseContentKey . "title", $dependency); if (!empty($view->blocks["content"])) { $view->blocks["content"] = $this->processChunks($view->blocks["content"], $baseContentKey . "content", $dependency); } if (!empty($view->blocks["announce"])) { $view->blocks["announce"] = $this->processChunks($view->blocks["announce"], $baseContentKey . "announce", $dependency); } } }
/** * @return array|mixed */ private static function getAllDiscounts() { if (self::$allDiscounts === []) { $cacheKey = 'getAllDiscounts'; if (!(self::$allDiscounts = Yii::$app->cache->get($cacheKey))) { self::$allDiscounts = []; $discounts = Discount::find()->all(); foreach ($discounts as $discount) { self::$allDiscounts[$discount->appliance][] = $discount; } Yii::$app->cache->set($cacheKey, self::$allDiscounts, 86400, new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(Discount::className())]])); } } return self::$allDiscounts; }
public static function renderCounters(Event $event) { if (isset($event->sender->context->module) && in_array($event->sender->context->module->id . '/' . $event->sender->context->id, $event->data)) { $counter_str = ''; /* @var $counters Counter[] */ if (false === ($counters = \Yii::$app->getCache()->get(\Yii::$app->getModule('seo')->cacheConfig['counterCache']['name']))) { $counters = self::find()->all(); \Yii::$app->getCache()->set(\Yii::$app->getModule('seo')->cacheConfig['counterCache']['name'], $counters, \Yii::$app->getModule('seo')->cacheConfig['counterCache']['expire'], new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(self::className())]])); } foreach ($counters as $counter) { $counter_str .= "\n<!-- {$counter->name} counter -->\n"; $counter_str .= $counter->code; $counter_str .= "\n<!-- /{$counter->name} counter -->\n"; } echo $counter_str; } }
/** * @return array [[DropDownList]] */ public static function getOrderStatusArray($asHtml = false) { $cacheKey = 'OrderStatusItems:' . implode(':', [intval($asHtml)]); $items = Yii::$app->cache->get($cacheKey); if ($items !== false) { return $items; } $data = self::find()->select(['order_status_id', 'name', 'color'])->orderBy('name ASC')->asArray()->all(); $cache_tags = [ActiveRecordHelper::getCommonTag(static::className())]; foreach ($data as $val) { $key = $val['order_status_id']; $items[$key] = $asHtml ? Html::badge($val['name'], ['class' => 'btn btn-xs btn-block ' . $val['color']]) : $val['name']; $cache_tags[] = ActiveRecordHelper::getObjectTag(static::className(), $key); } Yii::$app->cache->set($cacheKey, $items, 86400, new TagDependency(['tags' => $cache_tags])); return $items; }
public static function renderCounters(Event $event) { if (\Yii::$app->request->isAjax === false && \Yii::$app->controller->module instanceof BackendModule === false && \Yii::$app->controller instanceof BackendController === false) { $counter_str = ''; /* @var $counters Counter[] */ if (false === ($counters = \Yii::$app->getCache()->get(\Yii::$app->getModule('seo')->cacheConfig['counterCache']['name']))) { $counters = self::find()->all(); \Yii::$app->getCache()->set(\Yii::$app->getModule('seo')->cacheConfig['counterCache']['name'], $counters, \Yii::$app->getModule('seo')->cacheConfig['counterCache']['expire'], new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(self::className())]])); } foreach ($counters as $counter) { $counter_str .= "\n<!-- {$counter->name} counter -->\n"; $counter_str .= $counter->code; $counter_str .= "\n<!-- /{$counter->name} counter -->\n"; } echo $counter_str; } }
/** * Lists configurables by tabs and saves configuration * @return string * @throws \Exception * @throws \yii\web\ServerErrorHttpException */ public function actionIndex() { /** @var Configurable[] $models */ $models = Configurable::getDb()->cache(function ($db) { return Configurable::find()->orderBy(['sort_order' => SORT_ASC])->all($db); }, 86400, new TagDependency(['tags' => ActiveRecordHelper::getCommonTag(Configurable::className())])); foreach ($models as $model) { $configurableModel = $model->getConfigurableModel(); $configurableModel->loadState(); } if (Yii::$app->request->isPost === true) { if (ConfigurationUpdater::updateConfiguration($models, true)) { return $this->refresh(); } } return $this->render('index', ['models' => $models]); }
/** * @return array [[DropDownList]] */ public static function getPaymentMethodArray() { $cacheKey = 'PaymentMethodItems:' . implode(':', []); $items = Yii::$app->cache->get($cacheKey); if ($items !== false) { return $items; } $data = self::find()->select(['payment_method_id', 'name'])->orderBy('name ASC')->asArray()->all(); $cache_tags = [ActiveRecordHelper::getCommonTag(static::className())]; foreach ($data as $val) { $key = $val['payment_method_id']; $items[$key] = $val['name']; $cache_tags[] = ActiveRecordHelper::getObjectTag(static::className(), $key); } Yii::$app->cache->set($cacheKey, $items, 86400, new TagDependency(['tags' => $cache_tags])); return $items; }
public function run() { $cacheKey = static::className() . ':' . implode("_", [$this->model->object->id, $this->model->id, $this->viewFile, $this->limit, $this->offset, $this->thumbnailOnDemand ? '1' : '0', $this->thumbnailWidth, $this->thumbnailHeight, $this->useWatermark]); $result = Yii::$app->cache->get($cacheKey); if ($result === false) { if ($this->offset > 0 || !is_null($this->limit)) { $images = $this->model->getImages()->limit($this->limit)->offset($this->offset)->all(); } else { $images = $this->model->images; } if ($this->noImageOnEmptyImages === true && count($images) === 0) { return $this->render('noimage', ['model' => $this->model, 'thumbnailOnDemand' => $this->thumbnailOnDemand, 'thumbnailWidth' => $this->thumbnailWidth, 'thumbnailHeight' => $this->thumbnailHeight, 'useWatermark' => $this->useWatermark, 'additional' => $this->additional]); } $result = $this->render($this->viewFile, ['model' => $this->model, 'images' => $images, 'thumbnailOnDemand' => $this->thumbnailOnDemand, 'thumbnailWidth' => $this->thumbnailWidth, 'thumbnailHeight' => $this->thumbnailHeight, 'useWatermark' => $this->useWatermark, 'additional' => $this->additional]); Yii::$app->cache->set($cacheKey, $result, 86400, new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(Image::className()), ActiveRecordHelper::getCommonTag($this->model->className())]])); } return $result; }
/** * @inheritdoc */ public function init() { parent::init(); if ($this->slider_id === null && $this->slider_name === null && $this->slider === null) { throw new InvalidConfigException("Either slider, slider_id or slider_name should be set."); } if ($this->slider === null) { if ($this->slider_name !== null) { $this->slider = Yii::$app->cache->get("Slider:name:" . $this->slider_name); if ($this->slider === false) { $this->slider = Slider::find()->where(['name' => $this->slider_name])->one(); Yii::$app->cache->set("Slider:name:" . $this->slider_name, $this->slider, 86400, new \yii\caching\TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(Slider::className())]])); } } else { $this->slider = Slider::findById($this->slider_id); } } }