CategoryController.php 2.37 KB
<?php

namespace frontend\controllers;

use common\modules\product\models\Category;
use common\modules\product\models\Product;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\helpers\VarDumper;

/**
 * Category controller
 */
class CategoryController extends Controller
{
    /**
     * Displays
     *
     * @param integer $id
     * @return string
     */
    public function actionIndex($id)
    {
        $category = $this->findModel($id, 0);
        $query = Category::find()
            ->where([
                'parent_id' => $category->category_id
            ]);
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => false,
        ]);
        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'category' => $category,
        ]);
    }

    public function actionBrand($id)
    {
        $category = $this->findModel($id, 1);
        $query = Category::find()
            ->with('parent')
            ->where([
                'parent_id' => $category->category_id
            ]);
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => false,
        ]);
        return $this->render('brand', [
            'dataProvider' => $dataProvider,
            'category' => $category,
        ]);
    }

    public function actionCollection($id)
    {
        $category = $this->findModel($id, 2);
        $i = 0;
        foreach ($category->products as $product) {
            $products[$i][] = $product;
            $i++;
            if ($i === 3) $i = 0;
        }
        if (!empty($products)) {
            return $this->render('collection', [
                'products' => $products,
                'category' => $category,
            ]);
        } else {
            throw new NotFoundHttpException("В этой коллекции нет товаров");
        }
    }

    /**
     * Find model by id.
     *
     * @param integer $id
     * @return Category
     * @throws NotFoundHttpException
     */
    private function findModel($id, $depth) {
        $model = Category::find()->where([
            'category_id' => $id,
            'depth' => $depth,
        ])->one();
        if(!empty($model)) {
            return $model;
        } else {
            throw new NotFoundHttpException();
        }
    }
}