Completed
Push — development ( 7008fb...6c67b4 )
by Ashutosh
19:53 queued 09:53
created

TemplateController   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 422
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 43
eloc 260
dl 0
loc 422
rs 8.96
c 0
b 0
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 14 2
A smtpConfig() 0 11 1
A smtp() 0 17 2
A index() 0 6 2
A __construct() 0 41 1
A update() 0 18 2
A edit() 0 16 2
A store() 0 16 2
A destroy() 0 43 5
A getTemplates() 0 21 1
A checkPriceWithTaxClass() 0 19 4
A plans() 0 15 2
A leastAmount() 0 35 5
B mailing() 0 55 7
A leastAmountService() 0 35 5

How to fix   Complexity   

Complex Class

Complex classes like TemplateController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use TemplateController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace App\Http\Controllers\Common;
4
5
use App\Http\Controllers\Product\ProductController;
6
use App\Model\Common\Setting;
7
use App\Model\Common\Template;
8
use App\Model\Common\TemplateType;
9
use App\Model\licence\Licence;
10
use App\Model\Payment\Currency;
11
use App\Model\Payment\Plan;
12
use App\Model\Payment\Tax;
13
use App\Model\Payment\TaxClass;
14
use App\Model\Payment\TaxOption;
15
use App\Model\Payment\TaxProductRelation;
16
use App\Model\Product\Price;
17
use App\Model\Product\Product;
18
use App\Model\Product\Subscription;
19
use Bugsnag;
20
use Config;
21
use Illuminate\Http\Request;
22
23
class TemplateController extends BaseTemplateController
24
{
25
    public $template;
26
    public $type;
27
    public $product;
28
    public $price;
29
    public $subscription;
30
    public $plan;
31
    public $licence;
32
    public $tax_relation;
33
    public $tax;
34
    public $tax_class;
35
    public $tax_rule;
36
    public $currency;
37
38
    public function __construct()
39
    {
40
        $this->middleware('auth', ['except' => ['show']]);
41
        $this->middleware('admin', ['except' => ['show']]);
42
43
        $template = new Template();
44
        $this->template = $template;
45
46
        $type = new TemplateType();
47
        $this->type = $type;
48
49
        $product = new Product();
50
        $this->product = $product;
51
52
        $price = new Price();
53
        $this->price = $price;
54
55
        $subscription = new Subscription();
56
        $this->subscription = $subscription;
57
58
        $plan = new Plan();
59
        $this->plan = $plan;
60
61
        $licence = new Licence();
62
        $this->licence = $licence;
63
64
        $tax_relation = new TaxProductRelation();
65
        $this->tax_relation = $tax_relation;
66
67
        $tax = new Tax();
68
        $this->tax = $tax;
69
70
        $tax_class = new TaxClass();
71
        $this->tax_class = $tax_class;
72
73
        $tax_rule = new TaxOption();
74
        $this->tax_rule = $tax_rule;
75
76
        $currency = new Currency();
77
        $this->currency = $currency;
78
        $this->smtp();
79
    }
80
81
    public function smtp()
82
    {
83
        $settings = new Setting();
84
        $fields = $settings->find(1);
85
        $password = '';
86
        // $name = '';
87
        if ($fields) {
88
            $driver = $fields->driver;
89
            $port = $fields->port;
90
            $host = $fields->host;
91
            $enc = $fields->encryption;
92
            $email = $fields->email;
93
            $password = $fields->password;
94
            $name = $fields->company;
95
        }
96
97
        return $this->smtpConfig($driver, $port, $host, $enc, $email, $password, $name);
98
    }
99
100
    public function smtpConfig($driver, $port, $host, $enc, $email, $password, $name)
101
    {
102
        Config::set('mail.driver', $driver);
103
        Config::set('mail.password', $password);
104
        Config::set('mail.username', $email);
105
        Config::set('mail.encryption', $enc);
106
        Config::set('mail.from', ['address' => $email, 'name' => $name]);
107
        Config::set('mail.port', intval($port));
108
        Config::set('mail.host', $host);
109
110
        return 'success';
111
    }
112
113
    public function index()
114
    {
115
        try {
116
            return view('themes.default1.common.template.inbox');
117
        } catch (\Exception $ex) {
118
            return redirect()->back()->with('fails', $ex->getMessage());
119
        }
120
    }
121
122
    public function getTemplates()
123
    {
124
        return \DataTables::of($this->template->select('id', 'name', 'type')->get())
125
                        ->addColumn('checkbox', function ($model) {
126
                            return "<input type='checkbox' class='template_checkbox' 
127
                            value=".$model->id.' name=select[] id=check>';
128
                        })
129
130
                         ->addColumn('name', function ($model) {
131
                             return $model->name;
132
                         })
133
                        ->addColumn('type', function ($model) {
134
                            return $this->type->where('id', $model->type)->first()->name;
135
                        })
136
                        ->addColumn('action', function ($model) {
137
                            return '<a href='.url('templates/'.$model->id.'/edit').
138
                            " class='btn btn-sm btn-primary btn-xs'><i class='fa fa-edit'
139
                                 style='color:white;'> </i>&nbsp;&nbsp;Edit</a>";
140
                        })
141
                        ->rawColumns(['checkbox', 'name', 'type', 'action'])
142
                        ->make(true);
143
    }
144
145
    public function create()
146
    {
147
        try {
148
            $controller = new ProductController();
149
            $url = $controller->GetMyUrl();
150
            $i = $this->template->orderBy('created_at', 'desc')->first()->id + 1;
151
            $cartUrl = $url.'/'.$i;
152
            $type = $this->type->pluck('name', 'id')->toArray();
153
154
            return view('themes.default1.common.template.create', compact('type', 'cartUrl'));
155
        } catch (\Exception $ex) {
156
            Bugsnag::notifyException($ex);
157
158
            return redirect()->back()->with('fails', $ex->getMessage());
159
        }
160
    }
161
162
    public function store(Request $request)
163
    {
164
        $this->validate($request, [
165
            'name' => 'required',
166
            'data' => 'required',
167
            'type' => 'required',
168
        ]);
169
170
        try {
171
            $this->template->fill($request->input())->save();
172
173
            return redirect()->back()->with('success', \Lang::get('message.saved-successfully'));
174
        } catch (\Exception $ex) {
175
            Bugsnag::notifyException($ex);
176
177
            return redirect()->back()->with('fails', $ex->getMessage());
178
        }
179
    }
180
181
    public function edit($id)
182
    {
183
        try {
184
            $controller = new ProductController();
185
            $url = $controller->GetMyUrl();
186
187
            $i = $this->template->orderBy('created_at', 'desc')->first()->id + 1;
188
            $cartUrl = $url.'/'.$i;
189
            $template = $this->template->where('id', $id)->first();
190
            $type = $this->type->pluck('name', 'id')->toArray();
191
192
            return view('themes.default1.common.template.edit', compact('type', 'template', 'cartUrl'));
193
        } catch (\Exception $ex) {
194
            Bugsnag::notifyException($ex);
195
196
            return redirect()->back()->with('fails', $ex->getMessage());
197
        }
198
    }
199
200
    public function update($id, Request $request)
201
    {
202
        $this->validate($request, [
203
            'name' => 'required',
204
            'data' => 'required',
205
            'type' => 'required',
206
        ]);
207
208
        try {
209
            //dd($request);
210
            $template = $this->template->where('id', $id)->first();
211
            $template->fill($request->input())->save();
212
213
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
214
        } catch (\Exception $ex) {
215
            Bugsnag::notifyException($ex);
216
217
            return redirect()->back()->with('fails', $ex->getMessage());
218
        }
219
    }
220
221
    /**
222
     * Remove the specified resource from storage.
223
     *
224
     * @param int $id
225
     *
226
     * @return \Response
227
     */
228
    public function destroy(Request $request)
229
    {
230
        try {
231
            $ids = $request->input('select');
232
            if (!empty($ids)) {
233
                foreach ($ids as $id) {
234
                    $template = $this->template->where('id', $id)->first();
235
                    if ($template) {
236
                        $template->delete();
237
                    } else {
238
                        echo "<div class='alert alert-danger alert-dismissable'>
239
                    <i class='fa fa-ban'></i>
240
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
241
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
242
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
243
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
244
                </div>';
245
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
246
                    }
247
                }
248
                echo "<div class='alert alert-success alert-dismissable'>
249
                    <i class='fa fa-ban'></i>
250
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').
251
                    '!</b> './* @scrutinizer ignore-type */\Lang::get('message.success').'
252
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
253
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
254
                </div>';
255
            } else {
256
                echo "<div class='alert alert-danger alert-dismissable'>
257
                    <i class='fa fa-ban'></i>
258
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
259
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
260
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
261
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
262
                </div>';
263
            }
264
        } catch (\Exception $e) {
265
            echo "<div class='alert alert-danger alert-dismissable'>
266
                    <i class='fa fa-ban'></i>
267
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
268
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
269
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
270
                        '.$e->getMessage().'
271
                </div>';
272
        }
273
    }
274
275
    public function mailing($from, $to, $data, $subject, $replace = [],
276
     $type = '', $fromname = '', $toname = '', $cc = [], $attach = [])
277
    {
278
        try {
279
            $transform = [];
280
            $page_controller = new \App\Http\Controllers\Front\PageController();
281
            $transform[0] = $replace;
282
            $data = $page_controller->transform($type, $data, $transform);
283
284
            $settings = \App\Model\Common\Setting::find(1);
285
            $fromname = $settings->company;
286
            \Mail::send('emails.mail', ['data' => $data], function ($m) use ($from, $to, $subject, $fromname, $toname, $cc, $attach) {
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 134 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
287
                $m->from($from, $fromname);
288
289
                $m->to($to, $toname)->subject($subject);
290
291
                /* if cc is need  */
292
                if (!empty($cc)) {
293
                    foreach ($cc as $address) {
294
                        $m->cc($address['address'], $address['name']);
295
                    }
296
                }
297
298
                /*  if attachment is need */
299
                if (!empty($attach)) {
300
                    foreach ($attach as $file) {
301
                        $m->attach($file['path'], $options = []);
302
                    }
303
                }
304
            });
305
            \DB::table('email_log')->insert([
306
                'date' => date('Y-m-d H:i:s'),
307
            'from'     => $from,
308
            'to'       => $to,
309
             'subject' => $subject,
310
            'body'     => $data,
311
          'status'     => 'success',
312
          ]);
313
314
            return 'success';
315
        } catch (\Exception $ex) {
316
            \DB::table('email_log')->insert([
317
            'date'     => date('Y-m-d H:i:s'),
318
            'from'     => $from,
319
            'to'       => $to,
320
             'subject' => $subject,
321
            'body'     => $data,
322
            'status'   => 'failed',
323
        ]);
324
            Bugsnag::notifyException($ex);
325
            if ($ex instanceof \Swift_TransportException) {
326
                throw new \Exception('We can not reach to this email address');
327
            }
328
329
            throw new \Exception('mailing problem');
330
        }
331
    }
332
333
    public function checkPriceWithTaxClass($productid, $currency)
334
    {
335
        try {
336
            $product = $this->product->findOrFail($productid);
337
            // dd($product);
338
            if ($product->tax_apply == 1) {
339
                $price = $this->checkTax($product->id, $currency);
340
            } else {
341
                $price = $product->price()->where('currency', $currency)->first()->sales_price;
342
                if (!$price) {
343
                    $price = $product->price()->where('currency', $currency)->first()->price;
344
                }
345
            }
346
347
            return $price;
348
        } catch (\Exception $ex) {
349
            Bugsnag::notifyException($ex);
350
351
            throw new \Exception($ex->getMessage());
352
        }
353
    }
354
355
    public function plans($url, $id)
356
    {
357
        $plan = new Plan();
358
        $plan_form = 'Free'; //No Subscription
359
        $plans = $plan->where('product', '=', $id)->pluck('name', 'id')->toArray();
360
        $plans = $this->prices($id);
361
        // $planName = Plan::where()
362
        if ($plans) {
363
            $plan_form = \Form::select('subscription', ['Plans' => $plans], null);
364
        }
365
        $form = \Form::open(['method' => 'get', 'url' => $url]).
366
        $plan_form.
367
        \Form::hidden('id', $id);
368
369
        return $form;
370
    }
371
372
    public function leastAmount($id)
373
    {
374
        try {
375
            $cost = 'Free';
376
            $symbol = '';
377
            $price = '';
378
            $plan = new Plan();
379
            $plans = $plan->where('product', $id)->get();
380
            $cart_controller = new \App\Http\Controllers\Front\CartController();
381
            $currencyAndSymbol = $cart_controller->currency();
382
            $currency = $currencyAndSymbol['currency'];
383
            $symbol = $currencyAndSymbol['symbol'];
384
            $prices = [];
385
            $priceVal[] = [];
0 ignored issues
show
Comprehensibility Best Practice introduced by
$priceVal was never initialized. Although not strictly required by PHP, it is generally a good practice to add $priceVal = array(); before regardless.
Loading history...
386
            if ($plans->count() > 0) {
387
                foreach ($plans as $value) {
388
                    $days = $value->min('days');
389
                    $month = round($days / 30);
390
                    $prices[] = $value->planPrice()->where('currency', $currency)->min('add_price');
391
                }
392
                foreach ($prices as $key => $value) {
393
                    $duration = $this->getDuration($value);
394
                    $priceVal[] = intval($value);
395
                }
396
                $price = min($priceVal).' '.$duration;
397
                $cost = "$symbol$price";
398
            } else {
399
                $cost = 'Free';
400
            }
401
402
            return $cost;
403
        } catch (\Exception $ex) {
404
            Bugsnag::notifyException($ex);
405
406
            return redirect()->back()->with('fails', $ex->getMessage());
407
        }
408
    }
409
410
    public function leastAmountService($id)
411
    {
412
        try {
413
            $cost = 'Free';
414
            $symbol = '';
415
            $price = '';
416
            $plan = new Plan();
417
            $plans = $plan->where('product', $id)->get();
418
            $cart_controller = new \App\Http\Controllers\Front\CartController();
419
            $currencyAndSymbol = $cart_controller->currency();
420
            $currency = $currencyAndSymbol['currency'];
421
            $symbol = $currencyAndSymbol['symbol'];
422
            $prices = [];
423
            $priceVal[] = [];
0 ignored issues
show
Comprehensibility Best Practice introduced by
$priceVal was never initialized. Although not strictly required by PHP, it is generally a good practice to add $priceVal = array(); before regardless.
Loading history...
424
            if ($plans->count() > 0) {
425
                foreach ($plans as $value) {
426
                    $days = $value->min('days');
427
                    $month = round($days / 30);
428
                    $prices[] = $value->planPrice()->where('currency', $currency)->min('add_price');
429
                }
430
                foreach ($prices as $key => $value) {
431
                    $duration = $this->getDuration($value);
432
                    $priceVal[] = intval($value);
433
                }
434
                $price = min($priceVal).' '.$duration;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $duration seems to be defined by a foreach iteration on line 430. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
435
                $cost = "$symbol$price";
436
            } else {
437
                $cost = 'Free';
438
            }
439
440
            return $cost;
441
        } catch (\Exception $ex) {
442
            Bugsnag::notifyException($ex);
443
444
            return redirect()->back()->with('fails', $ex->getMessage());
445
        }
446
    }
447
}
448