Blame view

frontend/controllers/OrderController.php 2.45 KB
cc658b4c   Yarik   Big commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
  <?php
      
      namespace frontend\controllers;
      
      use common\behaviors\AjaxFilter;
      use common\models\Basket;
      use common\models\Orders;
      use common\models\OrdersProducts;
      use common\modules\product\models\ProductVariant;
      use yii\filters\VerbFilter;
      use yii\web\BadRequestHttpException;
  
      class OrderController extends \yii\web\Controller
      {
          
          public $enableCsrfValidation = false;
      
          public function behaviors()
          {
              return [
                  'verbs' => [
                      'class'   => VerbFilter::className(),
                      'actions' => [
                          'make'    => [ 'post' ],
                      ],
                  ],
                  'ajax' => [
                      'class' => AjaxFilter::className(),
                  ],
              ];
          }
          
          public function actionMake()
          {
              $respone = \Yii::$app->response;
              $respone->format = $respone::FORMAT_JSON;
              $post = \Yii::$app->request->post();
              /**
               * @var Basket $basket
               */
              $basket = \Yii::$app->basket;
              $basket_items = array_keys($basket->getData());
              $order = new Orders();
              if($order->load($post) && $order->save()) {
                  if(!empty( $basket_items )) {
                      foreach($basket_items as $basket_item) {
                          $product = ProductVariant::findOne($basket_item);
                          if(!empty( $product )) {
                              $orderProduct = new OrdersProducts([
                                  'order_id'     => $order->id,
                                  'product_name' => $product->product->name,
                                  'mod_id'       => $product->product_variant_id,
                                  'name'         => $product->name,
                                  'sku'          => $product->sku,
                                  'count'        => 1,
                              ]);
                              $orderProduct->save();
                          }
                      }
                      $basket->clear();
                  }
                  return [
                      'message' => $this->renderPartial('success', [
                          'order' => $order,
                      ]),
                  ];
              } else {
                  throw new BadRequestHttpException('Что то пошло не так');
              }
          }
      }