Completed
Push — master ( b39695...9f262c )
by Andrey
07:41
created

OrderAjaxController::behaviors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
1
<?php
2
3
namespace app\controllers\ajax;
4
5
use Yii;
6
use yii\filters\{ContentNegotiator, VerbFilter};
7
use yii\web\{Controller, Response, BadRequestHttpException};
8
use app\traits\ResponseTrait;
9
use app\components\BasketComponent;
10
use app\models\Order;
11
12
/**
13
 * Class OrderAjaxController
14
 *
15
 * @package app\controllers
16
 */
17
class OrderAjaxController extends Controller
18
{
19
    use ResponseTrait;
20
21
    /**
22
     * @var string|array the configuration for creating the serializer that formats the response data.
23
     */
24
    public $serializer = 'yii\rest\Serializer';
25
26
    /**
27
     * @var BasketComponent
28
     */
29
    protected $basketManager;
30
31
    /**
32
     * Initialize.
33
     */
34
    public function init()
35
    {
36
        parent::init();
37
38
        $this->basketManager = Yii::$app->get('basket');
39
    }
40
41
    /**
42
     * @return array
43
     */
44
    public function behaviors()
45
    {
46
        return [
47
            'contentNegotiator' => [
48
                'class' => ContentNegotiator::class,
49
                'formats' => [
50
                    'application/json' => Response::FORMAT_JSON,
51
                ],
52
            ],
53
            'verbFilter' => [
54
                'class' => VerbFilter::class,
55
                'actions' => $this->verbs(),
56
            ],
57
        ];
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function afterAction($action, $result)
64
    {
65
        $result = parent::afterAction($action, $result);
66
        return $this->serializeData($result);
67
    }
68
69
    /**
70
     * @return array
71
     */
72
    public function verbs()
73
    {
74
        return [
75
            'put-to-basket' => ['POST'],
76
            'set-count-in-basket' => ['POST'],
77
            'remove-from-basket' => ['POST'],
78
            'send-order' => ['POST'],
79
        ];
80
    }
81
82
    /**
83
     * @return array
84
     * @throws BadRequestHttpException
85
     */
86
    public function actionPutToBasket()
87
    {
88
        try {
89
            $id = Yii::$app->request->post('id');
90
            $count = Yii::$app->request->post('count');
91
92
            if ($this->basketManager->putToBasket($id, empty($count) ? 1 : $count)) {
93
                return $this->getSuccessResponse('', [
94
                    'total_amount' => $this->basketManager->getTotalAmount(),
95
                    'total_count' => $this->basketManager->getTotalCount(),
96
                ]);
97
            }
98
99
            return $this->getFailResponse('Failed put to basket');
100
101
        } catch (\Exception $e) {
102
            throw new BadRequestHttpException($e->getMessage(), $e->getCode());
103
        }
104
    }
105
106
    /**
107
     * @return array
108
     * @throws BadRequestHttpException
109
     */
110
    public function actionSetCountInBasket()
111
    {
112
        try {
113
            $id = Yii::$app->request->post('id');
114
            $count = Yii::$app->request->post('count');
115
116
            if ($this->basketManager->setCountInBasket($id, $count)) {
117
                $modelItems = $this->basketManager->getModelItems();
118
119
                return $this->getSuccessResponse('', [
120
                    'total_amount' => $this->basketManager->calculateTotalAmount($modelItems),
121
                    'total_count' => $this->basketManager->getTotalCount(),
122
                    'item_price' => $modelItems[$id]->price
123
                ]);
124
            }
125
126
            return $this->getFailResponse('Failed set count in a basket');
127
128
        } catch (\Exception $e) {
129
            throw new BadRequestHttpException($e->getMessage(), $e->getCode());
130
        }
131
    }
132
133
    /**
134
     * @return array
135
     * @throws BadRequestHttpException
136
     */
137
    public function actionRemoveFromBasket()
138
    {
139
        try {
140
            $id = Yii::$app->request->post('id');
141
142
            if ($this->basketManager->removeFromBasket($id)) {
143
                return $this->getSuccessResponse('', [
144
                    'total_amount' => $this->basketManager->getTotalAmount(),
145
                    'total_count' => $this->basketManager->getTotalCount(),
146
                ]);
147
            }
148
149
            return $this->getFailResponse('Failed remove from basket');
150
151
        } catch (\Exception $e) {
152
            throw new BadRequestHttpException($e->getMessage(), $e->getCode());
153
        }
154
    }
155
156
    /**
157
     * @return array
158
     * @throws BadRequestHttpException
159
     */
160
    public function actionSendOrder()
161
    {
162
        try {
163
            $order = new Order();
164
            $order->setAttributes(Yii::$app->request->post(), false);
165
166
            if ($order->handle(Yii::$app->params['adminEmail'])) {
167
                $this->basketManager->clearBasket();
168
                return $this->getSuccessResponse(Yii::t('order', 'You have successfully sent your order message.').' '.Yii::t('order', 'The manager will contact you.'));
169
170
            } else {
171
                return $this->getFailResponse(Yii::t('feedback', 'Error send data.'), [
172
                    'errors' => $order->getErrors()
173
                ]);
174
            }
175
176
        } catch (\Exception $e) {
177
            throw new BadRequestHttpException($e->getMessage(), $e->getCode());
178
        }
179
    }
180
181
    /**
182
     * Serializes the specified data.
183
     * The default implementation will create a serializer based on the configuration given by [[serializer]].
184
     * It then uses the serializer to serialize the given data.
185
     * @param mixed $data the data to be serialized
186
     * @return mixed the serialized data.
187
     */
188
    private function serializeData($data)
189
    {
190
        return Yii::createObject($this->serializer)->serialize($data);
191
    }
192
}
193