Completed
Push — development ( c6edbc...615590 )
by Ashutosh
09:59
created

ProductController::update()   B

Complexity

Conditions 6
Paths 61

Size

Total Lines 52
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 34
dl 0
loc 52
rs 8.7537
c 0
b 0
f 0
cc 6
nc 61
nop 2

How to fix   Long Method   

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
namespace App\Http\Controllers\Product;
4
5
// use Illuminate\Http\Request;
6
    use App\Model\Order\Order;
7
    use App\Model\Payment\Currency;
8
    use App\Model\Payment\Period;
9
    use App\Model\Payment\Plan;
10
    use App\Model\Payment\Tax;
11
    use App\Model\Payment\TaxClass;
12
    use App\Model\Payment\TaxProductRelation;
13
    use App\Model\Product\Price;
14
    use App\Model\Product\Product;
15
    use App\Model\Product\ProductGroup;
16
    use App\Model\Product\ProductUpload;
17
    use App\Model\Product\Subscription;
18
    use App\Model\Product\Type;
19
    use Bugsnag\BugsnagLaravel\Facades\Bugsnag;
20
    use Illuminate\Http\Request;
21
    use Illuminate\Support\Facades\Input;
22
    use Spatie\Activitylog\Models\Activity;
23
24
    // use Input;
25
26
    class ProductController extends BaseProductController
27
    {
28
        public $product;
29
        public $price;
30
        public $type;
31
        public $subscription;
32
        public $currency;
33
        public $group;
34
        public $plan;
35
        public $tax;
36
        public $tax_relation;
37
        public $tax_class;
38
        public $product_upload;
39
40
        public function __construct()
41
        {
42
            $this->middleware('auth');
43
            $this->middleware('admin', ['except' => ['adminDownload', 'userDownload']]);
44
45
            $product = new Product();
46
            $this->product = $product;
47
48
            $price = new Price();
49
            $this->price = $price;
50
51
            $type = new Type();
52
            $this->type = $type;
53
54
            $subscription = new Subscription();
55
            $this->subscription = $subscription;
56
57
            $currency = new Currency();
58
            $this->currency = $currency;
59
60
            $group = new ProductGroup();
61
            $this->group = $group;
62
63
            $plan = new Plan();
64
            $this->plan = $plan;
65
66
            $tax = new Tax();
67
            $this->tax = $tax;
68
69
            $period = new Period();
70
            $this->period = $period;
71
72
            $tax_relation = new TaxProductRelation();
73
            $this->tax_relation = $tax_relation;
74
75
            $tax_class = new TaxClass();
76
            $this->tax_class = $tax_class;
77
78
            $product_upload = new ProductUpload();
79
            $this->product_upload = $product_upload;
80
        }
81
82
        /**
83
         * Display a listing of the resource.
84
         *
85
         * @return \Response
86
         */
87
        public function index()
88
        {
89
            try {
90
                return view('themes.default1.product.product.index');
91
            } catch (\Exception $e) {
92
                Bugsnag::notifyException($e);
93
94
                return redirect('/')->with('fails', $e->getMessage());
95
            }
96
        }
97
98
        /**
99
         * Display a listing of the resource.
100
         *
101
         * @return \Response
102
         */
103
        public function getProducts()
104
        {
105
            try {
106
                $new_product = Product::select('id', 'name', 'type', 'group')->get();
107
108
                return\ DataTables::of($new_product)
109
            // return \Datatable::collection($this->product->select('id', 'name', 'type', 'group')->where('id', '!=', 1)->get())
110
                            ->addColumn('checkbox', function ($model) {
111
                                return "<input type='checkbox' class='product_checkbox' value=".$model->id.' name=select[] id=check>';
112
                            })
113
                            ->addColumn('name', function ($model) {
114
                                return ucfirst($model->name);
115
                            })
116
                            ->addColumn('type', function ($model) {
117
                                //dd($model->type());
118
                                if ($this->type->where('id', $model->type)->first()) {
119
                                    return $this->type->where('id', $model->type)->first()->name;
120
                                } else {
121
                                    return 'Not available';
122
                                }
123
                            })
124
                            ->addColumn('group', function ($model) {
125
                                //dd($model->type());
126
                                if ($this->group->where('id', $model->group)->first()) {
127
                                    return $this->group->where('id', $model->group)->first()->name;
128
                                } else {
129
                                    return 'Not available';
130
                                }
131
                            })
132
                            ->addColumn('price', function ($model) {
133
                                if ($this->price->where('product_id', $model->id)->first()) {
134
                                    return $this->price->where('product_id', $model->id)->first()->price;
135
                                } else {
136
                                    return 'Not available';
137
                                }
138
                            })
139
                            ->addColumn('currency', function ($model) {
140
                                if ($this->price->where('product_id', $model->id)->first()) {
141
                                    return $this->price->where('product_id', $model->id)->first()->currency;
142
                                } else {
143
                                    return 'Not available';
144
                                }
145
                            })
146
                            ->addColumn('Action', function ($model) {
147
                                $url = '';
148
                                if ($model->type == 2) {
149
                                    $url = '<a href='.url('product/download/'.$model->id)." class='btn btn-sm btn-primary btn-xs'><i class='fa fa-download' style='color:white;'> </i>&nbsp;&nbsp;Download</a>";
150
                                }
151
152
                                return '<p><a href='.url('products/'.$model->id.'/edit')." class='btn btn-sm btn-primary btn-xs'><i class='fa fa-edit' style='color:white;'> </i>&nbsp;&nbsp;Edit</a>&nbsp;$url</p>";
153
                            })
154
155
                            ->rawColumns(['checkbox', 'name', 'type', 'group', 'price', 'currency', 'Action'])
156
                            ->make(true);
157
            } catch (\Exception $e) {
158
                Bugsnag::notifyException($e);
159
160
                return redirect()->back()->with('fails', $e->getMessage());
161
            }
162
        }
163
164
        public function getUpload($id)
165
        {
166
            $new_upload = ProductUpload::where('product_id', '=', $id)->select('id', 'product_id', 'title', 'description', 'version', 'file')->get();
167
168
            return \DataTables::of($new_upload)
169
        ->addColumn('checkbox', function ($model) {
170
            return "<input type='checkbox' class='upload_checkbox' value=".$model->id.' name=select[] id=checks>';
171
        })
172
173
        ->addColumn('product_id', function ($model) {
174
            return ucfirst($this->product->where('id', $model->product_id)->first()->name);
175
        })
176
177
        ->addColumn('title', function ($model) {
178
            return ucfirst($model->title);
179
        })
180
        ->addColumn('description', function ($model) {
181
            return ucfirst($model->description);
182
        })
183
        ->addColumn('version', function ($model) {
184
            return $model->version;
185
        })
186
187
        ->addColumn('file', function ($model) {
188
            return $model->file;
189
        })
190
        ->addColumn('action', function ($model) {
191
            return '<a href='.('#edit-upload-option/'.$model->id).'  class=" btn btn-sm btn-primary " data-title="'.$model->title.'" data-description="'.$model->description.'" data-version="'.$model->version.'" data-id="'.$model->id.'" onclick="openEditPopup(this)" >Edit</a>';
192
        })
193
        ->rawcolumns(['checkbox', 'product_id', 'title', 'description', 'version', 'file', 'action'])
194
        ->make(true);
195
        }
196
197
        // Save file Info in Modal popup
198
        public function save(Request $request)
199
        {
200
            try {
201
                $product_id = Product::where('name', '=', $request->input('product'))->select('id')->first();
202
203
                $this->product_upload->product_id = $product_id->id;
204
                $this->product_upload->title = $request->input('title');
205
                $this->product_upload->description = $request->input('description');
206
                $this->product_upload->version = $request->input('version');
207
208
                if ($request->file) {
209
                    $file = $request->file('file')->getClientOriginalName();
210
211
                    $destination = storage_path().'/products';
212
                    $request->file('file')->move($destination, $file);
213
                    $this->product_upload->file = $file;
214
                }
215
                $this->product_upload->save();
216
217
                return redirect()->back()->with('success', \Lang::get('message.saved-successfully'));
218
            } catch (\Exception $e) {
219
                Bugsnag::notifyException($e);
220
221
                return redirect()->with('fails', $e->getMessage());
222
            }
223
        }
224
225
        //Update the File Info
226
        public function uploadUpdate($id, Request $request)
227
        {
228
            $file_upload = ProductUpload::find($id);
229
230
            $file_upload->title = $request->input('title');
231
            $file_upload->description = $request->input('description');
232
            $file_upload->version = $request->input('version');
233
            if ($request->file) {
234
                $file = $request->file('file')->getClientOriginalName();
235
236
                $destination = storage_path().'/products';
237
                $request->file('file')->move($destination, $file);
238
                $file_upload->file = $file;
239
            }
240
            $file_upload->save();
241
242
            return redirect()->back()->with('success', \Lang::get('message.saved-successfully'));
243
        }
244
245
        /**
246
         * Show the form for creating a new resource.
247
         *
248
         * @return \Response
249
         */
250
        public function create()
251
        {
252
            try {
253
                /*
254
                 * server url
255
                 */
256
                $url = $this->GetMyUrl();
257
                $i = $this->product->orderBy('created_at', 'desc')->first()->id + 1;
258
                $cartUrl = $url.'/pricing?id='.$i;
259
                $type = $this->type->pluck('name', 'id')->toArray();
260
                $subscription = $this->plan->pluck('name', 'id')->toArray();
261
                $currency = $this->currency->pluck('name', 'code')->toArray();
262
                $group = $this->group->pluck('name', 'id')->toArray();
263
                $products = $this->product->pluck('name', 'id')->toArray();
264
                $periods = $this->period->pluck('name', 'days')->toArray();
265
                $taxes = $this->tax_class->pluck('name', 'id')->toArray();
266
267
                return view('themes.default1.product.product.create', compact('subscription', 'type', 'periods', 'currency', 'group', 'cartUrl', 'products', 'taxes'));
268
            } catch (\Exception $e) {
269
                Bugsnag::notifyException($e);
270
271
                return redirect()->back()->with('fails', $e->getMessage());
272
            }
273
        }
274
275
        /**
276
         * Store a newly created resource in storage.
277
         *
278
         * @return \Response
279
         */
280
        public function store(Request $request)
281
        {
282
            $input = $request->all();
283
            // dd($input);
284
            $v = \Validator::make($input, [
285
                        'name'    => 'required|unique:products,name',
286
                        'type'    => 'required',
287
                        'group'   => 'required',
288
                        // 'image'   => 'sometimes | mimes:jpeg,jpg,png,gif | max:1000',
289
                        // 'version' => 'required',
290
            ]);
291
            if ($v->fails()) {
292
                //     $currency = $input['currency'];
293
294
                return redirect()->back()
295
                        ->withErrors($v)
296
                        ->withInput()
297
                        ->with('currency');
298
            }
299
300
            try {
301
                if ($request->hasFile('image')) {
302
                    $image = $request->file('image')->getClientOriginalName();
303
                    $imagedestinationPath = 'dist/product/images';
304
                    $request->file('image')->move($imagedestinationPath, $image);
305
                    $this->product->image = $image;
306
                }
307
308
                $product = $this->product;
309
                $product->fill($request->except('image', 'file'))->save();
310
                // Product::where('id',$product->id)->update(['name'=>$request->names]);
311
312
                $product_id = $product->id;
313
                $subscription = $request->input('subscription');
314
315
                $price = $request->input('price');
316
                // $price=
317
318
                $sales_price = $request->input('sales_price');
319
                $currencies = $request->input('currency');
320
                $taxes = $request->input('tax');
321
                if ($taxes) {
322
                    foreach ($taxes as $key=>$value) {
323
                        $newtax = new TaxProductRelation();
324
                        $newtax->product_id = $product_id;
325
                        $newtax->tax_class_id = $value;
326
                        $newtax->save();
327
                    }
328
                }
329
330
                return redirect()->back()->with('success', \Lang::get('message.saved-successfully'));
331
            } catch (\Exception $e) {
332
                Bugsnag::notifyException($e);
333
334
                return redirect()->with('fails', $e->getMessage());
335
            }
336
        }
337
338
        /**
339
         * Show the form for editing the specified resource.
340
         *
341
         * @param int $id
342
         *
343
         * @return \Response
344
         */
345
        public function edit($id)
346
        {
347
            try {
348
                $type = $this->type->pluck('name', 'id')->toArray();
349
350
                $subscription = $this->plan->pluck('name', 'id')->toArray();
351
                $currency = $this->currency->pluck('name', 'code')->toArray();
352
                $group = $this->group->pluck('name', 'id')->toArray();
353
                $products = $this->product->pluck('name', 'id')->toArray();
354
                $periods = $this->period->pluck('name', 'days')->toArray();
355
                $url = $this->GetMyUrl();
356
                $cartUrl = $url.'/cart?id='.$id;
357
                $product = $this->product->where('id', $id)->first();
358
                $price = $this->price->where('product_id', $product->id);
359
                foreach ($currency as $key => $value) {
360
                    if ($this->price->where('product_id', $product->id)->where('currency', $key)->first()) {
361
                        $regular[$key] = $this->price->where('product_id', $product->id)->where('currency', $key)->first()->price;
362
                        $sales[$key] = $this->price->where('product_id', $product->id)->where('currency', $key)->first()->sales_price;
363
                    } else {
364
                        $regular[$key] = '';
365
                        $sales[$key] = '';
366
                    }
367
                }
368
369
                $taxes = $this->tax_class->pluck('name', 'id')->toArray();
370
                // dd($taxes);
371
                $saved_taxes = $this->tax_relation->where('product_id', $id)->get();
372
                $savedTaxes = $this->tax_relation->where('product_id', $id)->pluck('tax_class_id')->toArray();
373
374
                return view('themes.default1.product.product.edit', compact('product', 'periods', 'type', 'subscription', 'currency', 'group', 'price', 'cartUrl', 'products', 'regular', 'sales', 'taxes', 'saved_taxes', 'savedTaxes'));
375
            } catch (\Exception $e) {
376
                Bugsnag::notifyException($e);
377
378
                return redirect()->back()->with('fails', $e->getMessage());
379
            }
380
        }
381
382
        /**
383
         * Update the specified resource in storage.
384
         *
385
         * @param int $id
386
         *
387
         * @return \Response
388
         */
389
        public function update($id, Request $request)
390
        {
391
            $input = $request->all();
392
            $v = \Validator::make($input, [
393
                        'name'    => 'required',
394
                        'type'    => 'required',
395
                        'group'   => 'required',
396
                        'image'   => 'sometimes | mimes:jpeg,jpg,png,gif | max:1000',
397
    //                    'subscription' => 'required',
398
    //                    'currency.*' => 'required',
399
    //                    'price.*' => 'required',
400
            ]);
401
402
            if ($v->fails()) {
403
                return redirect()->back()->with('errors', $v->errors());
404
            }
405
406
            try {
407
                $product = $this->product->where('id', $id)->first();
408
                if ($request->hasFile('image')) {
409
                    $image = $request->file('image')->getClientOriginalName();
410
                    $imagedestinationPath = 'dist/product/images';
411
                    $request->file('image')->move($imagedestinationPath, $image);
412
                    $product->image = $image;
413
                }
414
                if ($request->hasFile('file')) {
415
                    $file = $request->file('file')->getClientOriginalName();
416
                    $filedestinationPath = storage_path().'/products';
417
                    $request->file('file')->move($filedestinationPath, $file);
418
                    $product->file = $file;
419
                }
420
                $product->fill($request->except('image', 'file'))->save();
421
                $this->updateVersionFromGithub($product->id);
422
423
                $product_id = $product->id;
424
                $subscription = $request->input('subscription');
425
                $cost = $request->input('price');
426
                $sales_price = $request->input('sales_price');
427
                $currencies = $request->input('currency');
428
            
429
                //add tax class to tax_product_relation table
430
                $taxes = $request->input('tax');
431
                if ($taxes) {
432
                    $saveTax = $this->saveTax($taxes,$product_id);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $saveTax is correct as $this->saveTax($taxes, $product_id) targeting App\Http\Controllers\Pro...ctController::saveTax() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
433
                    }
434
                
435
436
                return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
437
            } catch (\Exception $e) {
438
                Bugsnag::notifyException($e);
439
440
                return redirect()->back()->with('fails', $e->getMessage());
441
            }
442
        }
443
444
        public function saveTax($taxes,$product_id)
445
        {
446
        $this->tax_relation->where('product_id', $product_id)->delete();
447
        foreach ($taxes as $tax) {
448
            $newTax = new TaxProductRelation();
449
            $newTax->product_id = $product_id;
450
            $newTax->tax_class_id = $tax;
451
            $newTax->save();
452
            }
453
        }
454
455
        /**
456
         * Remove the specified resource from storage.
457
         *
458
         * @param int $id
459
         *
460
         * @return \Response
461
         */
462
        public function destroy(Request $request)
463
        {
464
            try {
465
                $ids = $request->input('select');
466
                if (!empty($ids)) {
467
                    foreach ($ids as $id) {
468
                        if ($id != 1) {
469
                            $product = $this->product->where('id', $id)->first();
470
                            if ($product) {
471
                                $product->delete();
472
                            } else {
473
                                echo "<div class='alert alert-danger alert-dismissable'>
474
                    <i class='fa fa-ban'></i>
475
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
476
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
477
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
478
                </div>';
479
                                //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
480
                            }
481
                            echo "<div class='alert alert-success alert-dismissable'>
482
                    <i class='fa fa-ban'></i>
483
                    <b>"./* @scrutinizer ignore-type */
484
                    \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */ \Lang::get('message.success').'
485
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
486
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
487
                </div>';
488
                        } else {
489
                            echo "<div class='alert alert-danger alert-dismissable'>
490
                    <i class='fa fa-ban'></i>
491
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
492
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
493
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
494
                        './* @scrutinizer ignore-type */ \Lang::get('message.can-not-delete-default').'
495
                </div>';
496
                        }
497
                    }
498
                } else {
499
                    echo "<div class='alert alert-danger alert-dismissable'>
500
                    <i class='fa fa-ban'></i>
501
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
502
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
503
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
504
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
505
                </div>';
506
                    //echo \Lang::get('message.select-a-row');
507
                }
508
                $lastActivity = Activity::all()->last();
509
            } catch (\Exception $e) {
510
                echo "<div class='alert alert-danger alert-dismissable'>
511
                    <i class='fa fa-ban'></i>
512
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
513
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
514
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
515
                        '.$e->getMessage().'
516
                </div>';
517
            }
518
        }
519
520
        /*
521
        *  Download Files from Filesystem/Github
522
        */
523
        public function downloadProduct($uploadid, $id, $invoice_id, $version_id = '')
524
        {
525
            try {
526
                $product = $this->product->findOrFail($uploadid);
527
                $type = $product->type;
528
                $owner = $product->github_owner;
529
                $repository = $product->github_repository;
530
                $file = $this->product_upload->where('product_id', '=', $uploadid)->where('id', $version_id)->select('file')->first();
531
                $order = Order::where('invoice_id', '=', $invoice_id)->first();
532
                $order_id = $order->id;
533
                if ($type == 2) {
534
                    $relese = $this->getRelease($owner, $repository, $order_id, $file);
535
536
                    return $relese;
537
                }
538
            } catch (\Exception $e) {
539
                Bugsnag::notifyException($e);
540
541
                return redirect()->back()->with('fails', $e->getMessage());
542
            }
543
        }
544
545
        public function adminDownload($id, $invoice = '', $api = false)
546
        {
547
            try {
548
                $role = \Auth::user()->role;
549
                $release = $this->getLinkToDownload($role, $invoice, $id);
550
551
                if (is_array($release) && array_key_exists('type', $release)) {
552
                    header('Location: '.$release['release']);
553
                    exit;
554
                } else {
555
                    header('Content-type: Zip');
556
                    header('Content-Description: File Transfer');
557
                    header('Content-Disposition: attachment; filename=Faveo.zip');
558
                    header('Content-Length: '.filesize($release));
559
                    flush();
560
                    readfile("$release");
561
                }
562
            } catch (\Exception $e) {
563
                if ($api) {
564
                    return response()->json(['error'=>$e->getMessage()]);
565
                }
566
                Bugsnag::notifyException($e);
567
568
                return redirect()->back()->with('fails', $e->getMessage());
569
            }
570
        }
571
572
        public function getProductField($productid)
573
        {
574
            try {
575
                $field = '';
576
                $product = $this->product->find($productid);
577
                if ($product) {
578
                    if ($product->require_domain == 1) {
579
                        $field .= "<div class='col-md-4 form-group'>
580
                            <label class='required'>"./* @scrutinizer ignore-type */ \Lang::get('message.domain')."</label>
581
                            <input type='text' name='domain' class='form-control' id='domain' placeholder='http://example.com'>
582
                    </div>";
583
                    }
584
                }
585
586
                return $field;
587
            } catch (\Exception $ex) {
588
                Bugsnag::notifyException($ex);
589
590
                return $ex->getMessage();
591
            }
592
        }
593
594
        public function getSubscriptionCheckScript()
595
        {
596
            $response = "<script>
597
        function getPrice(val) {
598
            var user = document.getElementsByName('user')[0].value;
599
            var plan = '';
600
            if ($('#plan').length > 0) {
601
                var plan = document.getElementsByName('plan')[0].value;
602
            }
603
            //var plan = document.getElementsByName('plan')[0].value;
604
            //alert(user);
605
606
            $.ajax({
607
                type: 'POST',
608
                url: ".url('get-price').",
609
                data: {'product': val, 'user': user,'plan':plan},
610
                //data: 'product=' + val+'user='+user,
611
                success: function (data) {
612
                    var price = data['price'];
613
                    var field = data['field'];
614
                    $('#price').val(price);
615
                    $('#fields').append(field);
616
                }
617
            });
618
        }
619
620
    </script>";
621
        }
622
    }
623