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

TemplateController   B

Complexity

Total Complexity 47

Size/Duplication

Total Lines 350
Duplicated Lines 17.14 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 47
c 3
b 1
f 0
lcom 1
cbo 13
dl 60
loc 350
rs 8.439

12 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 25 1
A index() 0 7 2
A GetTemplates() 0 16 1
A create() 0 13 2
A store() 9 10 2
A edit() 0 16 2
A update() 10 11 2
B destroy() 41 41 5
F Mailing() 0 64 17
B mailtest() 0 33 2
C show() 0 51 7
B popup() 0 33 4

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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\Controller;
6
use App\Http\Controllers\Product\ProductController;
7
use App\Model\Common\Template;
8
use App\Model\Common\TemplateType;
9
use App\Model\licence\Licence;
10
use App\Model\Payment\Plan;
11
use App\Model\Product\Price;
12
use App\Model\Product\Product;
13
use App\Model\Product\Subscription;
14
use Illuminate\Http\Request;
15
16
class TemplateController extends Controller {
17
18
    public $template;
19
    public $type;
20
    public $product;
21
    public $price;
22
    public $subscription;
23
    public $plan;
24
    public $licence;
25
26
    public function __construct() {
27
        $this->middleware('auth', ['except' => ['show']]);
28
        $this->middleware('admin', ['except' => ['show']]);
29
30
        $template = new Template();
31
        $this->template = $template;
32
33
        $type = new TemplateType();
34
        $this->type = $type;
35
36
        $product = new Product();
37
        $this->product = $product;
38
39
        $price = new Price();
40
        $this->price = $price;
41
42
        $subscription = new Subscription();
43
        $this->subscription = $subscription;
44
45
        $plan = new Plan();
46
        $this->plan = $plan;
47
48
        $licence = new Licence();
49
        $this->licence = $licence;
50
    }
51
52
    public function index() {
53
        try {
54
            return view('themes.default1.common.template.inbox');
55
        } catch (\Exception $ex) {
56
            return redirect()->back()->with('fails', $ex->getMessage());
57
        }
58
    }
59
60
    public function GetTemplates() {
61
        return \Datatable::collection($this->template->select('id', 'name', 'type')->get())
62
                        ->addColumn('#', function ($model) {
63
                            return "<input type='checkbox' value=" . $model->id . ' name=select[] id=check>';
64
                        })
65
                        ->showColumns('name')
66
                        ->addColumn('type', function ($model) {
67
                            return $this->type->where('id', $model->type)->first()->name;
68
                        })
69
                        ->addColumn('action', function ($model) {
70
                            return '<a href=' . url('templates/' . $model->id . '/edit') . " class='btn btn-sm btn-primary'>Edit</a>";
71
                        })
72
                        ->searchColumns('name')
73
                        ->orderColumns('name')
74
                        ->make();
75
    }
76
77
    public function create() {
78
        try {
79
            $controller = new ProductController();
80
            $url = $controller->GetMyUrl();
81
            $i = $this->template->orderBy('created_at', 'desc')->first()->id + 1;
82
            $cartUrl = $url . '/' . $i;
83
            $type = $this->type->lists('name', 'id')->toArray();
84
85
            return view('themes.default1.common.template.create', compact('type', 'cartUrl'));
86
        } catch (\Exception $ex) {
87
            return redirect()->back()->with('fails', $ex->getMessage());
88
        }
89
    }
90
91 View Code Duplication
    public function store(Request $request) {
92
        try {
93
            //dd($request);
94
            $this->template->fill($request->input())->save();
0 ignored issues
show
Bug introduced by
It seems like $request->input() targeting Illuminate\Http\Request::input() can also be of type string; however, Illuminate\Database\Eloquent\Model::fill() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
95
96
            return redirect()->back()->with('success', \Lang::get('message.saved-successfully'));
97
        } catch (\Exception $ex) {
98
            return redirect()->back()->with('fails', $ex->getMessage());
99
        }
100
    }
101
102
    public function edit($id) {
103
        try {
104
            $controller = new ProductController();
105
            $url = $controller->GetMyUrl();
106
107
            $i = $this->template->orderBy('created_at', 'desc')->first()->id + 1;
108
            $cartUrl = $url . '/' . $i;
109
            //dd($cartUrl);
110
            $template = $this->template->where('id', $id)->first();
111
            $type = $this->type->lists('name', 'id')->toArray();
112
113
            return view('themes.default1.common.template.edit', compact('type', 'template', 'cartUrl'));
114
        } catch (\Exception $ex) {
115
            return redirect()->back()->with('fails', $ex->getMessage());
116
        }
117
    }
118
119 View Code Duplication
    public function update($id, Request $request) {
120
        try {
121
            //dd($request);
122
            $template = $this->template->where('id', $id)->first();
123
            $template->fill($request->input())->save();
124
125
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
126
        } catch (\Exception $ex) {
127
            return redirect()->back()->with('fails', $ex->getMessage());
128
        }
129
    }
130
131
    /**
132
     * Remove the specified resource from storage.
133
     *
134
     * @param int $id
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...
135
     *
136
     * @return Response
137
     */
138 View Code Duplication
    public function destroy(Request $request) {
139
        try {
140
            $ids = $request->input('select');
141
            if (!empty($ids)) {
142
                foreach ($ids as $id) {
0 ignored issues
show
Bug introduced by
The expression $ids of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
143
                    $template = $this->template->where('id', $id)->first();
144
                    if ($template) {
145
                        $template->delete();
146
                    } else {
147
                        echo "<div class='alert alert-danger alert-dismissable'>
148
                    <i class='fa fa-ban'></i>
149
                    <b>" . \Lang::get('message.alert') . '!</b> ' . \Lang::get('message.failed') . '
150
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
151
                        ' . \Lang::get('message.no-record') . '
152
                </div>';
153
//echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
154
                    }
155
                }
156
                echo "<div class='alert alert-success alert-dismissable'>
157
                    <i class='fa fa-ban'></i>
158
                    <b>" . \Lang::get('message.alert') . '!</b> ' . \Lang::get('message.success') . '
159
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
160
                        ' . \Lang::get('message.deleted-successfully') . '
161
                </div>';
162
            } else {
163
                echo "<div class='alert alert-danger alert-dismissable'>
164
                    <i class='fa fa-ban'></i>
165
                    <b>" . \Lang::get('message.alert') . '!</b> ' . \Lang::get('message.failed') . '
166
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
167
                        ' . \Lang::get('message.select-a-row') . '
168
                </div>';
169
            }
170
        } catch (\Exception $e) {
171
            echo "<div class='alert alert-danger alert-dismissable'>
172
                    <i class='fa fa-ban'></i>
173
                    <b>" . \Lang::get('message.alert') . '!</b> ' . \Lang::get('message.failed') . '
174
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
175
                        ' . $e->getMessage() . '
176
                </div>';
177
        }
178
    }
179
180
    public function Mailing($from, $to, $data, $subject, $replace = [], $fromname = '', $toname = '', $cc = [], $attach = []) {
181
        try {
182
            if (!array_key_exists('title', $replace)) {
183
                $replace['title'] = '';
184
            }
185
            if (!array_key_exists('currency', $replace)) {
186
                $replace['currency'] = '';
187
            }
188
            if (!array_key_exists('price', $replace)) {
189
                $replace['price'] = '';
190
            }
191
            if (!array_key_exists('subscription', $replace)) {
192
                $replace['subscription'] = '';
193
            }
194
            if (!array_key_exists('name', $replace)) {
195
                $replace['name'] = '';
196
            }
197
            if (!array_key_exists('url', $replace)) {
198
                $replace['url'] = '';
199
            }
200
            if (!array_key_exists('password', $replace)) {
201
                $replace['password'] = '';
202
            }
203
            if (!array_key_exists('address', $replace)) {
204
                $replace['address'] = '';
205
            }
206
            if (!array_key_exists('username', $replace)) {
207
                $replace['username'] = '';
208
            }
209
            if (!array_key_exists('email', $replace)) {
210
                $replace['email'] = '';
211
            }
212
            if (!array_key_exists('product', $replace)) {
213
                $replace['product'] = '';
214
            }
215
            $array1 = ['{{title}}', '{{currency}}', '{{price}}', '{{subscription}}', '{{name}}', '{{url}}', '{{password}}', '{{address}}', '{{username}}', '{{email}}','{{product}}'];
216
            $array2 = [$replace['title'], $replace['currency'], $replace['price'], $replace['subscription'], $replace['name'], $replace['url'], $replace['password'], $replace['address'], $replace['username'], $replace['email'], $replace['product']];
217
218
            $data = str_replace($array1, $array2, $data);
219
220
            \Mail::send('emails.mail', ['data' => $data], function ($m) use ($from, $to, $subject, $fromname, $toname, $cc, $attach) {
221
                $m->from($from, $fromname);
222
223
                $m->to($to, $toname)->subject($subject);
224
225
                /* if cc is need  */
226
                if (!empty($cc)) {
227
                    foreach ($cc as $address) {
228
                        $m->cc($address['address'], $address['name']);
229
                    }
230
                }
231
232
                /*  if attachment is need */
233
                if (!empty($attach)) {
234
                    foreach ($attach as $file) {
235
                        $m->attach($file['path'], $options = []);
236
                    }
237
                }
238
            });
239
        } catch (\Exception $ex) {
240
            //dd($ex);
241
            throw new \Exception('mailing problem');
242
        }
243
    }
244
245
    public function mailtest($id) {
246
        $from = '[email protected]';
247
        $to = '[email protected]';
248
        $subject = 'Tsting the mailer';
249
        $template = Template::where('id', $id)->whereBetween('type', [1, 8])->first();
250
        if ($template) {
251
            $data = $template->data;
252
        } else {
253
            return 'Select valid template';
254
        }
255
        $cc = [
256
            0 => [
257
                'name' => 'vijay',
258
                'address' => '[email protected]',
259
            ],
260
            1 => [
261
                'name' => 'vijay sebastian',
262
                'address' => '[email protected]',
263
            ],
264
        ];
265
        $attachments = [
266
            0 => [
267
                'path' => public_path('dist/img/avatar.png'),
268
            ],
269
        ];
270
        $replace = [
271
            'name' => 'vijay sebastian',
272
            'usernmae' => 'vijay',
273
            'password' => 'jfdvhd',
274
            'address' => 'dshbcvhjdsbvchdff',
275
        ];
276
        $this->Mailing($from, $to, $data, $subject, 'from', 'to', $cc, $attachments, $replace);
0 ignored issues
show
Documentation introduced by
'from' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$cc is of type array<integer,array<stri...dress\":\"string\"}>"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
277
    }
278
279
    public function show($id) {
280
        $currency = \Session::get('currency');
281
//        dd($currency);
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...
282
        try {
283
            if ($this->template->where('type', 3)->where('id', $id)->first()) {
284
                $data = $this->template->where('type', 3)->where('id', $id)->first()->data;
285
                //dd($data);
286
287
                $products = $this->product->where('id', '!=', 1)->take(4)->get();
288
289
                //dd($products);
290
                if (count($products) > 0) {
291
                    $template = '';
292
                    foreach ($products as $product) {
293
                        $url = $product->shoping_cart_link;
294
                        $title = $product->name;
295
                        if ($product->description) {
296
                            $description = str_replace('</ul>', '', str_replace('<ul>', '', $product->description));
297
                        } else {
298
                            $description = '';
299
                        }
300
                        if ($this->price->where('product_id', $product->id)->where('currency', $currency)->first()) {
301
                            $price = $this->price->where('product_id', $product->id)->where('currency', $currency)->first()->price;
302
303
                            $currency = $this->price->where('product_id', $product->id)->where('currency', $currency)->first()->currency;
304
305
                            $subscription = $this->plan->where('id', $this->price->where('product_id', $product->id)->where('currency', $currency)->first()->subscription)->first()->name;
306
                        }else{
307
                            return redirect('/')->with('fails',\Lang::get('message.no-such-currency-in-system'));
308
                        }
309
310
                        $array1 = ['{{title}}', '{{currency}}', '{{price}}', '{{subscription}}', '<li>{{feature}}</li>', '{{url}}'];
311
                        $array2 = [$title, $currency, $price, $subscription, $description, $url];
312
                        $template .= str_replace($array1, $array2, $data);
313
                    }
314
315
                    //dd($template);
316
                    return view('themes.default1.common.template.shoppingcart', compact('template'));
317
                } else {
318
                    $template = '<p>No Products</p>';
319
320
                    return view('themes.default1.common.template.shoppingcart', compact('template'));
321
                }
322
            } else {
323
                return redirect('/')->with('fails', 'no such record');
324
            }
325
        } catch (\Exception $e) {
326
            //dd($e);
327
            return redirect('/')->with('fails', $e->getMessage());
328
        }
329
    }
330
331
    public function popup($title, $body, $name = '', $modelid = '', $class = 'null', $trigger = false) {
332
        try {
333
            if ($modelid == '') {
334
                $modelid = $title;
335
            }
336
            if ($trigger == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
337
                $trigger = "<a href=# class=$class  data-toggle='modal' data-target=#edit" . $modelid . '>' . $name . '</a>';
338
            } else {
339
                $trigger = '';
340
            }
341
342
            return $trigger . "
343
                        <div class='modal fade' id=edit" . $modelid . ">
344
                            <div class='modal-dialog'>
345
                                <div class='modal-content'>
346
                                    <div class='modal-header'>
347
                                        <button type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>&times;</span></button>
348
                                        <h4 class='modal-title'>" . $title . "</h4>
349
                                    </div>
350
                                    <div class='modal-body'>
351
                                    " . $body . "
352
                                    </div>
353
                                    <div class='modal-footer'>
354
                                        <button type=button id=close class='btn btn-default pull-left' data-dismiss=modal>Close</button>
355
                                        <input type=submit class='btn btn-primary' value=" . \Lang::get('message.save') . '>
356
                                    </div>
357
                                </div>
358
                            </div>
359
                        </div>';
360
        } catch (\Exception $ex) {
361
            throw new \Exception($ex->getMessage());
362
        }
363
    }
364
365
}
366