public function run()
 {
     $id = $this->getId();
     $this->plugins = ArrayHelper::merge($this->plugins, ['checkbox']);
     $items = [];
     if (empty($this->selectedItems)) {
         $parent = Category::findById(Yii::$app->request->get('parent_id'));
         while ($parent instanceof Category) {
             $this->selectedItems[] = $parent->id;
             $parent = $parent->parent;
         }
     }
     $this->routes['getTree'] = ArrayHelper::merge($this->routes['getTree'], ['selectedItems' => implode(',', $this->selectedItems)]);
     if (isset($this->routes['edit'])) {
         $items['edit'] = ['label' => Yii::t('app', 'Edit'), 'icon' => 'fa fa-pencil', 'action' => new JsExpression("function (a) {\n                        var \$object = \$(a.reference[0]);\n                        document.location = " . Json::encode(Url::to($this->routes['edit'])) . "\n                            + '?id=' + \$object.attr('data-id') + '&parent_id=' +\n                            \$object.attr('data-parent-id');\n                        }")];
     }
     if (isset($this->routes['open'])) {
         $items['open'] = ['label' => Yii::t('app', 'Open'), 'icon' => 'fa fa-folder-open', 'action' => new JsExpression("function (a) {\n                        var \$object = \$(a.reference[0]);\n                        document.location = " . Json::encode(Url::to($this->routes['open'])) . "\n                            + '?parent_id=' + \$object.attr('data-id');\n                        }")];
     }
     if (isset($this->routes['create'])) {
         $items['create'] = ['label' => Yii::t('app', 'Create'), 'icon' => 'fa fa-plus-circle', 'action' => new JsExpression("function (a) {\n                        var \$object = \$(a.reference[0]);\n                        document.location = " . Json::encode(Url::to($this->routes['create'])) . "\n                            + '?parent_id=' + \$object.attr('data-id');\n                        }")];
     }
     if (isset($this->routes['delete'])) {
         $items['delete'] = ['label' => Yii::t('app', 'Delete'), 'icon' => 'fa fa-trash-o', 'action' => new JsExpression("function (a) {\n                        var \$object = \$(a.reference[0]);\n                        document.location = " . Json::encode(Url::to($this->routes['delete'])) . "\n                            + '?id=' + \$object.attr('data-id');\n                        }")];
     }
     $options = ['state' => ['key' => $this->stateKey], 'plugins' => $this->plugins, 'core' => ['check_callback' => true, 'data' => ['url' => new JsExpression("function (node) {\n                            return " . Json::encode(Url::to($this->routes['getTree'])) . ";\n                        }"), 'data' => new JsExpression("function (node) {\n                            return { 'id' : node.id };\n                        }")], 'multiple' => $this->multiple], 'checkbox' => ['three_state' => false], 'contextmenu' => ['items' => $items], 'dnd' => ['is_draggable' => false]];
     if (count($this->types) > 0) {
         $options['types'] = $this->types;
     }
     $this->selectOptions['id'] = $id . '-select';
     return $this->render('JSSelectableTree', ['id' => $id, 'flagFieldName' => $this->flagFieldName, 'fieldName' => $this->fieldName, 'model' => $this->model, 'multiple' => $this->multiple, 'options' => Json::encode($options), 'routes' => $this->routes, 'selectedItems' => $this->selectedItems, 'selectLabel' => $this->selectLabel, 'selectLabelOptions' => $this->selectLabelOptions, 'selectOptions' => $this->selectOptions, 'selectParents' => $this->selectParents]);
 }
Beispiel #2
0
 /**
  * @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;
 }
 /**
  * @inheritdoc
  */
 public function appendPart($route, $parameters = [], &$used_params = [], &$cacheTags = [])
 {
     /*
         В parameters должен храниться last_category_id
         Если его нет - используем parameters.category_id
     */
     $category_id = null;
     if (isset($parameters['last_category_id'])) {
         $category_id = $parameters['last_category_id'];
     } elseif (isset($parameters['category_id'])) {
         $category_id = $parameters['category_id'];
     }
     $used_params[] = 'last_category_id';
     $used_params[] = 'category_id';
     if ($category_id === null) {
         return false;
     }
     $category = Category::findById($category_id);
     if (is_object($category) === true) {
         $parentIds = $category->getParentIds();
         foreach ($parentIds as $id) {
             $cacheTags[] = ActiveRecordHelper::getObjectTag(Category::className(), $id);
         }
         $cacheTags[] = ActiveRecordHelper::getObjectTag(Category::className(), $category_id);
         return $category->getUrlPath($this->include_root_category);
     } else {
         return false;
     }
 }
 public function actionIndex($category_id = null)
 {
     $searchModel = new Category();
     $searchModel->active = 1;
     $params = Yii::$app->request->get();
     $dataProvider = $searchModel->search($params);
     $selectedCategory = null;
     if ($category_id !== null) {
         $selectedCategory = Category::findById($category_id);
     }
     if ($selectedCategory !== null) {
         if (Yii::$app->request->isPost === true) {
             $newProperty = isset($_GET['add_property_id']) ? Property::findById($_GET['add_property_id']) : null;
             if ($newProperty !== null) {
                 $filterSet = new FilterSets();
                 $filterSet->category_id = $selectedCategory->id;
                 $filterSet->property_id = $newProperty->id;
                 $filterSet->sort_order = 65535;
                 $filterSet->save();
             }
         }
     }
     $groups = PropertyGroup::getForObjectId(Object::getForClass(Product::className())->id, false);
     $propertiesDropdownItems = [];
     foreach ($groups as $group) {
         $item = ['label' => $group->name, 'url' => '#', 'items' => []];
         $properties = Property::getForGroupId($group->id);
         foreach ($properties as $prop) {
             $item['items'][] = ['label' => $prop->name, 'url' => '?category_id=' . $category_id . '&add_property_id=' . $prop->id, 'linkOptions' => ['class' => 'add-property-to-filter-set', 'data-property-id' => $prop->id, 'data-action' => 'post']];
         }
         $propertiesDropdownItems[] = $item;
     }
     return $this->render('index', ['dataProvider' => $dataProvider, 'searchModel' => $searchModel, 'selectedCategory' => $selectedCategory, 'propertiesDropdownItems' => $propertiesDropdownItems]);
 }
Beispiel #5
0
 /**
  * @return ActiveRecord
  */
 public function getParent()
 {
     $cacheKey = 'TreeParent:' . $this->owner->className() . ':' . $this->owner->getAttribute($this->idAttribute);
     /** @var $parent ActiveRecord */
     $parent = Yii::$app->cache->get($cacheKey);
     if ($parent === false) {
         $className = $this->owner->className();
         $parent = new $className();
         $parent_id = $this->owner->getAttribute($this->parentIdAttribute);
         if ($parent_id < 1) {
             return null;
         }
         /* findById does not have a calling standard and uses different parameters. For example isActive = 1.
          * But we must get a parent model by primary id only.
          * Uncomment this code if you unify findById method.
          */
         // if ($parent->hasMethod('findById')) {
         //     $parent = $parent->findById($parent_id);
         // } else {
         if ($parent instanceof Category) {
             $parent = Category::findById($parent_id, null);
         } else {
             $parent = $parent->findOne($parent_id);
         }
         Yii::$app->cache->set($cacheKey, $parent, 86400, new TagDependency(['tags' => [\devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag($className)]]));
     }
     return $parent;
 }
Beispiel #6
0
 protected function getCategoryLinks($id)
 {
     $model = Category::findById($id, null);
     if (!is_null($model)) {
         $this->frontendLink = Html::a($model->name, ['@category', 'model' => $model, 'category_group_id' => isset($model->category) ? $model->category->category_group_id : null]);
         $this->backendLink = Html::a($model->name, ['/shop/backend-category/edit', 'id' => $model->id, 'parent_id' => $model->parent_id, 'returnUrl' => Helper::getReturnUrl()]);
     }
 }
Beispiel #7
0
 /**
  * @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 = FilterSets::find()->where(['in', 'category_id', $categoryIds])->andWhere(['delegate_to_children' => 1])->orWhere(['category_id' => $category->id])->orderBy(['sort_order' => SORT_ASC])->all();
     Yii::endProfile('FilterSets.GetForCategory ' . $categoryId);
     return $filter_sets;
 }
Beispiel #8
0
 /**
  * @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;
 }
Beispiel #9
0
 public function run()
 {
     app\backend\assets\FrontendEditingAsset::register($this->view);
     $items = [['label' => Icon::show('dashboard') . ' ' . Yii::t('app', 'Backend'), 'url' => ['/backend/']]];
     switch (Yii::$app->requestedRoute) {
         case 'shop/product/list':
             if (isset($_GET['properties'])) {
                 $apply_if_params = [];
                 foreach ($_GET['properties'] as $property_id => $values) {
                     if (isset($values[0])) {
                         $apply_if_params[$property_id] = $values[0];
                     }
                 }
                 if (Yii::$app->response->dynamic_content_trait === true) {
                     $items[] = ['label' => Icon::show('puzzle') . ' ' . Yii::t('app', 'Edit Dynamic Content'), 'url' => ['/backend/dynamic-content/edit', 'id' => Yii::$app->response->matched_dynamic_content_trait_model->id]];
                 } else {
                     if (isset($_GET['properties'], $_GET['last_category_id'])) {
                         $items[] = ['label' => Icon::show('puzzle') . ' ' . Yii::t('app', 'Add Dynamic Content'), 'url' => ['/backend/dynamic-content/edit', 'DynamicContent' => ['apply_if_params' => Json::encode($apply_if_params), 'apply_if_last_category_id' => $_GET['last_category_id'], 'object_id' => Object::getForClass(app\modules\shop\models\Product::className())->id, 'route' => 'shop/product/list']]];
                     }
                 }
             } else {
                 // no properties selected - go to category edit page
                 if (isset($_GET['last_category_id'])) {
                     $reviewsLink = $this->getReviewEditParams("Category", intval($_GET['last_category_id']));
                     $cat = app\modules\shop\models\Category::findById($_GET['last_category_id']);
                     $items[] = ['label' => Icon::show('pencil') . ' ' . Yii::t('app', 'Edit category'), 'url' => ['/shop/backend-category/edit', 'id' => $cat->id, 'parent_id' => $cat->parent_id]];
                 }
             }
             break;
         case 'shop/product/show':
             if (isset($_GET['model_id'])) {
                 $reviewsLink = $this->getReviewEditParams("Product", intval($_GET['model_id']));
                 $items[] = ['label' => Icon::show('pencil') . ' ' . Yii::t('app', 'Edit product'), 'url' => ['/shop/backend-product/edit', 'id' => intval($_GET['model_id'])]];
             }
             break;
         case '/page/page/show':
         case '/page/page/list':
             if (isset($_GET['id'])) {
                 $page = app\modules\page\models\Page::findById($_GET['id']);
                 $reviewsLink = $this->getReviewEditParams("Page", $_GET['id']);
                 $items[] = ['label' => Icon::show('pencil') . ' ' . Yii::t('app', 'Edit page'), 'url' => ['/page/backend/edit', 'id' => $page->id, 'parent_id' => $page->parent_id]];
             }
             break;
     }
     if (!empty($reviewsLink)) {
         $items[] = $reviewsLink;
     }
     return $this->render('floating-panel', ['items' => $items, 'bottom' => $this->bottom]);
 }
 public function appendPart($route, $parameters = [], &$used_params = [], &$cacheTags = [])
 {
     $used_params[] = 'categories';
     $used_params[] = 'category_group_id';
     $used_params[] = $this->model_category_attribute;
     $attribute_name = $this->model_category_attribute;
     $category_id = $this->model->{$attribute_name};
     /** @var Category $category */
     $category = Category::findById($category_id);
     if (is_object($category) === true) {
         $parentIds = $category->getParentIds();
         foreach ($parentIds as $id) {
             $cacheTags[] = ActiveRecordHelper::getObjectTag(Category::className(), $id);
         }
         $cacheTags[] = ActiveRecordHelper::getObjectTag(Category::className(), $category_id);
         return $category->getUrlPath($this->include_root_category);
     } else {
         return false;
     }
 }
?>
        </article>

    </div>
</section>

<input type="hidden" name="DynamicContent[apply_if_params]" id="apply_if_params">


<?php 
BackendWidget::begin(['title' => Yii::t('app', 'Match settings'), 'icon' => 'cogs', 'footer' => $this->blocks['submit']]);
?>
<div id="properties">
    <?php 
$url = Url::to(['/shop/backend-category/autocomplete']);
$category = $model->apply_if_last_category_id > 0 ? \app\modules\shop\models\Category::findById($model->apply_if_last_category_id) : null;
?>
    <?php 
echo $form->field($model, 'apply_if_last_category_id')->widget(Select2::classname(), ['options' => ['placeholder' => 'Search for a category ...'], 'pluginOptions' => ['allowClear' => true, 'ajax' => ['url' => $url, 'dataType' => 'json', 'data' => new JsExpression('function(term,page) { return {search:term}; }'), 'results' => new JsExpression('function(data,page) { return {results:data.results}; }')]], 'initValueText' => !is_null($category) ? $category->name : '']);
?>
    <div class="row">
        <div class="col-md-10 col-md-offset-2">
            <a href="#" class="btn btn-md btn-primary add-property">
                <?php 
echo Icon::show('plus');
?>
                <?php 
echo Yii::t('app', 'Add property');
?>
            </a>
            <br>
Beispiel #12
0
use app\modules\shop\controllers\BackendCategoryController;
use kartik\helpers\Html;
use kartik\icons\Icon;
use app\backend\components\ActiveForm;
use kartik\widgets\DateTimePicker;
use yii\helpers\ArrayHelper;
use app\backend\components\Helper;
use app\modules\shop\ShopModule;
use yii\helpers\Url;
/**
 * @var $this \yii\web\View
 * @var $model \app\modules\shop\models\Category
 */
$this->title = Yii::t('app', 'Category edit');
$this->params['breadcrumbs'][] = ['url' => ['index'], 'label' => Yii::t('app', 'Categories')];
if ($model->parent_id > 0 && null !== ($parent = \app\modules\shop\models\Category::findById($model->parent_id, null, null))) {
    $this->params['breadcrumbs'][] = ['url' => ['index', 'id' => $parent->id, 'parent_id' => $parent->parent_id], 'label' => $parent->name];
}
$this->params['breadcrumbs'][] = $this->title;
?>

<?php 
echo app\widgets\Alert::widget(['id' => 'alert']);
?>

<?php 
$form = ActiveForm::begin(['id' => 'category-form', 'type' => ActiveForm::TYPE_HORIZONTAL]);
?>

<?php 
$this->beginBlock('submit');
Beispiel #13
0
 /**
  * Returns product main category model instance using per-request Identity Map
  * @return Category|null
  */
 public function getMainCategory()
 {
     return Category::findById($this->main_category_id, null);
 }
Beispiel #14
0
 ?>
                             </td>
                             <td>
                                 <?php 
 echo Html::checkbox('delegateToChildren[' . $filterSet->id . ']', $filterSet->delegate_to_children === 1, ['class' => 'delegate-property-checkbox', 'data-filterset-id' => $filterSet->id, 'data-inherited' => $filterSet->category_id === $selectedCategory->id ? '0' : '1']);
 ?>
                             </td>
                             <td>
                                 <?php 
 echo Html::checkbox('isRangeSlider[' . $filterSet->id . ']', $filterSet->is_range_slider === 1, ['class' => 'is-range-slider-checkbox', 'data-filterset-id' => $filterSet->id]);
 ?>
                             </td>
                             <td>
                                 <?php 
 if ($filterSet->category_id !== $selectedCategory->id) {
     $cat = \app\modules\shop\models\Category::findById($filterSet->category_id);
     echo Html::a($cat->name, ['/shop/backend-filter-sets/index', 'category_id' => $cat->id]);
 } else {
     echo '-';
 }
 ?>
                             </td>
                             <td>
                                 <?php 
 echo Html::a(Icon::show('trash-o'), ['/shop/backend-filter-sets/delete-filter-set', 'id' => $filterSet->id, 'category_id' => $selectedCategory->id], ['class' => 'btn btn-danger btn-xs', 'data-action' => 'post']);
 ?>
                                 <?php 
 if ($property->has_static_values === 1) {
     ?>
                                     <a href="#psv-table-<?php 
     echo $property->id;
 public function actionDelete($id = null, $parent_id = null, $mode = null)
 {
     if (null === $id || null === ($model = Category::findById($id, null, null))) {
         throw new NotFoundHttpException();
     }
     $model->deleteMode = $mode;
     if (!$model->delete()) {
         Yii::$app->session->setFlash('success', Yii::t('app', 'The object is placed in the cart'));
     } else {
         Yii::$app->session->setFlash('success', Yii::t('app', 'Object has been removed'));
     }
     return $this->redirect(Yii::$app->request->get('returnUrl', Url::to(['index', 'parent_id' => $model->parent_id])));
 }
Beispiel #16
0
 public static function renderEcommerceCounters(Event $event)
 {
     $order = Order::findOne(['id' => $event->data['orderId']]);
     $config = Config::getModelByKey('ecommerceCounters');
     if (empty($event->data['orderId']) || empty($config) || empty($order)) {
         return;
     }
     $orderItems = OrderItem::findAll(['order_id' => $event->data['orderId']]);
     if (!empty($orderItems)) {
         $products = [];
         foreach ($orderItems as $item) {
             $product = Product::findById($item->product_id, null, null);
             if (empty($product)) {
                 continue;
             }
             $category = Category::findById($product->main_category_id);
             $category = empty($category) ? 'Магазин' : str_replace('\'', '', $category->name);
             $products[] = ['id' => $product->id, 'name' => str_replace('\'', '', $product->name), 'price' => number_format($product->price, 2, '.', ''), 'category' => $category, 'qnt' => $item->quantity];
         }
         $order = ['id' => $order->id, 'total' => number_format($order->total_price, 2, '.', '')];
         echo Yii::$app->view->renderFile(Yii::getAlias('@app/modules/seo/views/manage/_ecommerceCounters.php'), ['order' => $order, 'products' => $products, 'config' => Json::decode($config->value)]);
     }
 }
 /**
  * This function build array for widget "Breadcrumbs"
  * @param Category $selCat - model of current category
  * @param Product|null $product - model of product, if current page is a page of product
  * Return an array for widget or empty array
  */
 private function buildBreadcrumbsArray($selCat, $product = null)
 {
     if ($selCat === null) {
         return [];
     }
     // init
     $breadcrumbs = [];
     if ($product !== null) {
         $crumbs[$product->slug] = !empty($product->breadcrumbs_label) ? $product->breadcrumbs_label : '';
     }
     $crumbs[$selCat->slug] = $selCat->breadcrumbs_label;
     // get basic data
     $parent = $selCat->parent_id > 0 ? Category::findById($selCat->parent_id) : null;
     while ($parent !== null) {
         $crumbs[$parent->slug] = $parent->breadcrumbs_label;
         $parent = $parent->parent;
     }
     // build array for widget
     $url = '';
     $crumbs = array_reverse($crumbs, true);
     foreach ($crumbs as $slug => $label) {
         $url .= '/' . $slug;
         $breadcrumbs[] = ['label' => $label, 'url' => $url];
     }
     unset($breadcrumbs[count($breadcrumbs) - 1]['url']);
     // last item is not a link
     if (isset(Yii::$app->response->blocks['breadcrumbs_label'])) {
         // last item label rewrited through prefiltered page or something similar
         $breadcrumbs[count($breadcrumbs) - 1]['label'] = Yii::$app->response->blocks['breadcrumbs_label'];
     }
     return $breadcrumbs;
 }
Beispiel #18
0
 /**
  * renders url according to given data
  * @param $chunkData
  * @param TagDependency $dependency
  * @return string
  */
 private static function renderUrl($chunkData, &$dependency)
 {
     $expression = '%(?P<objectName>[^#]+?)#(?P<objectId>[\\d]+?)$%';
     $output = '';
     preg_match($expression, $chunkData['key'], $m);
     if (true === isset($m['objectName'], $m['objectId'])) {
         $id = (int) $m['objectId'];
         switch (strtolower($m['objectName'])) {
             case "page":
                 if (null !== ($model = Page::findById($id))) {
                     $dependency->tags[] = ActiveRecordHelper::getCommonTag(Page::className());
                     $dependency->tags[] = $model->objectTag();
                     $output = Url::to(['@article', 'id' => $id]);
                 }
                 break;
             case "category":
                 if (null !== ($model = Category::findById($id))) {
                     $dependency->tags[] = ActiveRecordHelper::getCommonTag(Category::className());
                     $dependency->tags[] = $model->objectTag();
                     $output = Url::to(['@category', 'last_category_id' => $id, 'category_group_id' => $model->category_group_id]);
                 }
                 break;
             case "product":
                 if (null !== ($model = app\modules\shop\models\Product::findById($id))) {
                     $dependency->tags[] = ActiveRecordHelper::getCommonTag(Product::className());
                     $dependency->tags[] = $model->objectTag();
                     $output = Url::to(['@product', 'model' => $model, 'category_group_id' => $model->getMainCategory()->category_group_id]);
                 }
                 break;
         }
     }
     return $output;
 }
Beispiel #19
0
 /**
  * This function build array for widget "Breadcrumbs"
  * @param Category $selCat - model of current category
  * @param Product|null $product - model of product, if current page is a page of product
  * @param array $properties - array of properties and static values
  * Return an array for widget or empty array
  */
 private function buildBreadcrumbsArray($selCat, $product = null, $properties = [])
 {
     if ($selCat === null) {
         return [];
     }
     // init
     $breadcrumbs = [];
     if ($product !== null) {
         $crumbs[$product->slug] = !empty($product->breadcrumbs_label) ? $product->breadcrumbs_label : '';
     }
     $crumbs[$selCat->slug] = $selCat->breadcrumbs_label;
     // get basic data
     $parent = $selCat->parent_id > 0 ? Category::findById($selCat->parent_id) : null;
     while ($parent !== null) {
         $crumbs[$parent->slug] = $parent->breadcrumbs_label;
         $parent = $parent->parent;
     }
     // build array for widget
     $url = '';
     $crumbs = array_reverse($crumbs, true);
     foreach ($crumbs as $slug => $label) {
         $url .= '/' . $slug;
         $breadcrumbs[] = ['label' => $label, 'url' => $url];
     }
     if (is_null($product) && $this->module->showFiltersInBreadcrumbs && !empty($properties)) {
         $route = ['@category', 'last_category_id' => $selCat->id, 'category_group_id' => $selCat->category_group_id];
         $params = [];
         foreach ($properties as $propertyId => $propertyStaticValues) {
             $localParams = $params;
             foreach ($propertyStaticValues as $propertyStaticValue) {
                 $psv = PropertyStaticValues::findById($propertyStaticValue);
                 if (is_null($psv)) {
                     continue;
                 }
                 $localParams[$propertyId][] = $propertyStaticValue;
                 $breadcrumbs[] = ['label' => $psv['name'], 'url' => array_merge($route, ['properties' => $localParams])];
             }
             $params[$propertyId] = $propertyStaticValues;
         }
     }
     unset($breadcrumbs[count($breadcrumbs) - 1]['url']);
     // last item is not a link
     if (isset(Yii::$app->response->blocks['breadcrumbs_label'])) {
         // last item label rewrited through prefiltered page or something similar
         $breadcrumbs[count($breadcrumbs) - 1]['label'] = Yii::$app->response->blocks['breadcrumbs_label'];
     }
     return $breadcrumbs;
 }
Beispiel #20
0
 public function parseRequest($manager, $request)
 {
     Yii::beginProfile("ObjectRule::parseRequest");
     $url = $request->getPathInfo();
     if (empty($url)) {
         Yii::endProfile("ObjectRule::parseRequest");
         return false;
     }
     $cacheKey = 'ObjectRule:' . $url . ':' . Json::encode($request->getQueryParams());
     $result = Yii::$app->cache->get($cacheKey);
     if ($result !== false) {
         Yii::endProfile("ObjectRule::parseRequest");
         $this->defineBlocksTitleAndView($result);
         return $result['result'];
     }
     $prefilteredPage = PrefilteredPages::getActiveByUrl($url);
     if ($prefilteredPage !== null) {
         $params = ['properties' => Json::decode($prefilteredPage['params'])];
         $category = Category::findById($prefilteredPage['last_category_id']);
         if ($category === null) {
             throw new NotFoundHttpException();
         }
         $params['category_group_id'] = $category->category_group_id;
         $params['last_category_id'] = $category->id;
         $data = ['blocks' => []];
         if (!empty($prefilteredPage['title'])) {
             $data['title'] = $prefilteredPage['title'];
         }
         if (!empty($prefilteredPage['meta_description'])) {
             $data['meta_description'] = $prefilteredPage['meta_description'];
         }
         $blocks = ['content', 'announce', 'breadcrumbs_label', 'h1'];
         foreach ($blocks as $block_name) {
             if (!empty($prefilteredPage[$block_name])) {
                 $data['blocks'][$block_name] = $prefilteredPage[$block_name];
             }
         }
         $data['is_prefiltered_page'] = true;
         if ($prefilteredPage['view_id'] > 0) {
             $data['viewId'] = $prefilteredPage['view_id'];
         }
         $data['result'] = ['shop/product/list', $params];
         $this->defineBlocksTitleAndView($data);
         Yii::$app->cache->set($cacheKey, $data, 86400, new TagDependency(['tags' => [ActiveRecordHelper::getObjectTag(PrefilteredPages::className(), $prefilteredPage['id']), ActiveRecordHelper::getObjectTag(Category::className(), $category->id)]]));
         return $data['result'];
     }
     $routes = ObjectRule::getRoutes();
     $cacheTags = [];
     foreach ($routes as $model) {
         /** @var UrlPart[] $handlers */
         $handlers = [];
         $object = Object::findById($model->object_id);
         foreach ($model->template as $t) {
             $handler = Yii::createObject($t);
             $handler->object = $object;
             $handlers[] = $handler;
         }
         $url_parts = [];
         $parameters = [];
         $next_part = $url;
         foreach ($handlers as $handler) {
             if (empty($next_part)) {
                 //break;
             }
             $result = $handler->getNextPart($url, $next_part, $url_parts);
             if ($result !== false && is_object($result) === true) {
                 $parameters = ArrayHelper::merge($parameters, $result->parameters);
                 $cacheTags = ArrayHelper::merge($cacheTags, $result->cacheTags);
                 // удалим leading slash
                 $next_part = ltrim($result->rest_part, '/');
                 $url_parts[] = $result;
             } elseif ($result === false && $handler->optional === false) {
                 continue;
             }
         }
         if (count($url_parts) == 0) {
             continue;
         }
         // в конце удачного парсинга next_part должен остаться пустым
         if (empty($next_part)) {
             $resultForCache = ['result' => [$model->route, $parameters]];
             if (isset($_POST['properties'], $parameters['properties'])) {
                 foreach ($_POST['properties'] as $key => $value) {
                     if (isset($parameters['properties'][$key])) {
                         $parameters['properties'][$key] = array_unique(ArrayHelper::merge($parameters['properties'][$key], $value));
                     } else {
                         $parameters['properties'][$key] = array_unique($value);
                     }
                 }
             } elseif (isset($_POST['properties'])) {
                 $parameters['properties'] = $_POST['properties'];
             }
             Yii::endProfile("ObjectRule::parseRequest");
             if (isset($parameters['properties'])) {
                 foreach ($parameters['properties'] as $key => $values) {
                     foreach ($parameters['properties'][$key] as $index => $value) {
                         if ($value === '') {
                             unset($parameters['properties'][$key][$index]);
                         }
                     }
                     if (count($parameters['properties'][$key]) === 0) {
                         unset($parameters['properties'][$key]);
                     }
                 }
             }
             $result = [$model->route, $parameters];
             Yii::$app->cache->set($cacheKey, $resultForCache, 86400, new TagDependency(['tags' => $cacheTags]));
             return $result;
         }
     }
     Yii::endProfile("ObjectRule::parseRequest");
     return false;
     // this rule does not apply
 }