Completed
Push — master ( ebb499...f17270 )
by Alexey
03:58
created

Ecommerce::getItemsParams()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 1
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
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
        App::$primary->view->customAsset('js', '/moduleAsset/Ecommerce/js/cart.js');
15
    }
16
17
    public function getPayTypeHandlers($forSelect = false) {
18
        if (!$forSelect) {
19
            return $this->getSnippets('payTypeHandler');
20
        }
21
        $handlers = ['' => 'Не выбрано'];
22
        foreach ($this->getSnippets('payTypeHandler') as $key => $handler) {
23
            if (empty($handler)) {
24
                continue;
25
            }
26
            $handlers[$key] = $handler['name'];
27
        }
28
        return $handlers;
29
    }
30
31
    public function cartPayRecive($data) {
32
        $cart = Ecommerce\Cart::get($data['pay']->data);
33
        if ($cart) {
34
            $payed = true;
35
            foreach ($cart->pays as $pay) {
36
                if ($pay->pay_status_id != 2) {
37
                    $payed = false;
38
                    break;
39
                }
40
            }
41
            $cart->payed = $payed;
42
            $cart->save();
43
        }
44
    }
45
46 View Code Duplication
    public function parseFields($data, $cart) {
47
        $fields = \Ecommerce\UserAdds\Field::getList();
48
        $name = '';
49
        foreach ($fields as $field) {
50
            if ($field->save && !empty($data[$field->id])) {
51
                $name .= htmlspecialchars($data[$field->id]) . ' ';
52
            }
53
        }
54
        $name = trim($name);
55
56
        $userAdds = Ecommerce\UserAdds::get([['user_id', $cart->user->id], ['name', $name]]);
57
        if (!$userAdds) {
58
            $userAdds = new Ecommerce\UserAdds();
59
            $userAdds->user_id = $cart->user->id;
60
            $userAdds->name = $name;
61
            $userAdds->save();
62
            foreach ($fields as $field) {
63
                if (!$field->save) {
64
                    continue;
65
                }
66
                $userAddsValue = new Ecommerce\UserAdds\Value();
67
                $userAddsValue->value = htmlspecialchars($data[$field->id]);
68
                $userAddsValue->useradds_field_id = $field->id;
69
                $userAddsValue->useradds_id = $userAdds->id;
70
                $userAddsValue->save();
71
            }
72
        }
73
        $user = \Users\User::get($cart->user_id);
74
        foreach ($fields as $field) {
75
            $info = new \Ecommerce\Cart\Info();
76
            $info->name = $field->name;
77
            $info->value = htmlspecialchars($data[$field->id]);
78
            $info->useradds_field_id = $field->id;
79
            $info->cart_id = $cart->id;
80
            $info->save();
81
            $relations = [];
82
            if ($field->userfield) {
83
                if (strpos($field->userfield, ':')) {
84
                    $path = explode(':', $field->userfield);
85
                    if (!$user->{$path[0]}->{$path[1]}) {
86
                        $user->{$path[0]}->{$path[1]} = $info->value;
87
                        $relations[$path[0]] = $path[0];
88
                    }
89
                } else {
90
                    if (!$user->{$field->userfield}) {
91
                        $user->{$field->userfield} = $info->value;
92
                    }
93
                }
94
            }
95
            foreach ($relations as $rel) {
96
                $user->$rel->save();
97
            }
98
            $user->save();
99
        }
100
        return $userAdds;
101
    }
102
103 View Code Duplication
    public function parseDeliveryFields($data, $cart, $fields) {
104
        $name = '';
105
        foreach ($fields as $field) {
106
            if ($field->save && !empty($data[$field->id])) {
107
                $name .= htmlspecialchars($data[$field->id]) . ' ';
108
            }
109
        }
110
        $name = trim($name);
111
112
        $save = Ecommerce\Delivery\Save::get([['user_id', $cart->user->id], ['name', $name]]);
113
        if (!$save) {
114
            $save = new Ecommerce\Delivery\Save();
115
            $save->user_id = $cart->user->id;
116
            $save->name = $name;
117
            $save->save();
118
            foreach ($fields as $field) {
119
                if (!$field->save) {
120
                    continue;
121
                }
122
                $saveValue = new Ecommerce\Delivery\Value();
123
                $saveValue->value = htmlspecialchars($data[$field->id]);
124
                $saveValue->delivery_field_id = $field->id;
125
                $saveValue->delivery_save_id = $save->id;
126
                $saveValue->save();
127
            }
128
        }
129
        $user = \Users\User::get($cart->user_id);
130
        foreach ($fields as $field) {
131
            $info = new \Ecommerce\Cart\DeliveryInfo();
132
            $info->name = $field->name;
133
            $info->value = htmlspecialchars($data[$field->id]);
134
            $info->delivery_field_id = $field->id;
135
            $info->cart_id = $cart->id;
136
            $info->save();
137
            $relations = [];
138
            if ($field->userfield) {
139
                if (strpos($field->userfield, ':')) {
140
                    $path = explode(':', $field->userfield);
141
                    if (!$user->{$path[0]}->{$path[1]}) {
142
                        $user->{$path[0]}->{$path[1]} = $info->value;
143
                        $relations[$path[0]] = $path[0];
144
                    }
145
                } else {
146
                    if (!$user->{$field->userfield}) {
147
                        $user->{$field->userfield} = $info->value;
148
                    }
149
                }
150
            }
151
            foreach ($relations as $rel) {
152
                $user->$rel->save();
153
            }
154
            $user->save();
155
        }
156
        return $save;
157
    }
158
159
    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...
160
        $cart = false;
161
        if (!empty($_SESSION['cart']['cart_id'])) {
162
            $cart = Ecommerce\Cart::get((int) $_SESSION['cart']['cart_id']);
163
        }
164
        if (!$cart && $create) {
165
            $cart = new Ecommerce\Cart();
166
            $cart->cart_status_id = 1;
167
            $cart->user_id = Users\User::$cur->id;
168
            $userCard = \Ecommerce\Card\Item::get(\Users\User::$cur->id, 'user_id');
169
            if ($userCard) {
170
                $cart->card_item_id = $userCard->id;
171
            }
172
            $cart->save();
173
            $_SESSION['cart']['cart_id'] = $cart->id;
174
        }
175
        return $cart;
176
    }
177
178
    /**
179
     * Getting items params with params
180
     * 
181
     * @param array $params
182
     * @return array
183
     */
184
    public function getItemsParams($params = []) {
185
        $params['filters'] = [];
186
        $selectOptions = Ecommerce\OptionsParser::parse($params);
187
        $items = Ecommerce\Item::getList($selectOptions);
188
        if (!$items) {
189
            return [];
190
        }
191
        $items = Ecommerce\Item\Param::getList([
192
                    'where' => ['item_id', array_keys($items), 'IN'],
193
                    'join' => [[Ecommerce\Item\Option::table(), Ecommerce\Item\Option::index() . ' = ' . \Ecommerce\Item\Param::colPrefix() . Ecommerce\Item\Option::index() . ' and ' . \Ecommerce\Item\Option::colPrefix() . 'searchable = 1', 'inner']],
194
                    'distinct' => \Ecommerce\Item\Option::index()
195
        ]);
196
        return $items;
197
    }
198
199
    /**
200
     * Getting items with params
201
     * 
202
     * @param array $params
203
     * @return array
204
     */
205
    public function getItems($params = []) {
206
        $selectOptions = Ecommerce\OptionsParser::parse($params);
207
        $items = Ecommerce\Item::getList($selectOptions);
208
        return $items;
209
    }
210
211
    /**
212
     * Return count of items with params
213
     * 
214
     * @param array $params
215
     * @return int
216
     */
217
    public function getItemsCount($params = []) {
218
        $selectOptions = Ecommerce\OptionsParser::parse($params);
219
        $selectOptions['distinct'] = \Ecommerce\Item::index();
220
        $counts = Ecommerce\Item::getCount($selectOptions);
221
        if (is_array($counts)) {
222
            $sum = 0;
223
            foreach ($counts as $count) {
224
                $sum +=$count['count'];
225
            }
226
            return $sum;
227
        }
228
        return $counts;
229
    }
230
231 View Code Duplication
    public function viewsCategoryList($inherit = true) {
232
        $return = [];
233
        if ($inherit) {
234
            $return['inherit'] = 'Как у родителя';
235
        }
236
        $return['itemList'] = 'Список товаров';
237
        $conf = App::$primary->view->template->config;
238
        if (!empty($conf['files']['modules']['Ecommerce'])) {
239
            foreach ($conf['files']['modules']['Ecommerce'] as $file) {
240
                if ($file['type'] == 'Category') {
241
                    $return[$file['file']] = $file['name'];
242
                }
243
            }
244
        }
245
        return $return;
246
    }
247
248 View Code Duplication
    public function templatesCategoryList() {
249
        $return = [
250
            'inherit' => 'Как у родителя',
251
            'current' => 'Текущая тема'
252
        ];
253
254
        $conf = App::$primary->view->template->config;
255
256
        if (!empty($conf['files']['aditionTemplateFiels'])) {
257
            foreach ($conf['files']['aditionTemplateFiels'] as $file) {
258
                $return[$file['file']] = '- ' . $file['name'];
259
            }
260
        }
261
        return $return;
262
    }
263
264
    public function cartStatusDetector($event) {
265
        $cart = $event['eventObject'];
266
        if (!empty($cart->_changedParams['cart_cart_status_id'])) {
267
            $cart->date_status = date('Y-m-d H:i:s');
268
            $event = new Ecommerce\Cart\Event(['cart_id' => $cart->id, 'user_id' => \Users\User::$cur->id, 'cart_event_type_id' => 5, 'info' => $cart->cart_status_id]);
269
            $event->save();
270
271
            $prev_status_id = $cart->_changedParams['cart_cart_status_id'];
272
            $now_status_id = $cart->cart_status_id;
273
274
            $status = Ecommerce\Cart\Status::getList(['where' => ['id', implode(',', [$prev_status_id, $now_status_id]), 'IN']]);
275
276
            $prefix = isset(App::$cur->ecommerce->config['orderPrefix']) ? $config = App::$cur->ecommerce->config['orderPrefix'] : '';
277
            \App::$cur->users->AddUserActivity($cart->user_id, 3, "Статус вашего заказа номер {$prefix}{$cart->id} изменился с {$status[$prev_status_id]->name} на {$status[$now_status_id]->name}");
278
279
            if ($cart->cart_status_id == 5) {
280
                Inji::$inst->event('ecommerceCartClosed', $cart);
281
            }
282
        }
283
        return $cart;
284
    }
285
286
    public function cardTrigger($event) {
287
        $cart = $event['eventObject'];
288
        if ($cart->card) {
289
            $sum = 0;
290
            foreach ($cart->cartItems as $cartItem) {
291
                $sum += $cartItem->final_price * $cartItem->count;
292
            }
293
            $cardItemHistory = new Ecommerce\Card\Item\History();
294
            $cardItemHistory->amount = $sum;
295
            $cardItemHistory->card_item_id = $cart->card_item_id;
296
            $cardItemHistory->save();
297
            $cart->card->sum += $sum;
298
            $cart->card->save();
299
        }
300
        return $cart;
301
    }
302
303
    public function bonusTrigger($event) {
304
        $cart = $event['eventObject'];
305
        foreach ($cart->cartItems as $cartItem) {
306
            foreach ($cartItem->price->offer->bonuses as $bonus) {
307
                if ($bonus->limited && $bonus->left <= 0) {
308
                    continue;
309
                } elseif ($bonus->limited && $bonus->left > 0) {
310
                    $bonus->left -= 1;
311
                    $bonus->save();
312
                }
313
                switch ($bonus->type) {
314
                    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...
315
                        $currency = \Money\Currency::get($bonus->value);
316
                        $wallets = App::$cur->money->getUserWallets($cart->user->id);
317
                        $wallets[$currency->id]->diff($bonus->count, 'Бонус за покупку');
318
                        break;
319
                }
320
            }
321
        }
322
        return $cart;
323
    }
324
325 View Code Duplication
    function sitemap() {
1 ignored issue
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Coding Style introduced by
sitemap uses the super-global variable $_SERVER 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...
326
        $map = [];
327
        $zeroItems = \Ecommerce\Item::getList(['where' => ['category_id', 0]]);
328
        foreach ($zeroItems as $item) {
329
            $map[] = [
330
                'name' => $item->name,
331
                'url' => [
332
                    'loc' => (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . INJI_DOMAIN_NAME . ($item->getHref())
333
                ],
334
            ];
335
        }
336
337
        $categorys = \Ecommerce\Category::getList(['where' => ['parent_id', 0]]);
338
        $scan = function($category, $scan) {
339
            $map = [];
340
341
            foreach ($category->items as $item) {
342
                $map[] = [
343
                    'name' => $item->name,
344
                    'url' => [
345
                        'loc' => (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . INJI_DOMAIN_NAME . ($item->getHref())
346
                    ],
347
                ];
348
            }
349
            foreach ($category->catalogs as $child) {
350
                $map = array_merge($map, $scan($child, $scan));
351
            }
352
            return $map;
353
        };
354
        foreach ($categorys as $category) {
355
            $map = array_merge($map, $scan($category, $scan));
356
        }
357
        return $map;
358
    }
359
360
}
361