示例#1
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)];
 }