Completed
Push — master ( 9844ae...65cb7c )
by Alexey
13:58 queued 04:57
created

CartController::delcartitemAction()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 13
rs 9.2
cc 4
eloc 10
nc 3
nop 1
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
class CartController extends Controller
12
{
13
    public function indexAction()
2 ignored issues
show
Coding Style introduced by
indexAction uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
indexAction uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
14
    {
15
        $cart = '';
16
        $deliverys = \Ecommerce\Delivery::getList();
17
        $payTypes = \Ecommerce\PayType::getList();
18
        if (!empty($_SESSION['cart']['cart_id'])) {
19
            $cart = Ecommerce\Cart::get($_SESSION['cart']['cart_id']);
20
            if (!empty($_POST)) {
21
                $error = false;
22 View Code Duplication
                if (!Users\User::$cur->id) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
23
                    $user_id = $this->Users->registration($_POST, true);
24
                    if (!$user_id) {
25
                        $error = true;
26
                    } else {
27
                        $user = Users\User::get($user_id);
28
                    }
29
                } else {
30
                    $user = Users\User::$cur;
31
                }
32
                $ids = [];
33
                if (!empty($_POST['cartItems'])) {
34
                    foreach ($_POST['cartItems'] as $cartItemId => $cartItemCont) {
35
                        $cartItem = \Ecommerce\Cart\Item::get((int) $cartItemId);
36
                        if (!$cartItem) {
37
                            continue;
38
                        }
39
                        if ($cartItem->cart_id != $cart->id) {
40
                            continue;
41
                        }
42
                        $count = (float) $cartItemCont;
43
                        if ($count < 0.001) {
44
                            $count = 1;
45
                        }
46
                        $cartItem->count = $count;
47
                        $cartItem->save();
48
                        $ids[] = $cartItemId;
49
                    }
50
                    foreach ($cart->cartItems as $cartItem) {
51
                        if (!in_array($cartItem->id, $ids)) {
52
                            $cartItem->delete();
53
                        }
54
                    }
55
                }
56
                $cart = Ecommerce\Cart::get($cart->id);
57
                if (!$cart->cartItems) {
58
                    Tools::redirect('/ecommerce', 'Ваша корзина пуста');
59
                }
60
                if (empty($this->module->config['sell_over_warehouse'])) {
61
                    foreach ($cart->cartItems as $cartitem) {
62
                        $warecount = $cartitem->price->offer->warehouseCount($cart->id);
63
                        if ($cartitem->count > $warecount) {
64
                            $error = true;
65
                            Msg::add('Вы заказали <b>' . $cartitem->item->name . '</b> больше чем есть на складе. на складе: <b>' . $warecount . '</b>', 'danger');
66
                        }
67
                    }
68
                }
69
                if ($deliverys && empty($deliverys[$_POST['delivery']])) {
70
                    $error = 1;
71
                    Msg::add('Ошибка при выборе способа доставки');
72
                } elseif ($deliverys && !empty($deliverys[$_POST['delivery']])) {
73
                    $cart->delivery_id = $_POST['delivery'];
74
                }
75
                if ($payTypes && empty($payTypes[$_POST['payType']])) {
76
                    $error = 1;
77
                    Msg::add('Ошибка при выборе способа оплаты');
78
                } elseif ($payTypes && !empty($payTypes[$_POST['payType']])) {
79
                    $payType = $payTypes[$_POST['payType']];
80
                    $cart->paytype_id = $payType->id;
81
                } else {
82
                    $payType = null;
83
                }
84
                $fields = \Ecommerce\UserAdds\Field::getList();
85 View Code Duplication
                foreach ($fields as $field) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
86
                    if (empty($_POST['userAdds']['fields'][$field->id]) && $field->required) {
87
                        $error = 1;
88
                        Msg::add('Вы не указали: ' . $field->name);
89
                    }
90
                }
91
                if (!empty($_POST['discounts']['card_item_id'])) {
92
                    $userCard = \Ecommerce\Card\Item::get((int) $_POST['discounts']['card_item_id']);
93
                    if (!$userCard) {
94
                        $error = true;
95
                        Msg::add('Такой карты не существует');
96
                    } elseif ($userCard->user_id != $user->id) {
97
                        $error = true;
98
                        Msg::add('Это не ваша карта');
99
                    } else {
100
                        $cart->card_item_id = $userCard->id;
101
                        $cart->save();
102
                    }
103
                }
104
105
                if (!$error && !empty($_POST['action']) && $_POST['action'] = 'order') {
106
                    $cart->user_id = $user->user_id;
107
                    $this->module->parseFields($_POST['userAdds']['fields'], $cart);
108
                    $cart->cart_status_id = 2;
109
                    $cart->comment = htmlspecialchars($_POST['comment']);
110
                    $cart->date_status = date('Y-m-d H:i:s');
111
                    $cart->complete_data = date('Y-m-d H:i:s');
112
                    $cart->warehouse_block = 1;
113
                    $cart->save();
114
115
                    $cart = \Ecommerce\Cart::get($cart->id);
116
                    foreach ($cart->cartItems as $cartItem) {
117
                        $cartItem->discount = $cartItem->discount();
118
                        $cartItem->final_price = $cartItem->price->price - $cartItem->discount;
119
                        $cartItem->save();
120
                    }
121
                    if (!empty(\App::$cur->ecommerce->config['notify_mail'])) {
122
                        $text = 'Перейдите в админ панель чтобы просмотреть новый заказ <a href = "http://' . idn_to_utf8(INJI_DOMAIN_NAME) . '/admin/ecommerce/Cart">Админ панель</a>';
123
                        $title = 'Новый заказ в интернет магазине на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME);
124
                        \Tools::sendMail('noreply@' . INJI_DOMAIN_NAME, \App::$cur->ecommerce->config['notify_mail'], $title, $text);
125
                    }
126
                    if ($this->notifications) {
127
                        $notification = new Notifications\Notification();
128
                        $notification->name = 'Новый заказ в интернет магазине на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME);
129
                        $notification->text = 'Перейдите в админ панель чтобы просмотреть новый заказ';
130
                        $notification->chanel_id = $this->notifications->getChanel('Ecommerce-orders')->id;
131
                        $notification->save();
132
                    }
133
                    $handlers = $this->ecommerce->getSnippets('payTypeHandler');
134
                    $redirect = ['/ecommerce/cart/success'];
135
                    if ($payType && !empty($handlers[$payType->handler]['handler'])) {
136
                        $newRedirect = $handlers[$payType->handler]['handler']($cart);
137
                        if (!empty($newRedirect)) {
138
                            $redirect = $newRedirect;
139
                        }
140
                    }
141
                    unset($_SESSION['cart']['cart_id']);
142
                    call_user_func_array(['Tools', 'redirect'], $redirect);
143
                }
144
            }
145
        }
146
        $this->view->setTitle('Корзина');
147
        $bread = [];
148
        $bread[] = [
149
            'text' => 'Каталог',
150
            'href' => '/ecommerce'
151
        ];
152
        $bread[] = [
153
            'text' => 'Корзина',
154
            'href' => '/ecommerce/cart'
155
        ];
156
        $this->view->page(['data' => compact('cart', 'items', 'deliverys', 'payTypes', 'packItem', 'bread')]);
157
    }
158
159
    public function orderDetailAction($id = 0)
160
    {
161
        $cart = Ecommerce\Cart::get((int) $id);
162
        if ($cart->user_id != Users\User::$cur->id) {
163
            $this->url->redirect('/', 'Это не ваша корзина');
164
        }
165
        $bread[] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$bread was never initialized. Although not strictly required by PHP, it is generally a good practice to add $bread = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
166
            'text' => 'Каталог',
167
            'href' => '/ecommerce'
168
        ];
169
        $bread[] = [
170
            'text' => 'Корзина',
171
            'href' => '/ecommerce/cart'
172
        ];
173
        $bread[] = [
174
            'text' => 'Заказ: №' . $cart->id,
175
            'href' => '/ecommerce/cart/orderDetail/' . $cart->id
176
        ];
177
        $this->view->setTitle('Заказ №' . $cart->id);
178
        $this->view->page(['data' => compact('cart', 'bread')]);
179
    }
180
181
    public function continueAction($id = 0)
1 ignored issue
show
Coding Style introduced by
continueAction uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
182
    {
183
        $cart = \Ecommerce\Cart::get((int) $id);
184
        if ($cart->user_id != Users\User::$cur->id) {
185
            Tools::redirect('/', 'Это не ваша корзина');
186
        }
187
        if ($cart->cart_status_id > 1) {
188
            Tools::redirect('/', 'Корзина уже оформлена');
189
        }
190
        $_SESSION['cart']['cart_id'] = $cart->id;
191
        Tools::redirect('/ecommerce/cart');
192
    }
193
194
    public function deleteAction($id = 0)
1 ignored issue
show
Coding Style introduced by
deleteAction uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
195
    {
196
        $cart = \Ecommerce\Cart::get((int) $id);
197
        if ($cart->user_id != Users\User::$cur->id) {
198
            Tools::redirect('/', 'Это не ваша корзина');
199
        }
200
        if ($cart->cart_status_id > 1) {
201
            Tools::redirect('/', 'Корзина уже оформлена');
202
        }
203
        if (!empty($_SESSION['cart']['cart_id']) && $_SESSION['cart']['cart_id'] == $cart->id) {
204
            unset($_SESSION['cart']['cart_id']);
205
        }
206
        $cart->delete();
207
        Tools::redirect('/users/cabinet/ecommerceOrdersHistory', 'Корзина была удалена', 'success');
208
    }
209
210
    public function refillAction($id = 0)
1 ignored issue
show
Coding Style introduced by
refillAction uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
211
    {
212
        $cart = \Ecommerce\Cart::get((int) $id);
213
        if ($cart->user_id != Users\User::$cur->id) {
214
            Tools::redirect('/', 'Это не ваша корзина');
215
        }
216
        if (!empty($_SESSION['cart']['cart_id'])) {
217
            unset($_SESSION['cart']['cart_id']);
218
        }
219
        $newCart = $this->ecommerce->getCurCart();
220
        foreach ($cart->cartItems as $cartitem) {
221
            $newCart->addItem($cartitem->item_id, $cartitem->item_offer_price_id, $cartitem->count);
222
        }
223
224
        $newCart->save();
225
226
        Tools::redirect('/ecommerce/cart/');
227
    }
228
229
    public function successAction()
230
    {
231
        $bread = [];
232
        $bread[] = [
233
            'text' => 'Каталог',
234
            'href' => '/ecommerce'
235
        ];
236
        $bread[] = [
237
            'text' => 'Корзина',
238
            'href' => '/ecommerce/cart'
239
        ];
240
        $bread[] = [
241
            'text' => 'Заказ принят',
242
            'href' => '/ecommerce/cart/success'
243
        ];
244
        $this->view->setTitle('Заказ принят');
245
        $this->view->page(['data' => compact('bread')]);
246
    }
247
248
    public function addAction()
1 ignored issue
show
Coding Style introduced by
addAction uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
249
    {
250
        $result = new Server\Result();
251
        if (empty($_GET['itemOfferPriceId'])) {
252
            $result->success = false;
253
            $result->content = 'Произошла непредвиденная ошибка при добавлении товара';
254
            $result->send();
255
        }
256
        $price = \Ecommerce\Item\Offer\Price::get((int) $_GET['itemOfferPriceId']);
257
        if (!$price) {
258
            $result->success = false;
259
            $result->content = 'Такой цены не найдено';
260
            $result->send();
261
        }
262
        $item = $price->offer->item;
263
264
        if (!$item) {
265
            $result->success = false;
266
            $result->content = 'Такого товара не существует';
267
            $result->send();
268
        }
269
270
        $item->sales ++;
271
        $item->save();
272
273
        if (empty($_GET['count']))
274
            $count = 1;
275
        else
276
            $count = (float) $_GET['count'];
277
278
        $cart = $this->ecommerce->getCurCart();
279
280
        if (empty($this->module->config['sell_over_warehouse']) && $price->offer->warehouseCount() < $count) {
281
            $result->success = false;
282
            $result->content = 'На складе недостаточно товара! Доступно: ' . $price->offer->warehouseCount();
283
            $result->send();
284
        }
285
286
        $isset = false;
287
        foreach ($cart->cartItems as $cartItem) {
288
            if ($cartItem->item_id == $item->id && $cartItem->item_offer_price_id == $price->id) {
289
                $cartItem->count += $count;
290
                $cartItem->save();
291
                $isset = true;
292
                break;
293
            }
294
        }
295
        if (!$isset) {
296
            $cart->addItem($item->id, $price->id, $count);
297
        }
298
        $cart->calc();
299
        $result->successMsg = '<a href="/ecommerce/view/' . $item->id . '">' . $item->name() . ($price->offer->name() ? ' (' . $price->offer->name() . ')' : '') . '</a> добавлен <a href="/ecommerce/cart">в корзину покупок</a>!';
300
        $result->send();
301
    }
302
303
    public function getcartAction()
304
    {
305
        $result = new Server\Result();
306
        ob_start();
307
        $this->view->widget('Ecommerce\cart');
308
        $result->content = ob_get_contents();
309
        ob_end_clean();
310
        $result->send();
311
    }
312
313
}
314