Completed
Branch master (bb48cc)
by vijay
148:50 queued 92:39
created

CartController   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 291
Duplicated Lines 17.87 %

Coupling/Cohesion

Components 2
Dependencies 10

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 36
c 3
b 1
f 0
lcom 2
cbo 10
dl 52
loc 291
rs 8.8

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 16 1
A ProductList() 0 20 4
A Cart() 0 19 4
C CheckTax() 36 77 9
A CartRemove() 0 7 1
A ReduseQty() 8 8 1
A IncreaseQty() 8 8 1
A AddAddons() 0 14 1
A GetProductAddons() 0 9 2
B AddProduct() 0 38 4
A ClearCart() 0 5 1
A LicenceCart() 0 19 2
A cartUpdate() 0 10 2
A addCurrencyAttributes() 0 16 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace App\Http\Controllers\Front;
4
5
use App\Http\Controllers\Common\TemplateController;
6
use App\Http\Controllers\Controller;
7
use App\Model\Payment\Currency;
8
use App\Model\Payment\Tax;
9
use App\Model\Payment\TaxRules;
10
use App\Model\Product\Product;
11
use Cart;
12
use Illuminate\Http\Request;
13
14
class CartController extends Controller {
15
16
    public $templateController;
17
    public $product;
18
    public $currency;
19
    public $taxRules;
20
    public $addons;
21
    public $addonRelation;
22
    public $licence;
23
24
    public function __construct() {
25
        $templateController = new TemplateController();
26
        $this->templateController = $templateController;
27
28
        $product = new Product();
29
        $this->product = $product;
30
31
        $currency = new Currency();
32
        $this->currency = $currency;
33
34
        $tax = new Tax();
35
        $this->tax = $tax;
0 ignored issues
show
Bug introduced by
The property tax does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
36
37
        $taxRules = new TaxRules();
38
        $this->taxRules = $taxRules;
39
    }
40
41
    public function ProductList(Request $request) {
42
43
        if (!$request->has('currency')) {
44
            $currency = "USD";
45
        } else {
46
            $currency = $request->input('currency');
47
        }
48
        \Session::put('currency', $currency);
49
        if (!\Session::has('currency')) {
50
            \Session::put('currency', 'USD');
51
            //dd(\Session::get('currency'));
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
52
        }
53
54
55
        try {
56
            return $this->templateController->show(1);
57
        } catch (\Exception $ex) {
58
            return redirect()->back()->with('fails', $ex->getMessage());
59
        }
60
    }
61
62
    public function Cart(Request $request) {
63
        try {
64
            $id = $request->input('id');
65
            if (!array_key_exists($id, Cart::getContent()->toArray())) {
66
                $items = $this->AddProduct($id);
67
                Cart::add($items);
68
            }
69
70
            $cartCollection = Cart::getContent();
71
            foreach($cartCollection as $item){
72
                $attributes[]=$item->attributes;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$attributes was never initialized. Although not strictly required by PHP, it is generally a good practice to add $attributes = 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...
73
            }
74
            return view('themes.default1.front.cart', compact('cartCollection','attributes'));
75
        } catch (\Exception $ex) {
76
            dd($ex);
77
78
            return redirect()->back()->with('fails', $ex->getMessage());
79
        }
80
    }
81
82
    public function CheckTax($isTaxApply,$id) {
83
        try {
84
            $rate1 = 0;
85
            $rate2 = 0;
86
            $name1 = 'null';
87
            $name2 = 'null';
88
            $ruleEnabled = $this->taxRules->where('id', '1')->first();
89
            if ($ruleEnabled) {
90
                $enabled = $ruleEnabled->status;
91
                $type = $ruleEnabled->type;
92
                $compound = $ruleEnabled->compound;
93
                if ($enabled == 1 && $type == 'exclusive') {
94
                    if ($isTaxApply == 1) {
95
                        $tax1 = $this->tax->where('level', 1)->first();
96
                        $tax2 = $this->tax->where('level', 2)->first();
97 View Code Duplication
                        if ($tax1) {
98
                            $name1 = $tax1->name;
99
                            $rate1 = $tax1->rate;
100
                            $taxCondition1 = new \Darryldecode\Cart\CartCondition([
101
                                'name' => $name1,
102
                                'type' => 'tax',
103
                                'target' => 'item',
104
                                'value' => $rate1 . '%',
105
                            ]);
106
                        } else {
107
                            $taxCondition1 = new \Darryldecode\Cart\CartCondition([
108
                                'name' => $name1,
109
                                'type' => 'tax',
110
                                'target' => 'item',
111
                                'value' => $rate1,
112
                            ]);
113
                        }
114 View Code Duplication
                        if ($tax2) {
115
                            $name2 = $tax2->name;
116
                            $rate2 = $tax2->rate;
117
                            $taxCondition2 = new \Darryldecode\Cart\CartCondition([
118
                                'name' => $name2,
119
                                'type' => 'tax',
120
                                'target' => 'item',
121
                                'value' => $rate2 . '%',
122
                            ]);
123
                        } else {
124
                            $taxCondition2 = new \Darryldecode\Cart\CartCondition([
125
                                'name' => $name2,
126
                                'type' => 'tax',
127
                                'target' => 'item',
128
                                'value' => $rate2,
129
                            ]);
130
                        }
131
                    } else {
132
                        $taxCondition1 = new \Darryldecode\Cart\CartCondition([
133
                            'name' => $name1,
134
                            'type' => 'tax',
135
                            'target' => 'item',
136
                            'value' => $rate1,
137
                        ]);
138
                        $taxCondition2 = new \Darryldecode\Cart\CartCondition([
139
                            'name' => $name2,
140
                            'type' => 'tax',
141
                            'target' => 'item',
142
                            'value' => $rate2,
143
                        ]);
144
                    }
145
                    $currency_attribute = $this->addCurrencyAttributes($id);
146
                    //dd($currency_attribute);
147
                    if ($compound == 1) {
148
                        return ['conditions' => [$taxCondition1, $taxCondition2], 'attributes' => ['tax' => [['name' => $name1, 'rate' => $rate1], ['name' => $name2, 'rate' => $rate2]],'currency'=>$currency_attribute]];
149
                    } else {
150
                        return ['conditions' => $taxCondition2, 'attributes' => ['tax' => [['name' => $name2, 'rate' => $rate2]],'currency'=>$currency_attribute]];
151
                    }
152
                }
153
            }
154
        } catch (\Exception $ex) {
155
            dd($ex);
156
            throw new \Exception('Can not check the tax');
157
        }
158
    }
159
160
    public function CartRemove(Request $request) {
161
        $id = $request->input('id');
162
        //dd($id);
163
        Cart::remove($id);
164
165
        return 'success';
166
    }
167
168 View Code Duplication
    public function ReduseQty(Request $request) {
169
        $id = $request->input('id');
170
        Cart::update($id, [
171
            'quantity' => -1, // so if the current product has a quantity of 4, it will subtract 1 and will result to 3
172
        ]);
173
        //dd(Cart::getContent());
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
174
        return 'success';
175
    }
176
177 View Code Duplication
    public function IncreaseQty(Request $request) {
178
        $id = $request->input('id');
179
        Cart::update($id, [
180
            'quantity' => +1, // so if the current product has a quantity of 4, it will add 1 and will result to 5
181
        ]);
182
        //dd(Cart::getContent());
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
183
        return 'success';
184
    }
185
186
    public function AddAddons($id) {
187
        $addon = $this->addons->where('id', $id)->first();
188
189
        $isTaxApply = $addon->tax_addon;
190
191
        $taxConditions = $this->CheckTax($isTaxApply);
0 ignored issues
show
Bug introduced by
The call to CheckTax() misses a required argument $id.

This check looks for function calls that miss required arguments.

Loading history...
192
193
        $items = ['id' => 'addon' . $addon->id, 'name' => $addon->name, 'price' => $addon->selling_price, 'quantity' => 1];
194
        $items = array_merge($items, $taxConditions);
195
196
        //dd($items);
197
198
        return $items;
199
    }
200
201
    public function GetProductAddons($productId) {
202
        $addons = [];
203
        if ($this->addonRelation->where('product_id', $productId)->count() > 0) {
204
            $addid = $this->addonRelation->where('product_id', $productId)->pluck('addon_id')->toArray();
205
            $addons = $this->addons->whereIn('id', $addid)->get();
206
        }
207
208
        return $addons;
209
    }
210
211
    public function AddProduct($id) {
212
        $currency = \Session::get('currency');
213
//        if (!$currency) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
214
//            $currency = 'USD';
215
//        }
216
        $product = $this->product->where('id', $id)->first();
217
        if ($product) {
218
            $productCurrency = $product->price()->where('currency', $currency)->first()->currency;
219
            $actualPrice = $product->price()->where('currency', $currency)->first()->sales_price;
220
            if (!$actualPrice) {
221
                $actualPrice = $product->price()->where('currency', $currency)->first()->price;
222
            }
223
            $currency = $this->currency->where('code', $productCurrency)->get()->toArray();
224
225
            $productName = $product->name;
226
227
            /*
228
             * Check the Tax is On
229
             */
230
            $isTaxApply = $product->tax_apply;
231
232
            $taxConditions = $this->CheckTax($isTaxApply,$id);
233
            //dd($taxConditions);
234
235
            /*
236
             * Check if this product allow multiple qty
237
             */
238
            if ($product->multiple_qty == 1) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
239
                // Allow
240
            } else {
241
                $qty = 1;
242
            }
243
            $items = ['id' => $id, 'name' => $productName, 'price' => $actualPrice, 'quantity' => $qty, 'attributes' => ['currency' => [[$currency]]]];
0 ignored issues
show
Bug introduced by
The variable $qty does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
244
            $items = array_merge($items, $taxConditions);
245
246
            return $items;
247
        }
248
    }
249
250
    public function ClearCart() {
251
        Cart::clear();
252
253
        return redirect('home');
254
    }
255
256
    public function LicenceCart($id) {
257
        try {
258
            $licence = $this->licence->where('id', $id)->first();
259
260
            $isTaxApply = 0;
261
262
            $taxConditions = $this->CheckTax($isTaxApply);
0 ignored issues
show
Bug introduced by
The call to CheckTax() misses a required argument $id.

This check looks for function calls that miss required arguments.

Loading history...
263
264
            $items = ['id' => $licence->id, 'name' => $licence->name, 'price' => $licence->price, 'quantity' => 1, 'attributes' => ['number_of_sla' => $licence->number_of_sla]];
265
            $items = array_merge($items, $taxConditions);
266
            Cart::clear();
267
            Cart::add($items);
268
269
            return view('themes.default1.front.cart', compact('cartCollection'));
270
        } catch (\Exception $ex) {
271
            dd($ex);
272
            throw new \Exception('Problem while adding licence to cart');
273
        }
274
    }
275
276
    public function cartUpdate($id, $key, $value) {
277
        try {
278
            Cart::update($id, [
279
                $key => $value, // new item name
280
                    ]
281
            );
282
        } catch (\Exception $ex) {
283
            
284
        }
285
    }
286
287
    public function addCurrencyAttributes($id) {
288
        try {
289
            $currency = \Session::get('currency');
290
            $product = $this->product->where('id', $id)->first();
291
            //dd($product);
292
        if ($product) {
293
            $productCurrency = $product->price()->where('currency', $currency)->first()->currency;
294
            $currency = $this->currency->where('code', $productCurrency)->get()->toArray();  
295
        }else{
296
            $currency=[];
297
        }
298
        return $currency; 
299
        } catch (\Exception $ex) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
300
            
301
        }
302
    }
303
304
}
305