Completed
Push — master ( 97b00d...004fa5 )
by Alexey
07:14
created

Ecommerce::parseOptions()   F

Complexity

Conditions 39
Paths 6912

Size

Total Lines 138
Code Lines 96

Duplication

Lines 15
Ratio 10.87 %
Metric Value
dl 15
loc 138
rs 2
cc 39
eloc 96
nc 6912
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Ecommerce module
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 Ecommerce extends Module
12
{
13
    public function init()
14
    {
15
        App::$primary->view->customAsset('js', '/moduleAsset/Ecommerce/js/cart.js');
16
    }
17
18
    public function getPayTypeHandlers($forSelect = false)
19
    {
20
        if (!$forSelect) {
21
            return $this->getSnippets('payTypeHandler');
22
        }
23
        $handlers = [];
24
        foreach ($this->getSnippets('payTypeHandler') as $key => $handler) {
25
            if (empty($handler)) {
26
                continue;
27
            }
28
            $handlers[$key] = $handler['name'];
29
        }
30
        return $handlers;
31
    }
32
33
    public function cartPayRecive($data)
34
    {
35
        $cart = Ecommerce\Cart::get($data['pay']->data);
36
        if ($cart) {
37
            $payed = true;
38
            foreach ($cart->pays as $pay) {
39
                if ($pay->pay_status_id != 2) {
40
                    $payed = false;
41
                    break;
42
                }
43
            }
44
            $cart->payed = $payed;
45
            $cart->save();
46
        }
47
    }
48
49
    public function parseFields($data, $cart)
50
    {
51
        $fields = \Ecommerce\UserAdds\Field::getList();
52
        $name = '';
53
        foreach ($fields as $field) {
54
            if ($field->save && !empty($data[$field->id])) {
55
                $name .= htmlspecialchars($data[$field->id]) . ' ';
56
            }
57
        }
58
        $name = trim($name);
59
60
        $userAdds = Ecommerce\UserAdds::get([['user_id', $cart->user->id], ['name', $name]]);
61
        if (!$userAdds) {
62
            $userAdds = new Ecommerce\UserAdds();
63
            $userAdds->user_id = $cart->user->id;
64
            $userAdds->name = $name;
65
            $userAdds->save();
66
            foreach ($fields as $field) {
67
                if (!$field->save) {
68
                    continue;
69
                }
70
                $userAddsValue = new Ecommerce\UserAdds\Value();
71
                $userAddsValue->value = htmlspecialchars($data[$field->id]);
72
                $userAddsValue->useradds_field_id = $field->id;
73
                $userAddsValue->useradds_id = $userAdds->id;
74
                $userAddsValue->save();
75
            }
76
        }
77
        $user = \Users\User::get($cart->user_id);
78
        foreach ($fields as $field) {
79
            $info = new \Ecommerce\Cart\Info();
80
            $info->name = $field->name;
81
            $info->value = htmlspecialchars($data[$field->id]);
82
            $info->useradds_field_id = $field->id;
83
            $info->cart_id = $cart->id;
84
            $info->save();
85
            $relations = [];
86
            if ($field->userfield) {
87
                if (strpos($field->userfield, ':')) {
88
                    $path = explode(':', $field->userfield);
89
                    if (!$user->{$path[0]}->{$path[1]}) {
90
                        $user->{$path[0]}->{$path[1]} = $info->value;
91
                        $relations[$path[0]] = $path[0];
92
                    }
93
                } else {
94
                    if (!$user->{$field->userfield}) {
95
                        $user->{$field->userfield} = $info->value;
96
                    }
97
                }
98
            }
99
            foreach ($relations as $rel) {
100
                $user->$rel->save();
101
            }
102
            $user->save();
103
        }
104
        return $userAdds;
105
    }
106
107
    public function getCurCart($create = true)
1 ignored issue
show
Coding Style introduced by
getCurCart 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...
108
    {
109
        $cart = false;
110
        if (!empty($_SESSION['cart']['cart_id'])) {
111
            $cart = Ecommerce\Cart::get((int) $_SESSION['cart']['cart_id']);
112
        }
113
        if (!$cart && $create) {
114
            $cart = new Ecommerce\Cart();
115
            $cart->cart_status_id = 1;
116
            $cart->user_id = Users\User::$cur->id;
117
            $userCard = \Ecommerce\Card\Item::get(\Users\User::$cur->id, 'user_id');
118
            if ($userCard) {
119
                $cart->card_item_id = $userCard->id;
120
            }
121
            $cart->save();
122
            $_SESSION['cart']['cart_id'] = $cart->id;
123
        }
124
        return $cart;
125
    }
126
127
    public function parseOptions($options = [])
128
    {
129
        $selectOptions = [
130
            'where' => !empty($options['where']) ? $options['where'] : [],
131
            'distinct' => false,
132
            'join' => [],
133
            'order' => [],
134
            'start' => isset($options['start']) ? (int) $options['start'] : 0,
135
            'key' => isset($options['key']) ? $options['key'] : null,
136
            'limit' => !empty($options['count']) ? (int) $options['count'] : 0,
137
        ];
138
        if (!empty($options['sort']) && is_array($options['sort'])) {
139
            foreach ($options['sort'] as $col => $direction) {
140
                switch ($col) {
141
                    case 'price':
142
                        $selectOptions['order'][] = [Ecommerce\Item\Offer\Price::colPrefix() . 'price', strtolower($direction) == 'desc' ? 'desc' : 'asc'];
143
                        break;
144 View Code Duplication
                    case 'name':
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...
145
                        $selectOptions['order'][] = ['name', strtolower($direction) == 'desc' ? 'desc' : 'asc'];
146
                        break;
147 View Code Duplication
                    case 'sales':
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...
148
                        $selectOptions['order'][] = ['sales', strtolower($direction) == 'desc' ? 'desc' : 'asc'];
149
                        break;
150 View Code Duplication
                    case 'weight':
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...
151
                        $selectOptions['order'][] = ['weight', strtolower($direction) == 'desc' ? 'desc' : 'asc'];
152
                        break;
153
                }
154
            }
155
        }
156
157
        if (empty($this->config['view_empty_image'])) {
158
            $selectOptions['where'][] = ['image_file_id', 0, '!='];
159
        }
160
        if (!empty($this->config['view_filter'])) {
161
            if (!empty($this->config['view_filter']['options'])) {
162
                foreach ($this->config['view_filter']['options'] as $optionId => $optionValue) {
163
                    $selectOptions['join'][] = [Ecommerce\Item\Param::table(), Ecommerce\Item::index() . ' = ' . 'option' . $optionId . '.' . Ecommerce\Item\Param::colPrefix() . Ecommerce\Item::index() . ' AND ' .
164
                        'option' . $optionId . '.' . Ecommerce\Item\Param::colPrefix() . Ecommerce\Item\Option::index() . ' = "' . (int) $optionId . '" AND ' .
165
                        'option' . $optionId . '.' . Ecommerce\Item\Param::colPrefix() . 'value = "' . (int) $optionValue . '"',
166
                        'inner', 'option' . $optionId];
167
                }
168
            }
169
        }
170
        //filters
171
        if (!empty($options['filters'])) {
172
            foreach ($options['filters'] as $col => $filter) {
173
                switch ($col) {
174
                    case 'price':
175 View Code Duplication
                        if (!empty($filter['min'])) {
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...
176
                            $selectOptions['where'][] = [Ecommerce\Item\Offer\Price::colPrefix() . 'price', (float) $filter['min'], '>='];
177
                        }
178 View Code Duplication
                        if (!empty($filter['max'])) {
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...
179
                            $selectOptions['where'][] = [Ecommerce\Item\Offer\Price::colPrefix() . 'price', (float) $filter['max'], '<='];
180
                        }
181
                        break;
182
                    case 'options':
183
                        foreach ($filter as $optionId => $optionValue) {
184
                            $selectOptions['join'][] = [Ecommerce\Item\Param::table(), Ecommerce\Item::index() . ' = ' . 'option' . $optionId . '.' . Ecommerce\Item\Param::colPrefix() . Ecommerce\Item::index() . ' AND ' .
185
                                'option' . $optionId . '.' . Ecommerce\Item\Param::colPrefix() . Ecommerce\Item\Option::index() . ' = "' . (int) $optionId . '" AND ' .
186
                                'option' . $optionId . '.' . Ecommerce\Item\Param::colPrefix() . 'value = "' . (int) $optionValue . '"',
187
                                'inner', 'option' . $optionId];
188
                        }
189
                        break;
190
                }
191
            }
192
        }
193
        //parents
194
        if (!empty($options['parent']) && strpos($options['parent'], ',') !== false) {
195
            $first = true;
196
            $where = [];
197
            foreach (explode(',', $options['parent']) as $categoryId) {
198
                if (!$categoryId) {
199
                    continue;
200
                }
201
                $category = \Ecommerce\Category::get($categoryId);
202
                $where[] = ['tree_path', $category->tree_path . (int) $categoryId . '/%', 'LIKE', $first ? 'AND' : 'OR'];
203
                $first = false;
204
            }
205
            $selectOptions['where'][] = $where;
206
        } elseif (!empty($options['parent'])) {
207
            $category = \Ecommerce\Category::get($options['parent']);
208
            $selectOptions['where'][] = ['tree_path', $category->tree_path . (int) $options['parent'] . '/%', 'LIKE'];
209
        }
210
211
        //search
212
        if (!empty($options['search'])) {
213
            $searchStr = preg_replace('![^A-zА-я0-9 ]!iSu', ' ', $options['search']);
214
            $searchArr = [];
215
            foreach (explode(' ', $searchStr) as $part) {
216
                $part = trim($part);
217
                if ($part && strlen($part) > 2) {
218
                    $searchArr[] = ['search_index', '%' . $part . '%', 'LIKE'];
219
                }
220
            }
221
            if (!empty($searchArr)) {
222
                $selectOptions['where'][] = $searchArr;
223
            }
224
        }
225
        if (empty($this->config['view_empty_warehouse'])) {
226
            $selectOptions['where'][] = [
227
                '(
228
          (SELECT COALESCE(sum(`' . \Ecommerce\Item\Offer\Warehouse::colPrefix() . 'count`),0) 
229
            FROM ' . \App::$cur->db->table_prefix . \Ecommerce\Item\Offer\Warehouse::table() . ' iciw 
230
            WHERE iciw.' . \Ecommerce\Item\Offer\Warehouse::colPrefix() . \Ecommerce\Item\Offer::index() . ' = ' . \Ecommerce\Item\Offer::index() . '
231
            )
232
          -
233
          (SELECT COALESCE(sum(' . \Ecommerce\Warehouse\Block::colPrefix() . 'count) ,0)
234
            FROM ' . \App::$cur->db->table_prefix . \Ecommerce\Warehouse\Block::table() . ' iewb
235
            inner JOIN ' . \App::$cur->db->table_prefix . \Ecommerce\Cart::table() . ' icc ON icc.' . \Ecommerce\Cart::index() . ' = iewb.' . \Ecommerce\Warehouse\Block::colPrefix() . \Ecommerce\Cart::index() . ' AND (
236
                (`' . \Ecommerce\Cart::colPrefix() . 'warehouse_block` = 1 and `' . \Ecommerce\Cart::colPrefix() . 'cart_status_id` in(2,3,6)) ||
237
                (`' . \Ecommerce\Cart::colPrefix() . \Ecommerce\Cart\Status::index() . '` in(0,1) and `' . \Ecommerce\Cart::colPrefix() . 'date_last_activ` >=subdate(now(),INTERVAL 30 MINUTE))
238
            )
239
            WHERE iewb.' . \Ecommerce\Warehouse\Block::colPrefix() . \Ecommerce\Item\Offer::index() . ' = ' . \Ecommerce\Item\Offer::index() . ')
240
          )',
241
                0,
242
                '>'
243
            ];
244
        }
245
246
247
        $selectOptions['join'][] = [Ecommerce\Item\Offer::table(), Ecommerce\Item::index() . ' = ' . Ecommerce\Item\Offer::colPrefix() . Ecommerce\Item::index(), 'inner'];
248
        $selectOptions['join'][] = [Ecommerce\Item\Offer\Price::table(),
249
            Ecommerce\Item\Offer::index() . ' = ' . Ecommerce\Item\Offer\Price::colPrefix() . Ecommerce\Item\Offer::index() . ' and ' . Ecommerce\Item\Offer\Price::colPrefix() . 'price>0', 'inner'];
250
        $selectOptions['join'][] = [
251
            Ecommerce\Item\Offer\Price\Type::table(), Ecommerce\Item\Offer\Price::colPrefix() . Ecommerce\Item\Offer\Price\Type::index() . ' = ' . Ecommerce\Item\Offer\Price\Type::index() .
252
            ' and (' . Ecommerce\Item\Offer\Price\Type::colPrefix() . 'roles="" || ' . Ecommerce\Item\Offer\Price\Type::colPrefix() . 'roles LIKE "%|' . \Users\User::$cur->role_id . '|%")'
253
        ];
254
        $selectOptions['where'][] = [
255
            [Ecommerce\Item\Offer\Price::colPrefix() . Ecommerce\Item\Offer\Price\Type::index(), 0],
256
            [Ecommerce\Item\Offer\Price\Type::index(), 0, '>', 'OR']
257
        ];
258
259
260
261
        $selectOptions['group'] = Ecommerce\Item::index();
262
263
        return $selectOptions;
264
    }
265
266
    /**
267
     * Getting items with params
268
     * 
269
     * @param array $params
270
     * @return array
271
     */
272
    public function getItems($params = [])
273
    {
274
        $selectOptions = $this->parseOptions($params);
275
        $items = Ecommerce\Item::getList($selectOptions);
276
        return $items;
277
    }
278
279
    /**
280
     * Return count of items with params
281
     * 
282
     * @param array $params
283
     * @return int
284
     */
285
    public function getItemsCount($params = [])
286
    {
287
        $selectOptions = $this->parseOptions($params);
288
        $selectOptions['distinct'] = \Ecommerce\Item::index();
289
        $counts = Ecommerce\Item::getCount($selectOptions);
290
        if (is_array($counts)) {
291
            $sum = 0;
292
            foreach ($counts as $count) {
293
                $sum +=$count['count'];
294
            }
295
            return $sum;
296
        }
297
        return $counts;
298
    }
299
300 View Code Duplication
    public function viewsCategoryList($inherit = true)
301
    {
302
        $return = [];
303
        if ($inherit) {
304
            $return['inherit'] = 'Как у родителя';
305
        }
306
        $return['itemList'] = 'Список товаров';
307
        $conf = App::$primary->view->template->config;
308
        if (!empty($conf['files']['modules']['Ecommerce'])) {
309
            foreach ($conf['files']['modules']['Ecommerce'] as $file) {
310
                if ($file['type'] == 'Category') {
311
                    $return[$file['file']] = $file['name'];
312
                }
313
            }
314
        }
315
        return $return;
316
    }
317
318 View Code Duplication
    public function templatesCategoryList()
319
    {
320
        $return = [
321
            'inherit' => 'Как у родителя',
322
            'current' => 'Текущая тема'
323
        ];
324
325
        $conf = App::$primary->view->template->config;
326
327
        if (!empty($conf['files']['aditionTemplateFiels'])) {
328
            foreach ($conf['files']['aditionTemplateFiels'] as $file) {
329
                $return[$file['file']] = '- ' . $file['name'];
330
            }
331
        }
332
        return $return;
333
    }
334
335
    public function cartStatusDetector($event)
336
    {
337
        $item = $event['eventObject'];
338
        if (!empty($item->_changedParams['cart_cart_status_id'])) {
339
            $item->date_status = date('Y-m-d H:i:s');
340
            $event = new Ecommerce\Cart\Event(['cart_id' => $item->id, 'user_id' => \Users\User::$cur->id, 'cart_event_type_id' => 5, 'info' => $item->cart_status_id]);
341
            $event->save();
342
343
            if ($item->cart_status_id == 5) {
344
                Inji::$inst->event('ecommerceCartClosed', $item);
345
            }
346
        }
347
    }
348
349
    public function cardTrigger($event)
350
    {
351
        $cart = $event['eventObject'];
352
        if ($cart->card) {
353
            $sum = 0;
354
            foreach ($cart->cartItems as $cartItem) {
355
                $sum += $cartItem->final_price * $cartItem->count;
356
            }
357
            $cardItemHistory = new Ecommerce\Card\Item\History();
358
            $cardItemHistory->amount = $sum;
359
            $cardItemHistory->card_item_id = $cart->card_item_id;
360
            $cardItemHistory->save();
361
            $cart->card->sum += $sum;
362
            $cart->card->save();
363
        }
364
    }
365
366
    public function bonusTrigger($event)
367
    {
368
        $cart = $event['eventObject'];
369
        foreach ($cart->cartItems as $cartItem) {
370
            foreach ($cartItem->price->offer->bonuses as $bonus) {
371
                if ($bonus->limited && $bonus->left <= 0) {
372
                    continue;
373
                } elseif ($bonus->limited && $bonus->left > 0) {
374
                    $bonus->left -= 1;
375
                    $bonus->save();
376
                }
377
                switch ($bonus->type) {
378
                    case'currency':
0 ignored issues
show
Coding Style introduced by
As per coding-style, case should be followed by a single space.

As per the PSR-2 coding standard, there must be a space after the case keyword, instead of the test immediately following it.

switch (true) {
    case!isset($a):  //wrong
        doSomething();
        break;
    case !isset($b):  //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
379
                        $currency = \Money\Currency::get($bonus->value);
380
                        $wallets = App::$cur->money->getUserWallets($cart->user->id);
381
                        $wallets[$currency->id]->diff($bonus->count, 'Бонус за покупку');
382
                        break;
383
                }
384
            }
385
        }
386
    }
387
388
}
389