CartController   F
last analyzed

Complexity

Total Complexity 86

Size/Duplication

Total Lines 363
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 363
rs 1.5789
c 0
b 0
f 0
wmc 86

9 Methods

Rating   Name   Duplication   Size   Complexity  
F indexAction() 0 161 53
B deleteItemAction() 0 24 3
A refillAction() 0 16 4
A getcartAction() 0 7 1
A orderDetailAction() 0 20 2
B deleteAction() 0 13 5
F addAction() 0 78 14
A successAction() 0 16 1
A continueAction() 0 10 3

How to fix   Complexity   

Complex Class

Complex classes like CartController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use CartController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * Ecommerce Cart app controller
5
 *
6
 * @author Alexey Krupskiy <[email protected]>
7
 * @link http://inji.ru/
8
 * @copyright 2015 Alexey Krupskiy
9
 * @license https://github.com/injitools/cms-Inji/blob/master/LICENSE
10
 */
11
12
/**
13
 * Class CartController
14
 * @property Ecommerce $ecommerce
15
 * @property Ecommerce $module
16
 */
17
class CartController extends Controller {
0 ignored issues
show
Bug introduced by
The type Controller was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
19
    public function indexAction() {
20
        $deliverys = \Ecommerce\Delivery::getList(['where' => ['disabled', 0], 'order' => ['weight', 'ASC']]);
21
        $cart = $this->ecommerce->getCurCart(false);
22
        if ($cart && !empty($_POST)) {
23
            $error = false;
24
            $user = Users\User::$cur;
25
            if (!Users\User::$cur->id) {
26
                $user_id = $this->Users->registration($_POST, true);
27
                if (!$user_id) {
28
                    $error = true;
29
                } else {
30
                    $user = Users\User::get($user_id);
31
                }
32
            }
33
            $ids = [];
34
            if (!empty($_POST['cartItems'])) {
35
                foreach ($_POST['cartItems'] as $cartItemId => $cartItemCont) {
36
                    $cartItem = \Ecommerce\Cart\Item::get((int) $cartItemId);
0 ignored issues
show
Bug introduced by
The type Ecommerce\Cart\Item was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
37
                    if (!$cartItem) {
38
                        continue;
39
                    }
40
                    if ($cartItem->cart_id != $cart->id) {
41
                        continue;
42
                    }
43
                    $count = (float) $cartItemCont;
44
                    if ($count < 0.001) {
45
                        $count = 1;
46
                    }
47
                    $cartItem->count = $count;
48
                    $cartItem->save();
49
                    $ids[] = $cartItemId;
50
                }
51
            }
52
            foreach ($cart->cartItems as $cartItem) {
53
                if (!in_array($cartItem->id, $ids)) {
54
                    $cartItem->delete();
55
                }
56
            }
57
            $cart = Ecommerce\Cart::get($cart->id);
58
            if (!$cart->cartItems) {
59
                $error = true;
60
            }
61
            if (empty($this->module->config['sell_over_warehouse'])) {
62
                foreach ($cart->cartItems as $cartitem) {
63
                    $warecount = $cartitem->price->offer->warehouseCount($cart->id);
64
                    if ($cartitem->count > $warecount) {
65
                        $error = true;
66
                        \Inji\Msg::add('Вы заказали <b>' . $cartitem->item->name . '</b> больше чем есть на складе. на складе: <b>' . $warecount . '</b>', 'danger');
67
                    }
68
                }
69
            }
70
            $this->module->parseFields($_POST['userAdds']['fields'], $cart);
71
            if ($deliverys && !$cart->delivery_id && (empty($_POST['delivery']) || empty($deliverys[$_POST['delivery']]))) {
72
                $error = 1;
73
                \Inji\Msg::add('Выберите способ доставки', 'danger');
74
            } elseif ($deliverys && !empty($_POST['delivery']) && !empty($deliverys[$_POST['delivery']])) {
75
                $cart->delivery_id = $_POST['delivery'];
76
            }
77
            if ($cart->delivery) {
78
                foreach ($deliverys[$cart->delivery_id]->fields as $field) {
79
                    if (empty($_POST['deliveryFields'][$field->id]) && $field->required) {
80
                        $error = 1;
81
                        \Inji\Msg::add('Вы не указали: ' . $field->name, 'danger');
82
                    }
83
                }
84
                $this->module->parseDeliveryFields($_POST['deliveryFields'], $cart, $cart->delivery->fields);
85
            }
86
87
            $payTypes = $cart->availablePayTypes();
88
            $payType = false;
89
            if ($payTypes && (empty($_POST['payType']) || empty($payTypes[$_POST['payType']]) || ($cart->paytype_id && !isset($payTypes[$cart->paytype_id])))) {
90
                $error = 1;
91
                \Inji\Msg::add('Выберите способ оплаты', 'danger');
92
            } elseif ($payTypes && !empty($payTypes[$_POST['payType']])) {
93
                $payType = $payTypes[$_POST['payType']];
94
                $cart->paytype_id = $payType->id;
95
            }
96
            foreach (\Ecommerce\UserAdds\Field::getList() as $field) {
0 ignored issues
show
Bug introduced by
The type Ecommerce\UserAdds\Field was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
97
                if (empty($_POST['userAdds']['fields'][$field->id]) && $field->required) {
98
                    $error = 1;
99
                    \Inji\Msg::add('Вы не указали: ' . $field->name, 'danger');
100
                }
101
            }
102
            if (!empty($_POST['discounts']['card_item_id'])) {
103
                $userCard = \Ecommerce\Card\Item::get((int) $_POST['discounts']['card_item_id']);
0 ignored issues
show
Bug introduced by
The type Ecommerce\Card\Item was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
104
                if (!$userCard) {
105
                    $error = true;
106
                    \Inji\Msg::add('Такой карты не существует', 'danger');
107
                } elseif ($userCard->user_id != $user->id) {
108
                    $error = true;
109
                    \Inji\Msg::add('Это не ваша карта', 'danger');
110
                } else {
111
                    $cart->card_item_id = $userCard->id;
112
                }
113
            }
114
115
            $cart->save();
116
            if (!$error && !empty($_POST['action']) && $_POST['action'] = 'order') {
117
                $cart->user_id = $user->user_id;
118
                $cart->cart_status_id = 2;
119
                $cart->comment = !empty($_POST['comment']) ? htmlspecialchars($_POST['comment']) : '';
120
                $cart->date_status = date('Y-m-d H:i:s');
121
                $cart->complete_data = date('Y-m-d H:i:s');
122
                $cart->warehouse_block = 1;
123
                $cart->save();
124
125
                $cart = \Ecommerce\Cart::get($cart->id);
126
                foreach ($cart->cartItems as $cartItem) {
127
                    $cartItem->discount = $cartItem->discount();
128
                    $cartItem->final_price = $cartItem->price->price - $cartItem->discount;
129
                    $cartItem->save();
130
                }
131
                $cart = \Ecommerce\Cart::get($cart->id);
132
133
                $orderInfo = $cart->buildOrderInfo();
134
                $domain = App::$cur->getDomain(true);
135
                $domainRaw = App::$cur->getDomain();
136
                $title = 'Новый заказ в интернет магазине на сайте ' . $domain;
137
138
                if ($user && !empty($user->mail)) {
139
                    $text = '<p><b><a href = "http://' . App::$cur->getDomain() . '/ecommerce/cart/orderDetail/' . ($cart->id) . '">Посмотреть на сайте</a></b></p>' . $orderInfo;
140
                    \Inji\Tools::sendMail('noreply@' . $domainRaw, $cart->user->mail, $title, $text);
141
                }
142
                if (!empty(\App::$cur->ecommerce->config['notify_mail'])) {
143
                    $text = '<p><b><a href = "http://' . App::$cur->getDomain() . '/admin/Ecommerce/view/Cart/' . ($cart->id) . '">Открыть заказ в админ панеле</a></b></p>' . $orderInfo;
144
                    \Inji\Tools::sendMail('noreply@' . $domainRaw, \App::$cur->ecommerce->config['notify_mail'], $title, $text);
145
                }
146
147
                if ($this->notifications) {
148
                    $notification = new Notifications\Notification();
149
                    $notification->name = 'Новый заказ в интернет магазине на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME);
0 ignored issues
show
Bug Best Practice introduced by
The property name does not exist on Notifications\Notification. Since you implemented __set, consider adding a @property annotation.
Loading history...
150
                    $notification->text = 'Перейдите в админ панель чтобы просмотреть новый заказ';
0 ignored issues
show
Bug Best Practice introduced by
The property text does not exist on Notifications\Notification. Since you implemented __set, consider adding a @property annotation.
Loading history...
151
                    $notification->chanel_id = $this->notifications->getChanel('Ecommerce-orders')->id;
0 ignored issues
show
Bug Best Practice introduced by
The property chanel_id does not exist on Notifications\Notification. Since you implemented __set, consider adding a @property annotation.
Loading history...
152
                    $notification->save();
153
                }
154
                $handlers = $this->ecommerce->getSnippets('payTypeHandler');
155
                $redirect = ['/ecommerce/cart/success'];
156
                if ($payType && !empty($handlers[$payType->handler]['handler'])) {
157
                    $newRedirect = $handlers[$payType->handler]['handler']($cart);
158
                    if (!empty($newRedirect)) {
159
                        $redirect = $newRedirect;
160
                    }
161
                }
162
                unset($_SESSION['cart']['cart_id']);
163
                call_user_func_array(['Tools', 'redirect'], $redirect);
164
            }
165
166
        } elseif ($cart) {
167
            $payTypes = $cart->availablePayTypes();
168
        }
169
        $this->view->setTitle('Корзина');
170
        $bread = [];
171
        $bread[] = [
172
            'text' => 'Каталог',
173
            'href' => '/ecommerce'
174
        ];
175
        $bread[] = [
176
            'text' => 'Корзина',
177
            'href' => '/ecommerce/cart'
178
        ];
179
        $this->view->page(['data' => compact('cart', 'items', 'deliverys', 'payTypes', 'packItem', 'bread')]);
180
    }
181
182
    public function orderDetailAction($id = 0) {
183
        $cart = Ecommerce\Cart::get((int) $id);
184
        if ($cart->user_id != Users\User::$cur->id) {
185
            $this->url->redirect('/', 'Это не ваша корзина');
186
        }
187
        $bread = [];
188
        $bread[] = [
189
            'text' => 'Каталог',
190
            'href' => '/ecommerce'
191
        ];
192
        $bread[] = [
193
            'text' => 'Корзина',
194
            'href' => '/ecommerce/cart'
195
        ];
196
        $bread[] = [
197
            'text' => 'Заказ: №' . $cart->id,
198
            'href' => '/ecommerce/cart/orderDetail/' . $cart->id
199
        ];
200
        $this->view->setTitle('Заказ №' . $cart->id);
201
        $this->view->page(['data' => compact('cart', 'bread')]);
202
    }
203
204
    public function continueAction($id = 0) {
205
        $cart = \Ecommerce\Cart::get((int) $id);
206
        if ($cart->user_id != Users\User::$cur->id) {
207
            Tools::redirect('/', 'Это не ваша корзина');
0 ignored issues
show
Bug introduced by
The type Tools was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
208
        }
209
        if ($cart->cart_status_id > 1) {
210
            Tools::redirect('/', 'Корзина уже оформлена');
211
        }
212
        $_SESSION['cart']['cart_id'] = $cart->id;
213
        Tools::redirect('/ecommerce/cart');
214
    }
215
216
    public function deleteAction($id = 0) {
217
        $cart = \Ecommerce\Cart::get((int) $id);
218
        if ($cart->user_id != Users\User::$cur->id) {
219
            Tools::redirect('/', 'Это не ваша корзина');
220
        }
221
        if ($cart->cart_status_id > 1) {
222
            Tools::redirect('/', 'Корзина уже оформлена');
223
        }
224
        if (!empty($_SESSION['cart']['cart_id']) && $_SESSION['cart']['cart_id'] == $cart->id) {
225
            unset($_SESSION['cart']['cart_id']);
226
        }
227
        $cart->delete();
228
        Tools::redirect('/users/cabinet/ecommerceOrdersHistory', 'Корзина была удалена', 'success');
229
    }
230
231
    public function refillAction($id = 0) {
232
        $cart = \Ecommerce\Cart::get((int) $id);
233
        if ($cart->user_id != Users\User::$cur->id) {
234
            Tools::redirect('/', 'Это не ваша корзина');
235
        }
236
        if (!empty($_SESSION['cart']['cart_id'])) {
237
            unset($_SESSION['cart']['cart_id']);
238
        }
239
        $newCart = $this->ecommerce->getCurCart();
240
        foreach ($cart->cartItems as $cartitem) {
241
            $newCart->addItem($cartitem->item_offer_price_id, $cartitem->count);
242
        }
243
244
        $newCart->save();
245
246
        Tools::redirect('/ecommerce/cart/');
247
    }
248
249
    public function successAction() {
250
        $bread = [];
251
        $bread[] = [
252
            'text' => 'Каталог',
253
            'href' => '/ecommerce'
254
        ];
255
        $bread[] = [
256
            'text' => 'Корзина',
257
            'href' => '/ecommerce/cart'
258
        ];
259
        $bread[] = [
260
            'text' => 'Заказ принят',
261
            'href' => '/ecommerce/cart/success'
262
        ];
263
        $this->view->setTitle('Заказ принят');
264
        $this->view->page(['data' => compact('bread')]);
265
    }
266
267
    public function addAction() {
268
        $result = new Server\Result();
0 ignored issues
show
Bug introduced by
The type Server\Result was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
269
        if (empty($_GET['itemOfferPriceId'])) {
270
            $result->success = false;
271
            $result->content = 'Произошла непредвиденная ошибка при добавлении товара';
272
            $result->send();
273
        }
274
275
        $price = \Ecommerce\Item\Offer\Price::get((int) $_GET['itemOfferPriceId']);
0 ignored issues
show
Bug introduced by
The type Ecommerce\Item\Offer\Price was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
276
        if (!$price) {
277
            $result->success = false;
278
            $result->content = 'Такой цены не найдено';
279
            $result->send();
280
        }
281
282
        $offer = $price->offer;
283
        if (!$offer) {
284
            $result->success = false;
285
            $result->content = 'Такого предложения не существует';
286
            $result->send();
287
        }
288
289
        $item = $price->offer->item;
290
291
        if (!$item) {
292
            $result->success = false;
293
            $result->content = 'Такого товара не существует';
294
            $result->send();
295
        }
296
297
        $cart = $this->ecommerce->getCurCart();
298
        /**
299
         * @var \Ecommerce\Cart\Item[] $cartItems
300
         */
301
        $cartItems =[];
302
        foreach ($cart->cartItems as $cartItem){
303
            $cartItems[$cartItem->price->item_offer_id] = $cartItem;
304
        }
305
        if (!empty($this->ecommerce->config['cartAddToggle']) && isset($cartItems[$offer->id])) {
306
            $cartItems[$offer->id]->delete();
307
            $cart = $this->ecommerce->getCurCart();
308
            $cart->date_last_activ = date('Y-m-d H:i:s');
309
            $item->sales--;
310
            $cart->calc(true);
311
            $result->successMsg = '<a href="/ecommerce/view/' . $item->id . '">' . $item->name() . ($price->offer->name() && $price->offer->name() != $item->name() ? ' (' . $price->offer->name() . ')' : '') . '</a> удален <a href="/ecommerce/cart">из корзины покупок</a>!';
312
            $result->content = ['result' => 'toggleDelete'];
313
            return $result->send();
314
        }
315
316
        if (empty($_GET['count'])) {
317
            $count = 1;
318
        } else {
319
            $count = (float) $_GET['count'];
320
        }
321
322
        if (empty($this->module->config['sell_over_warehouse']) && $price->offer->warehouseCount() < $count) {
323
            $result->success = false;
324
            $result->content = 'На складе недостаточно товара! Доступно: ' . $price->offer->warehouseCount();
325
            $result->send();
326
        }
327
        $price = $price->offer->getPrice($cart);
328
        if (!isset($cartItems[$offer->id])) {
329
            $cart->addItem($price->id, $count);
330
            $result->content = ['result' => 'addNew'];
331
        } else {
332
            $cartItems[$offer->id]->count += $count;
333
            $cartItems[$offer->id]->item_offer_price_id = $price->id;
334
            $cartItems[$offer->id]->save();
335
            $result->content = ['result' => 'addCount'];
336
        }
337
        $cart->date_last_activ = date('Y-m-d H:i:s');
338
        $cart->calc(true);
339
340
        $item->sales++;
341
        $item->save();
342
343
        $result->successMsg = '<a href="/ecommerce/view/' . $item->id . '">' . $price->name() . '</a> добавлен <a href="/ecommerce/cart">в корзину покупок</a>!';
344
        $result->send();
345
    }
346
347
    public function deleteItemAction() {
348
        $result = new Server\Result();
349
        if (empty($_GET['cartItemId'])) {
350
            $result->success = false;
351
            $result->content = 'Произошла непредвиденная ошибка при добавлении товара';
352
            $result->send();
353
        }
354
355
        $cart = $this->ecommerce->getCurCart();
356
        if (!isset($cart->cartItems[$_GET['cartItemId']])) {
357
            $result->success = false;
358
            $result->content = 'Такого товара нет в вашей корзине';
359
            $result->send();
360
        }
361
        $cart->cartItems[$_GET['cartItemId']]->delete();
362
        $cart = $this->ecommerce->getCurCart();
363
        $cart->date_last_activ = date('Y-m-d H:i:s');
364
        $cart->calc();
365
        ob_start();
366
        $this->view->widget('Ecommerce\cart');
367
        $result->content = ob_get_contents();
368
        ob_end_clean();
369
        $result->successMsg = 'Товар был удален';
370
        $result->send();
371
    }
372
373
    public function getcartAction() {
374
        $result = new Server\Result();
375
        ob_start();
376
        $this->view->widget('Ecommerce\cart');
377
        $result->content = ob_get_contents();
378
        ob_end_clean();
379
        $result->send();
380
    }
381
382
}
383