DiscountManager::validation()   F
last analyzed

Complexity

Conditions 47
Paths > 20000

Size

Total Lines 86

Duplication

Lines 24
Ratio 27.91 %

Importance

Changes 0
Metric Value
cc 47
nc 1572864
nop 2
dl 24
loc 86
rs 0
c 0
b 0
f 0

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
// to do validate max_aply, comulativ begin value end value, all_order begin_value
4
5
namespace mod_discount\classes;
6
7
use MY_Controller;
8
use MY_Lang;
9
10
if (!defined('BASEPATH')) {
11
    exit('No direct script access allowed');
12
}
13
14
/**
15
 * Class DiscountManager for Mod_Discount module
16
 * @use \My_Controller
17
 * @author DevImageCms
18
 * @copyright (c) 2013, ImageCMS
19
 * @package ImageCMSModule
20
 * @property discount_model_admin $discount_model_admin
21
 */
22
class DiscountManager extends MY_Controller
23
{
24
25
    public $error = [];
26
27
    public function __construct() {
28
29
        parent::__construct();
30
        $lang = new MY_Lang();
31
        $lang->load('mod_discount');
32
        $this->load->model('discount_model_admin');
33
    }
34
35
    /**
36
     * create brand discount
37
     * @access public
38
     * @author DevImageCms
39
     * @param array $data input params:
40
     * - (string) key: discount key optional
41
     * - (string) name: discount name
42
     * - (int) max_apply: max apply discount default null - infinity
43
     * - (int) type_value: 1 - % 2 - float
44
     * - (int) value: discount value
45
     * - (string) type_discount: (all_order, comulativ, user, group_user, category, product, brand)
46
     * - (string) date_begin: data begin discount
47
     * - (string) date_end: data end discount default null - infinity
48
     * - (int) brand_id: id brand
49
     * @return array $data params:
50
     * - (boolean) success: result of create brand discount
51
     * - (string) errors: message of error
52
     * @copyright (c) 2013, ImageCMS
53
     */
54 View Code Duplication
    public function createBrandDiscount($data) {
55
56
        if (!$this->discount_model_admin->checkEntityExists('brand', $data['brand_id'])) {
57
            $this->error[] = lang('Entity does not exists!', 'mod_discount');
58
        }
59
        $data['type_discount'] = 'brand';
60
        $data['brand']['brand_id'] = $data['brand_id'];
61
        unset($data['brand_id']);
62
        return $this->create($data);
63
    }
64
65
    /**
66
     * create category discount
67
     * @access public
68
     * @author DevImageCms
69
     * @param array $data input params:
70
     * - (string) key: discount key optional
71
     * - (string) name: discount name
72
     * - (int) max_apply: max apply discount default null - infinity
73
     * - (int) type_value: 1 - % 2 - float
74
     * - (int) value: discount value
75
     * - (string) type_discount: (all_order, comulativ, user, group_user, category, product, brand)
76
     * - (string) date_begin: data begin discount
77
     * - (string) date_end: data end discount default null - infinity
78
     * - (int) category_id: id category
79
     * - (int) child: change childs category
80
     * @return array $data params:
81
     * - (boolean) success: result of create category discount
82
     * - (string) errors: message of error
83
     * @copyright (c) 2013, ImageCMS
84
     */
85
    public function createCategoryDiscount($data) {
86
87
        if (!$this->discount_model_admin->checkEntityExists('category', $data['category_id'])) {
88
            $this->error[] = lang('Entity does not exists!', 'mod_discount');
89
        }
90
        $data['type_discount'] = 'category';
91
        $data['category']['category_id'] = $data['category_id'];
92
        $data['category']['child'] = $data['child'];
93
        unset($data['category_id']);
94
        return $this->create($data);
95
    }
96
97
    /**
98
     * create product discount
99
     * @access public
100
     * @author DevImageCms
101
     * @param array $data input params:
102
     * - (string) key: discount key optional
103
     * - (string) name: discount name
104
     * - (int) max_apply: max apply discount default null - infinity
105
     * - (int) type_value: 1 - % 2 - float
106
     * - (int) value: discount value
107
     * - (string) type_discount: (all_order, comulativ, user, group_user, category, product, brand)
108
     * - (string) date_begin: data begin discount
109
     * - (string) date_end: data end discount default null - infinity
110
     * - (int) product_id: id product
111
     * @return array $data params:
112
     * - (boolean) success: result of create product discount
113
     * - (string) errors: message of error
114
     * @copyright (c) 2013, ImageCMS
115
     */
116 View Code Duplication
    public function createProductDiscount($data) {
117
118
        if (!$this->discount_model_admin->checkEntityExists('product', $data['product_id'])) {
119
            $this->error[] = lang('Entity does not exists!', 'mod_discount');
120
        }
121
        $data['type_discount'] = 'product';
122
        $data['product']['product_id'] = $data['product_id'];
123
        unset($data['product_id']);
124
        return $this->create($data);
125
    }
126
127
    /**
128
     * create user discount
129
     * @access public
130
     * @author DevImageCms
131
     * @param array $data input params:
132
     * - (string) key: discount key optional
133
     * - (string) name: discount name
134
     * - (int) max_apply: max apply discount default null - infinity
135
     * - (int) type_value: 1 - % 2 - float
136
     * - (int) value: discount value
137
     * - (string) type_discount: (all_order, comulativ, user, group_user, category, product, brand)
138
     * - (string) date_begin: data begin discount
139
     * - (string) date_end: data end discount default null - infinity
140
     * - (int) user_id: id user
141
     * @return array $data params:
142
     * - (boolean) success: result of create user discount
143
     * - (string) errors: message of error
144
     * @copyright (c) 2013, ImageCMS
145
     */
146 View Code Duplication
    public function createUserDiscount($data) {
147
148
        if (!$this->discount_model_admin->checkEntityExists('user', $data['user_id'])) {
149
            $this->error[] = lang('Entity does not exists!', 'mod_discount');
150
        }
151
        $data['type_discount'] = 'user';
152
        $data['user']['user_id'] = $data['user_id'];
153
        unset($data['user_id']);
154
        return $this->create($data);
155
    }
156
157
    /**
158
     * create user group discount discount
159
     * @access public
160
     * @author DevImageCms
161
     * @param array $data input params:
162
     * - (string) key: discount key optional
163
     * - (string) name: discount name
164
     * - (int) max_apply: max apply discount default null - infinity
165
     * - (int) type_value: 1 - % 2 - float
166
     * - (int) value: discount value
167
     * - (string) type_discount: (all_order, comulativ, user, group_user, category, product, brand)
168
     * - (string) date_begin: data begin discount
169
     * - (string) date_end: data end discount default null - infinity
170
     * - (int) group_id: id user group
171
     * @return array $data params:
172
     * - (boolean) success: result of create user group discount
173
     * - (string) errors: message of error
174
     * @copyright (c) 2013, ImageCMS
175
     */
176 View Code Duplication
    public function createUserGroupDiscount($data) {
177
178
        if (!$this->discount_model_admin->checkEntityExists('group_user', $data['group_id'])) {
179
            $this->error[] = lang('Entity does not exists!', 'mod_discount');
180
        }
181
        $data['type_discount'] = 'group_user';
182
        $data['group_user']['group_id'] = $data['group_id'];
183
        unset($data['group_id']);
184
        return $this->create($data);
185
    }
186
187
    /**
188
     * create comulativ discount
189
     * @access public
190
     * @author DevImageCms
191
     * @param array $data input params:
192
     * - (string) key: discount key optional
193
     * - (string) name: discount name
194
     * - (int) max_apply: max apply discount default null - infinity
195
     * - (int) type_value: 1 - % 2 - float
196
     * - (int) value: discount value
197
     * - (string) type_discount: (all_order, comulativ, user, group_user, category, product, brand)
198
     * - (string) date_begin: data begin discount
199
     * - (string) date_end: data end discount default null - infinity
200
     * - (float) begin_value: value begin
201
     * - (float) end_value: value end default null - infinity
202
     * @return array $data params:
203
     * - (boolean) success: result of create comulativ
204
     * - (string) errors: message of error
205
     * @copyright (c) 2013, ImageCMS
206
     */
207
    public function createComulativDiscount($data) {
208
209
        $data['type_discount'] = 'comulativ';
210
        $data['comulativ']['begin_value'] = $data['begin_value'];
211
        $data['comulativ']['end_value'] = $data['end_value'];
212
        unset($data['begin_value']);
213
        unset($data['end_value']);
214
        return $this->create($data);
215
    }
216
217
    /**
218
     * create gift discount
219
     * @access public
220
     * @author DevImageCms
221
     * @param array $data input params:
222
     * - (string) key: discount key optional
223
     * - (string) name: discount name
224
     * - (int) max_apply: max apply discount default null - infinity
225
     * - (int) type_value: 1 - % 2 - float
226
     * - (int) value: discount value
227
     * - (string) type_discount: (all_order, comulativ, user, group_user, category, product, brand)
228
     * - (string) date_begin: data begin discount
229
     * - (string) date_end: data end discount default null - infinity
230
     * @return array $data params:
231
     * - (boolean) success: result of create gift
232
     * - (string) errors: message of error
233
     * @copyright (c) 2013, ImageCMS
234
     */
235
    public function createGift($data) {
236
237
        $data['type_discount'] = 'all_order';
238
        $data['all_order']['is_gift'] = 1;
239
        $data['max_apply'] = 777;
240
        return $this->create($data);
241
    }
242
243
    /**
244
     * delete discount
245
     * @access public
246
     * @author DevImageCms
247
     * @param (int) id discount:
248
     * @return (boolean) success: result of deleting
249
     * @copyright (c) 2013, ImageCMS
250
     */
251
    public function deleteDiscount($id) {
252
253
        return $this->discount_model_admin->deleteDiscountById($id);
254
    }
255
256
    /**
257
     * create discount
258
     * @access public
259
     * @author DevImageCms
260
     * @param array $postArray input params:
261
     * @return array $data params:
262
     * - (boolean) success: result of create
263
     * - (string) errors: message of error
264
     * @copyright (c) 2013, ImageCMS
265
     */
266
    public function create($postArray) {
267
268
        $this->validation($postArray);
269
270
        if (count($this->error) > 0) {
271
            return [
272
                    'success' => false,
273
                    'error'   => $this->error,
274
                   ];
275
        }
276
277
        if (!$postArray['key']) {
278
            $postArray['key'] = self::generateDiscountKey();
279
        }
280
281
        $typeDiscount = $postArray['type_discount'];
282
        $typeDiscountTableName = 'mod_discount_' . $typeDiscount;
283
284
        // Check range for cumulative discount
285
        if ($typeDiscount == 'comulativ' AND $this->discount_model_admin->checkRangeForCumulativeDiscount($postArray[$typeDiscount])) {
286
            return [
287
                    'success' => false,
288
                    'error'   => [lang('Has been already created with the cumulative discount value', 'mod_discount')],
289
                   ];
290
        }
291
292
        $data = [
293
                 'key'           => $postArray['key'],
294
                 'type_value'    => $postArray['type_value'],
295
                 'value'         => $postArray['value'],
296
                 'type_discount' => $typeDiscount,
297
                 'date_begin'    => strtotime($postArray['date_begin']),
298
                 'date_end'      => strtotime($postArray['date_end']),
299
                 'active'        => '1',
300
                ];
301
302
        if ($postArray['max_apply']) {
303
            $data['max_apply'] = $postArray['max_apply'];
304
        }
305
306
        // gift correction (just in case)
307
        if ($postArray['all_order']['is_gift']) {
308
            $data['max_apply'] = 1;
309
        }
310
311
        if ($postArray['certificate']['is_gift']) {
312
            $data['max_apply'] = 1;
313
        }
314
315
        if ($postArray['type_discount'] == 'certificate') {
316
            $data['max_apply'] = 1;
317
            $postArray['all_order']['is_gift'] = 1;
318
            $postArray['certificate']['is_gift'] = 1;
319
        }
320
321
        $discountId = $this->discount_model_admin->insertDataToDB('mod_shop_discounts', $data);
322
323
        $data_locale = [
324
                        'id'     => $discountId,
325
                        'locale' => MY_Controller::getCurrentLocale(),
326
                        'name'   => $postArray['name'],
327
                       ];
328
329
        $typeDiscountData = $postArray[$typeDiscount];
330
331
        $this->discount_model_admin->insertDataToDB('mod_shop_discounts_i18n', $data_locale);
332
333
        if ($discountId != false) {
334
            $typeDiscountData['discount_id'] = $discountId;
335
            $typeDiscountTableName = $typeDiscountTableName == 'mod_discount_certificate' ? 'mod_discount_all_order' : $typeDiscountTableName;
336
            $result = $this->discount_model_admin->insertDataToDB($typeDiscountTableName, $typeDiscountData);
337
        }
338
339
        if ($result && $discountId) {
340
            return [
341
                    'success' => true,
342
                    'id'      => $discountId,
343
                   ];
344
        } else {
345
            return [
346
                    'success' => false,
347
                    'error'   => [lang('Error creating discount', 'mod_discount')],
348
                   ];
349
        }
350
    }
351
352
    /**
353
     * validation data
354
     * @access public
355
     * @author DevImageCms
356
     * @param array $postArray
357
     * @param integer $id (optional) need to be specified on discount editing
358
     * @copyright (c) 2013, ImageCMS
359
     */
360
    public function validation($postArray, $id = null) {
361
362
        $typeDiscount = $postArray['type_discount'];
363
364
        if (!in_array($typeDiscount, ['certificate', 'all_order', 'comulativ', 'user', 'group_user', 'category', 'product', 'brand'])) {
365
            $this->error[] = lang('Wrong type discount', 'mod_discount');
366
        }
367
368 View Code Duplication
        if ($typeDiscount == 'comulativ' && $postArray[$typeDiscount]['end_value'] && !preg_match('/^[0-9]{1,15}$/', $postArray[$typeDiscount]['end_value'])) {
369
            $this->error[] = lang('End value must be numeric');
370
        }
371
372 View Code Duplication
        if ($typeDiscount == 'comulativ' && $postArray[$typeDiscount]['begin_value'] && !preg_match('/^[0-9]{1,15}$/', $postArray[$typeDiscount]['begin_value'])) {
373
            $this->error[] = lang('Begin value must be numeric');
374
        }
375
376 View Code Duplication
        if ($typeDiscount == 'certificate' && $postArray[$typeDiscount]['begin_value'] && !preg_match('/^[0-9]{1,15}$/', $postArray[$typeDiscount]['begin_value'])) {
377
            $this->error[] = lang('Begin value must be numeric');
378
        }
379
380 View Code Duplication
        if ($typeDiscount == 'all_order' && $postArray[$typeDiscount]['begin_value'] && !preg_match('/^[0-9]{1,15}$/', $postArray[$typeDiscount]['begin_value'])) {
381
            $this->error[] = lang('Begin value must be numeric');
382
        }
383
384
        if ($postArray['max_apply'] && !preg_match('/^[0-9]{1,15}$/', $postArray['max_apply'])) {
385
            $this->error[] = lang('Max apply must be numeric');
386
        }
387
388
        if (!$postArray['value'] || !preg_match('/^[0-9]{1,15}$/', $postArray['value'])) {
389
            $this->error[] = lang('Value must be numeric', 'mod_discount');
390
        }
391
392
        if ($typeDiscount == 'comulativ' && $postArray[$typeDiscount]['end_value'] < $postArray[$typeDiscount]['begin_value'] && is_numeric($postArray[$typeDiscount]['end_value'])) {
393
            $this->error[] = lang('Amount <<from>> can not be greater than the sum <<to>>', 'mod_discount');
394
        }
395
396
        if ($typeDiscount == 'product' && !$postArray[$typeDiscount]['product_id']) {
397
            $this->error[] = lang('Enter a product that is in the database', 'mod_discount');
398
        }
399
400 View Code Duplication
        if ($typeDiscount == 'user' && !$postArray[$typeDiscount]['user_id']) {
401
            $this->error[] = lang('Enter the user who is in the database', 'mod_discount');
402
        }
403
404 View Code Duplication
        if ($typeDiscount == 'user' && !$this->validateUserDiscount($postArray[$typeDiscount]['user_id']) && $id == null) {
405
            $this->error[] = lang('This user already have active discount', 'mod_discount');
406
        }
407
408
        if ($typeDiscount == 'group_user' && !$this->validateGroupDiscount($postArray[$typeDiscount]['group_id']) && $id == null) {
409
            $this->error[] = lang('This group of users already have active discount', 'mod_discount');
410
        }
411
412
        if ($typeDiscount == 'comulativ' && $postArray[$typeDiscount]['end_value'] == null && $this->discount_model_admin->checkHaveAnyComulativDiscountMaxEndValue($id)) {
413
            $this->error[] = lang('There can be more than one discount with said upper threshold as a <<maximum>>!', 'mod_discount');
414
        }
415
416 View Code Duplication
        if ($postArray['type_value'] != 1 && $postArray['type_value'] != 2) {
417
            $this->error[] = lang('Invalid type value!', 'mod_discount');
418
        }
419
420 View Code Duplication
        if ($postArray['type_value'] == 1 && $postArray['value'] >= 100) {
421
            $this->error[] = lang('Invalid type value!', 'mod_discount');
422
        }
423
424
        if (!preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $postArray['date_begin'])) {
425
            $this->error[] = lang('Invalid date range!', 'mod_discount');
426
        }
427
428
        if ($postArray['date_end'] && !preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $postArray['date_end'])) {
429
            $this->error[] = lang('Invalid date range!', 'mod_discount');
430
        }
431
432
        if ($postArray['date_begin'] >= $postArray['date_end'] && !$postArray['date_end'] == null) {
433
            $this->error[] = lang('Invalid date range!', 'mod_discount');
434
        }
435
436
        if ($typeDiscount == 'comulativ' && $postArray['comulativ']['begin_value'] === $postArray['comulativ']['end_value']) {
437
            $this->error[] = lang('Values `from` and `to` can not be equal', 'mod_discount');
438
        }
439
440
        if ($typeDiscount == 'comulativ') {
441
            if ($this->discount_model_admin->checkRangeForCumulativeDiscount($postArray['comulativ'], $id)) {
442
                $this->error[] = lang('Has been already created with the cumulative discount value', 'mod_discount');
443
            }
444
        }
445
    }
446
447
    /**
448
     * Helper function for checking that user have no discounts already
449
     * @param integer $userId id of user
450
     * @return boolean true if user have no discounts alreaty, false otherwise
451
     */
452
    public static function validateUserDiscount($userId) {
453
454
        $data = BaseDiscount::create()->discountType['user'];
455
        foreach ($data as $oneDiscountData) {
456
            if ($oneDiscountData['user_id'] == $userId) {
457
                return FALSE;
458
            }
459
        }
460
        return TRUE;
461
    }
462
463
    /**
464
     * Helper function for checking that user-group have no discounts already
465
     * @param integer $groupId id of group
466
     * @return boolean true if user-group have no discounts alreaty, false otherwise
467
     */
468
    public static function validateGroupDiscount($groupId) {
469
470
        $data = BaseDiscount::create()->discountType['group_user'];
471
        foreach ($data as $oneDiscountData) {
472
            if ($oneDiscountData['group_id'] == $groupId) {
473
                return FALSE;
474
            }
475
        }
476
        return TRUE;
477
    }
478
479
    /**
480
     * Generate key for discount
481
     *
482
     * @param integer $charsCount
483
     * @param integer $digitsCount
484
     * @static
485
     * @return string
486
     */
487
    public static function generateDiscountKey($charsCount = 8, $digitsCount = 8) {
488
        $ci = get_instance();
489
        $ci->load->helper('string');
490
        $result = random_string('alnum', $charsCount + $digitsCount);
491
        if ($ci->discount_model_admin->checkDiscountCode($result)) {
492
            return self::generateDiscountKey($charsCount, $digitsCount);
493
        }
494
        return strtolower($result);
495
    }
496
497
}