CollectionController.php 2.45 KB
<?php
    
    namespace frontend\controllers;
    
    use common\models\Project;
    use common\modules\product\models\Product;
    use common\modules\product\models\ProductVariant;
    use yii\helpers\ArrayHelper;
    use yii\web\Controller;
    use yii\web\NotFoundHttpException;
    
    /**
     * Article controller
     */
    class CollectionController extends Controller
    {
        
        /**
         * Displays article list.
         * @return string
         */
        public function actionIndex($id)
        {
            /**
             * @var ProductVariant $variant
             */
            $collection = $this->findCollection($id);
            $variant = current($collection->variants);
            return $this->redirect([
                'view',
                'collection_id' => $collection->product_id,
                'variant_id'    => $variant->product_variant_id,
            ]);
        }
        
        public function actionView($collection_id, $variant_id)
        {
            $collection = $this->findCollection($collection_id, $variant_id);
            $variants = $collection->variants;
            $variants = ArrayHelper::index($variants, 'product_variant_id');
            $variant = $variants[ $variant_id ];
            $projects = Project::find()
                               ->joinWith('productToProject')
                               ->with('image')
                               ->where([ 'product_to_project.product_variant_id' => $variant->product_variant_id ])
                               ->all();
            return $this->render('view', [
                'collection' => $collection,
                'variants'   => $variants,
                'variant'    => $variant,
                'projects'   => $projects,
            ]);
        }
        
        /**
         * @param $id
         *
         * @return Product
         * @throws NotFoundHttpException
         */
        private function findCollection($id, $variant_id = NULL)
        {
            $model = Product::find()
                            ->joinWith('variants', true, 'INNER JOIN')
                            ->with('productSpec')
                            ->where([ 'product.product_id' => $id ])
                            ->andFilterWhere([ 'product_variant_id' => $variant_id ])
                            ->one();
            if(empty( $model )) {
                throw new NotFoundHttpException();
            }
            return $model;
        }
    }