Completed
Push — development ( cfd391...deed4d )
by Andrij
12:03
created

discount_api::getUserDiscount()   C

Complexity

Conditions 7
Paths 20

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 13
nc 20
nop 1
dl 0
loc 23
rs 6.7272
c 0
b 0
f 0
1
<?php
2
3
use Cart\BaseCart;
4
use CMSFactory\assetManager;
5
use mod_discount\classes\BaseDiscount;
6
use mod_discount\classes\DiscountManager;
7
use mod_discount\Discount_product;
8
9
if (!defined('BASEPATH')) {
10
    exit('No direct script access allowed');
11
}
12
13
/**
14
 * Class discount_api for Mod_Discount module
15
 * @property BaseDiscount baseDiscount
16
 * @uses \MY_Controller
17
 * @author DevImageCms
18
 * @copyright (c) 2013, ImageCMS
19
 * @package ImageCMSModule
20
 */
21
class discount_api extends MY_Controller
0 ignored issues
show
introduced by
Class name must begin with a capital letter
Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
Coding Style introduced by
This class is not in CamelCase format.

Classes in PHP are usually named in CamelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. The whole name starts with a capital letter as well.

Thus the name database provider becomes DatabaseProvider.

Loading history...
22
{
23
24
    /**
25
     * __construct base object loaded
26
     * @access public
27
     * @author DevImageCms
28
     * @copyright (c) 2013, ImageCMS
29
     */
30
    public function __construct() {
31
        parent::__construct();
32
        $lang = new MY_Lang();
33
        $lang->load('mod_discount');
34
    }
35
36
    /**
37
     * is in project gift certificate
38
     * @deprecated since version 4.5.2
39
     * @copyright (c) 2013, ImageCMS
40
     */
41
    public function isGiftCertificat() {
42
        $this->baseDiscount = BaseDiscount::create();
43
        foreach ($this->baseDiscount->discountType['certificate'] as $disc) {
44
            if ($disc['is_gift']) {
45
                return true;
46
            }
47
        }
48
        return false;
49
    }
50
51
    /**
52
     * get gift certificate in json format
53
     * @access public
54
     * @author DevImageCms
55
     * @param (string) key optional
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
introduced by
Missing parameter name
Loading history...
56
     * @param (float) totalPrice optional
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
57
     * @return string
58
     * @copyright (c) 2013, ImageCMS
59
     */
60
    public function getGiftCertificate($key = null, $totalPrice = null) {
61
        $cart = BaseCart::getInstance();
62
        $this->baseDiscount = BaseDiscount::create();
63
        if ($totalPrice === null) {
64
            $totalPrice = $cart->getTotalPrice();
65
        }
66
67
        if (null === $key) {
68
            $key = strip_tags(trim($this->input->get('key')));
69
        }
70
71
        foreach ($this->baseDiscount->discountType['certificate'] as $disc) {
72
            if ($disc['key'] == $key and $disc['is_gift']) {
73
                $value = $this->baseDiscount->getDiscountValue($disc, $totalPrice);
74
                return json_encode(['key' => $disc['key'], 'val_orig' => $value, 'value' => ShopCore::app()->SCurrencyHelper->convert($value), 'gift_array' => $disc]);
75
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
76
            }
77
        }
78
        return json_encode(['error' => true, 'mes' => lang('Invalid code try again', 'mod_discount')]);
79
    }
80
81
    /**
82
     * get discount in json format
83
     * @access public
84
     * @author DevImageCms
85
     * @param array $option
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
86
     * @param array $typeReturn params:
0 ignored issues
show
Documentation introduced by
Should the type for parameter $typeReturn not be array|null? Also, consider making the array more specific, something like array<String>, or String[].

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive. In addition it looks for parameters that have the generic type array and suggests a stricter type like array<String>.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
87
     * - (float) price:
0 ignored issues
show
introduced by
Parameter comment must start with a capital letter
Loading history...
88
     * - (int) userId:
89
     * - (bool) ignoreCart: ignore cart Data:
90
     * - (bool) new: for redeclare singelton:
0 ignored issues
show
introduced by
Parameter comment must end with a full stop
Loading history...
91
     * @return json
0 ignored issues
show
Documentation introduced by
Should the return type not be null|array?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
92
     * @internal param $ (bool) typeReturn optional
93
     * @copyright (c) 2013, ImageCMS
94
     */
95
    public function getDiscount($option = [], $typeReturn = null) {
96
97
        if (count($option) > 0) {
98
            BaseDiscount::prepareOption($option);
99
        }
100
101
        $this->baseDiscount = BaseDiscount::create();
102
        if (BaseDiscount::checkModuleInstall()) {
103
            $discount['max_discount'] = $this->baseDiscount->discountMax;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$discount was never initialized. Although not strictly required by PHP, it is generally a good practice to add $discount = 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...
104
            $discount['sum_discount_product'] = $this->baseDiscount->discountProductVal;
105
            $discount['sum_discount_no_product'] = $this->baseDiscount->discountNoProductVal;
0 ignored issues
show
Bug introduced by
The property discountNoProductVal does not seem to exist. Did you mean discountProductVal?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
106 View Code Duplication
            if ($this->baseDiscount->discountProductVal > $this->baseDiscount->discountNoProductVal) {
0 ignored issues
show
Bug introduced by
The property discountNoProductVal does not seem to exist. Did you mean discountProductVal?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
107
                $discount['result_sum_discount'] = $this->baseDiscount->discountProductVal;
108
                $discount['type'] = 'product';
109
            } else {
110
                $discount['result_sum_discount'] = $this->baseDiscount->discountNoProductVal;
0 ignored issues
show
Bug introduced by
The property discountNoProductVal does not seem to exist. Did you mean discountProductVal?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
111
                $discount['type'] = 'user';
112
            }
113
            $discount['result_sum_discount_convert'] = ShopCore::app()->SCurrencyHelper->convert($discount['result_sum_discount']);
114
        }
115 View Code Duplication
        if ($discount['result_sum_discount']) {
116
            if ($this->input->server('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' && !$typeReturn) {
117
                echo json_encode($discount);
118
            } else {
119
                return $discount;
120
            }
121
        } else {
122
            echo '';
123
        }
124
    }
125
126
    /**
127
     * get discount product
128
     * @access public
129
     * @author DevImageCms
130
     * @param float|null $product
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
131
     * @param array [pid,vid], (float) price optional
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
132
     * @return array
133
     * @copyright (c) 2013, ImageCMS
134
     */
135
    public function getDiscountProduct($product, $price = null) {
136
        if (BaseDiscount::checkModuleInstall()) {
137
            $DiscProdObj = Discount_product::create();
138
            if ($DiscProdObj->getProductDiscount($product, $price)) {
139
                $arr = assetManager::create()->discount;
0 ignored issues
show
Bug introduced by
The property discount does not seem to exist in CMSFactory\assetManager.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
140
                if ($this->input->server('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest') {
141
                    echo json_encode($arr);
142
                } else {
143
                    return $arr;
144
                }
145
            }
146
        }
147
        return false;
148
    }
149
150
    /**
151
     * get all discount information without maximized
152
     * @access public
153
     * @author DevImageCms
154
     * @param array $option params:
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
155
     * - (float) price:
0 ignored issues
show
introduced by
Parameter comment must start with a capital letter
Loading history...
156
     * - (int) userId:
157
     * - (bool) ignoreCart: ignore cart Data:
158
     * - (bool) new: for redeclare singelton:
0 ignored issues
show
introduced by
Parameter comment must end with a full stop
Loading history...
159
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be array<string,array>|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
160
     * @copyright (c) 2013, ImageCMS
161
     */
162
    public function getUserDiscount($option = []) {
163
        if (count($option) > 0) {
164
            BaseDiscount::prepareOption($option);
165
        }
166
167
        $this->baseDiscount = BaseDiscount::create();
168
        if (BaseDiscount::checkModuleInstall()) {
169
            $this->baseDiscount->discountType['comulativ'] = $this->getComulativDiscount($option);
170
171
            foreach ($this->baseDiscount->discountType['user'] as $user) {
172
                if ($user['user_id'] == $this->dx_auth->get_user_id()) {
173
                    $this->baseDiscount->discountType['user'][0] = $user;
174
                }
175
            }
176
177
            foreach ($this->baseDiscount->discountType['group_user'] as $group) {
178
                if ($group['group_id'] == $this->dx_auth->get_role_id()) {
179
                    $this->baseDiscount->discountType['group_user'][0] = $group;
180
                }
181
            }
182
            return $this->baseDiscount->discountType;
183
        }
184
    }
185
186
    /**
187
     * If discount for current user exist or nots
188
     * @return boolean
189
     */
190
    public function discountsExists() {
191
        $ud = $this->userDiscountExists();
192
        $gd = $this->groupDiscountExists();
193
        $userDiscount = $this->getUserDiscount();
194
        return $ud || $gd || (bool) $userDiscount['comulativ'] ? TRUE : FALSE;
195
    }
196
197
    public function userDiscountExists() {
198
        return (bool) !DiscountManager::validateUserDiscount(CI::$APP->dx_auth->get_user_id());
199
    }
200
201
    public function groupDiscountExists() {
202
        return (bool) !DiscountManager::validateGroupDiscount(CI::$APP->dx_auth->get_role_id());
203
    }
204
205
    /**
206
     * get comulativ discount sorting
207
     * @access private
208
     * @author DevImageCms
209
     * @param (float) price optional
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
introduced by
Missing parameter name
Loading history...
210
     * @param (float) userId optional
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
211
     * @param (bool) new optional
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
212
     * @return array
213
     * @copyright (c) 2013, ImageCMS
214
     */
215
    private function getComulativDiscount($option) {
216
217
        if (count($option) > 0) {
218
            BaseDiscount::prepareOption($option);
219
        }
220
221
        $this->baseDiscount = BaseDiscount::create();
222
223
        return user_function_sort($this->baseDiscount->discountType['comulativ'], 'begin_value');
224
    }
225
226
    /**
227
     * get one discount
228
     * @access public
229
     * @author DevImageCms
230
     * @param string $key: criteria
0 ignored issues
show
Bug introduced by
There is no parameter named $key:. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
introduced by
Doc comment for parameter $key: does not match actual variable name $id
Loading history...
231
     * @param int $id: id discount
0 ignored issues
show
Bug introduced by
There is no parameter named $id:. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
introduced by
Doc comment for parameter $id: does not match actual variable name $id
Loading history...
232
     * @return string|false
233
     * @copyright (c) 2013, ImageCMS
234
     */
235
    public function getDiscountBy($key, $id) {
236
237
        $this->baseDiscount = BaseDiscount::create();
238
        foreach ($this->baseDiscount->allDiscount as $disc) {
239
            switch ($key) {
240
                case 'key':
241
                    if ($disc['key'] == $id) {
242
                        return json_encode($disc);
243
                    }
244
                    break;
0 ignored issues
show
Coding Style introduced by
Case breaking statements must be followed by a single blank line
Loading history...
245
                case 'id':
246
                    if ($disc['ids'] == $id) {
247
                        return json_encode($disc);
248
                    }
249
                    break;
250
251
                default:
252
                    break;
253
            }
254
        }
255
        return false;
256
    }
257
258
    /**
259
     * get all active discount
260
     * @access public
261
     * @author DevImageCms
262
     * @param (float) price optional
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
introduced by
Missing parameter name
Loading history...
263
     * @param (float) userId optional
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
264
     * @param (bool) new optional
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
265
     * @return string
266
     * @copyright (c) 2013, ImageCMS
267
     */
268
    public function getAllDiscount() {
269
270
        $this->baseDiscount = BaseDiscount::create();
271
        return json_encode($this->baseDiscount->discountType);
272
    }
273
274
    /**
275
     * apply discount for all products
276
     * @access public
277
     * @author DevImageCms
278
     * @return (int) cnt: count update products
279
     * @copyright (c) 2013, ImageCMS
280
     */
281
    public function applyProductDiscount() {
282
283
        $productVariants = $this->db
284
            ->select('shop_product_variants.id as var_id, shop_product_variants.price as price, shop_products.id as id, shop_products.brand_id as brand_id, shop_products.category_id as category_id')
285
            ->from('shop_products')
286
            ->join('shop_product_variants', 'shop_product_variants.product_id = shop_products.id')
287
            ->get('shop_product_variants')
288
            ->result_array();
289
        foreach ($productVariants as $var) {
290
            $arr_for_discount = [
291
                                 'product_id'  => $var['id'],
292
                                 'category_id' => $var['category_id'],
293
                                 'brand_id'    => $var['brand_id'],
294
                                 'vid'         => $var['var_id'],
295
                                 'id'          => $var['id'],
296
                                ];
297
            assetManager::create()->discount = 0;
0 ignored issues
show
Bug introduced by
The property discount does not seem to exist in CMSFactory\assetManager.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
298
            Discount_product::create()->getProductDiscount($arr_for_discount);
299
300
            if ($discount = assetManager::create()->discount) {
301
                $priceNew = ((float) $var['price'] - (float) $discount['discount_value'] < 0) ? 1 : (float) $var['price'] - (float) $discount['discount_value'];
302
                $dataProductUpdate = [
303
                                      'price'         => ($discount) ? $priceNew : $var['price'],
304
                                      'price_no_disc' => $var['price'],
305
                                      'disc'          => $discount['discount_value'],
306
                                     ];
307
                $this->db->where('id', $var['var_id'])->update('shop_product_variants', $dataProductUpdate);
308
                $cnt++;
309
            }
310
        }
311
        return $cnt;
312
    }
313
314
    /**
315
     * is in project gift certificate
316
     * @deprecated since version 4.5.2
317
     * @copyright (c) 2013, ImageCMS
318
     */
319
    public function is_gift_certificat() {
320
        return $this->isGiftCertificat();
0 ignored issues
show
Deprecated Code introduced by
The method discount_api::isGiftCertificat() has been deprecated with message: since version 4.5.2

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
321
    }
322
323
    /**
324
     * render gift input
325
     * @deprecated since version 4.5.2
326
     * @copyright (c) 2013, ImageCMS
327
     */
328
    public function render_gift_input($mes = null) {
329
        if (BaseDiscount::checkModuleInstall()) {
330
            if ($this->is_gift_certificat()) {
0 ignored issues
show
Deprecated Code introduced by
The method discount_api::is_gift_certificat() has been deprecated with message: since version 4.5.2

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
331
                assetManager::create()->setData(['mes' => $mes])->render('gift', true);
332
            }
333
        }
334
    }
335
336
    /**
337
     * get gift certificate in tpl
338
     * @deprecated since version 4.5.2
339
     * @copyright (c) 2013, ImageCMS
340
     */
341
    public function render_gift_succes() {
342
        $json = json_decode($this->input->get('json'));
343
        assetManager::create()->setData(['gift' => $json])->render('gift_succes', true);
344
    }
345
346
    /**
347
     * get all discount information without maximized
348
     * @deprecated since version 4.5.2
349
     * @copyright (c) 2013, ImageCMS
350
     * @param array $option
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
351
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be array<string,array>|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
352
     */
353
    public function get_user_discount_api($option = []) {
354
        return $this->getUserDiscount($option);
355
    }
356
357
    /**
358
     * get discount product
359
     * @deprecated since version 4.5.2
360
     * @copyright (c) 2013, ImageCMS
361
     * @param $product
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
introduced by
Missing parameter type
Loading history...
362
     * @param null $typeReturn
363
     * @param null $price
364
     * @return array
365
     */
366
    public function get_discount_product_api($product, $typeReturn = null, $price = null) {
367
        return $this->getDiscountProduct($product, $typeReturn = null, $price = null);
368
    }
369
370
    /**
371
     * get discount in tpl format from json
372
     * @deprecated since version 4.5.2
373
     * @copyright (c) 2013, ImageCMS
374
     */
375
    public function get_discount_tpl_from_json_api() {
376
        $json = json_decode($this->input->get('json'));
377
378
        assetManager::create()->setData(['discount' => $json])->render('discount_order', true);
379
    }
380
381
    /**
382
     * get discount in json format
383
     * @deprecated since version 4.5.2
384
     * @copyright (c) 2013, ImageCMS
385
     * @param array $option
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
386
     * @return json
0 ignored issues
show
Documentation introduced by
Should the return type not be null|array?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
387
     */
388
    public function get_discount_api($option = []) {
389
        return $this->getDiscount($option);
390
    }
391
392
    /**
393
     * get gift certificate in json format
394
     * @deprecated since version 4.5.2
395
     * @copyright (c) 2013, ImageCMS
396
     * @param null|string $key
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
397
     * @param null|string $totalPrice
398
     * @return string
399
     */
400
    public function get_gift_certificate($key = null, $totalPrice = null) {
401
        return $this->getGiftCertificate($key = null, $totalPrice = null);
402
    }
403
404
}