Пример #1
0
 /**
  * @param $term
  * @return string JSON
  */
 public function actionAutoCompleteSearch($term)
 {
     Yii::$app->response->format = Response::FORMAT_JSON;
     $search = new Search();
     $search->q = $term;
     $search->on(Search::QUERY_SEARCH_PRODUCTS_BY_DESCRIPTION, function (SearchEvent $event) {
         $event->setFunctionSearch(function ($activeQuery) {
             $activeQuery->limit(Yii::$app->getModule('core')->autoCompleteResultsCount);
             return Product::find()->select(['id', 'name', 'main_category_id', 'slug', 'sku'])->where(['id' => $activeQuery->all()])->all();
         });
     });
     $products = $search->searchProductsByDescription();
     $result = [];
     foreach ($products as $product) {
         /** @var Product $product */
         $result[] = ['id' => $product->id, 'name' => $product->name, 'url' => Url::toRoute(['@product', 'model' => $product, 'category_group_id' => $product->getMainCategory()->category_group_id], true)];
     }
     return $result;
 }
Пример #2
0
 /**
  * Search handler
  * @return array
  * @throws ForbiddenHttpException
  */
 public function actionSearch()
 {
     $headers = Yii::$app->response->getHeaders();
     $headers->set('X-Robots-Tag', 'none');
     $headers->set('X-Frame-Options', 'SAMEORIGIN');
     $headers->set('X-Content-Type-Options', 'nosniff');
     if (!Yii::$app->request->isAjax) {
         throw new ForbiddenHttpException();
     }
     $model = new Search();
     $model->load(Yii::$app->request->get());
     $cacheKey = 'ProductSearchIds: ' . $model->q;
     $ids = Yii::$app->cache->get($cacheKey);
     if ($ids === false) {
         $ids = ArrayHelper::merge($model->searchProductsByDescription(), $model->searchProductsByProperty());
         Yii::$app->cache->set($cacheKey, $ids, 86400, new TagDependency(['tags' => ActiveRecordHelper::getCommonTag(Product::className())]));
     }
     /** @var \app\modules\shop\ShopModule $module */
     $module = Yii::$app->modules['shop'];
     $pages = new Pagination(['defaultPageSize' => $module->searchResultsLimit, 'forcePageParam' => false, 'totalCount' => count($ids)]);
     $cacheKey .= ' : ' . $pages->offset;
     $products = Yii::$app->cache->get($cacheKey);
     if ($products === false) {
         $products = Product::find()->where(['in', '`id`', array_slice($ids, $pages->offset, $pages->limit)])->addOrderBy('sort_order')->with('images')->all();
         Yii::$app->cache->set($cacheKey, $products, 86400, new TagDependency(['tags' => ActiveRecordHelper::getCommonTag(Product::className())]));
     }
     Yii::$app->response->format = Response::FORMAT_JSON;
     return ['view' => $this->renderAjax('search', ['model' => $model, 'pages' => $pages, 'products' => $products]), 'totalCount' => count($ids)];
 }