Completed
Push — development ( c72a58...bbb3cb )
by Ashutosh
10:50 queued 12s
created

PageController   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 371
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 44
eloc 194
dl 0
loc 371
rs 8.8798
c 0
b 0
f 0

18 Methods

Rating   Name   Duplication   Size   Complexity  
A index() 0 6 2
A getLocation() 0 12 2
A __construct() 0 7 1
A getPages() 0 33 2
A create() 0 11 2
A edit() 0 15 2
A transform() 0 16 3
A search() 0 9 2
A show() 0 11 4
A addSegment() 0 8 2
A getPageUrl() 0 9 1
A getSlug() 0 4 1
A pageTemplates() 0 23 3
A checkString() 0 4 2
A store() 0 30 3
B destroy() 0 60 6
A update() 0 28 3
A generate() 0 12 3

How to fix   Complexity   

Complex Class

Complex classes like PageController 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 PageController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace App\Http\Controllers\Front;
4
5
use App\DefaultPage;
6
use App\Model\Common\PricingTemplate;
7
use App\Model\Front\FrontendPage;
8
use App\Model\Product\ProductGroup;
9
use Bugsnag;
10
use Illuminate\Http\Request;
11
12
class PageController extends GetPageTemplateController
13
{
14
    public $page;
15
16
    public function __construct()
17
    {
18
        // $this->middleware('auth');
19
        // $this->middleware('admin');
20
21
        $page = new FrontendPage();
22
        $this->page = $page;
23
    }
24
25
    public function index()
26
    {
27
        try {
28
            return view('themes.default1.front.page.index');
29
        } catch (\Exception $ex) {
30
            return redirect()->back()->with('fails', $ex->getMessage());
31
        }
32
    }
33
34
    public function getLocation()
35
    {
36
        try {
37
            $location = \GeoIP::getLocation();
38
39
            return $location;
40
        } catch (Exception $ex) {
0 ignored issues
show
Bug introduced by
The type App\Http\Controllers\Front\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
41
            app('log')->error($ex->getMessage());
42
            Bugsnag::notifyException($ex->getMessage());
43
            $location = \Config::get('geoip.default_location');
44
45
            return $location;
46
        }
47
    }
48
49
    public function getPages()
50
    {
51
        return \DataTables::of($this->page->get())
52
                        ->addColumn('checkbox', function ($model) {
53
                            return "<input type='checkbox' class='page_checkbox' 
54
                            value=".$model->id.' name=select[] id=check>';
55
                        })
56
                        ->addColumn('name', function ($model) {
57
                            return ucfirst($model->name);
58
                        })
59
                        ->addColumn('url', function ($model) {
60
                            return $model->url;
61
                        })
62
                        ->addColumn('created_at', function ($model) {
63
                            $created = $model->created_at;
64
                            if ($created) {
65
                                $date1 = new \DateTime($created);
66
                                $tz = \Auth::user()->timezone()->first()->name;
67
                                $date1->setTimezone(new \DateTimeZone($tz));
68
                                $createdate = $date1->format('M j, Y, g:i a ');
69
                            }
70
71
                            return $createdate;
72
                        })
73
74
                        ->addColumn('action', function ($model) {
75
                            return '<a href='.url('pages/'.$model->id.'/edit')
76
                            ." class='btn btn-sm btn-primary btn-xs'><i class='fa fa-edit'
77
                                 style='color:white;'> </i>&nbsp;&nbsp;Edit</a>";
78
                        })
79
80
                          ->rawColumns(['checkbox', 'name', 'url',  'created_at', 'action'])
81
                        ->make(true);
82
        // ->searchColumns('name', 'content')
83
                        // ->orderColumns('name')
84
                        // ->make();
85
    }
86
87
    public function create()
88
    {
89
        try {
90
            $parents = $this->page->pluck('name', 'id')->toArray();
91
92
            return view('themes.default1.front.page.create', compact('parents'));
93
        } catch (\Exception $ex) {
94
            app('log')->error($ex->getMessage());
95
            Bugsnag::notifyException($ex);
96
97
            return redirect()->back()->with('fails', $ex->getMessage());
98
        }
99
    }
100
101
    public function edit($id)
102
    {
103
        try {
104
            $page = $this->page->where('id', $id)->first();
105
            $parents = $this->page->where('id', '!=', $id)->pluck('name', 'id')->toArray();
106
            $selectedDefault = DefaultPage::value('page_id');
107
            $date = $this->page->where('id', $id)->pluck('created_at')->first();
108
            $publishingDate = date('d/m/Y', strtotime($date));
109
            $selectedParent = $this->page->where('id', $id)->pluck('parent_page_id')->toArray();
110
            $parentName = $this->page->where('id', $selectedParent)->pluck('name', 'id')->toArray();
111
112
            return view('themes.default1.front.page.edit', compact('parents', 'page', 'default', 'selectedDefault', 'publishingDate','selectedParent',
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 150 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...
113
                'parentName'));
114
        } catch (\Exception $ex) {
115
            return redirect()->back()->with('fails', $ex->getMessage());
116
        }
117
    }
118
119
    public function store(Request $request)
120
    {
121
        $this->validate($request, [
122
            'name'    => 'required',
123
            'publish' => 'required',
124
            'slug'    => 'required',
125
            'url'     => 'required',
126
            'content' => 'required',
127
        ]);
128
129
        try {
130
            $url = $request->input('url');
131
            if ($request->input('type') =='contactus') {
132
               $url = url('/contact-us');
133
            }
134
            $this->page->name = $request->input('name');
135
            $this->page->publish = $request->input('publish');
136
            $this->page->slug = $request->input('slug');
137
            $this->page->url = $url;
138
            $this->page->parent_page_id = $request->input('parent_page_id');
139
            $this->page->type = $request->input('type');
140
            $this->page->content = $request->input('content');
141
            $this->page->save();
142
143
            return redirect()->back()->with('success', \Lang::get('message.saved-successfully'));
144
        } catch (\Exception $ex) {
145
            app('log')->error($ex->getMessage());
146
            Bugsnag::notifyException($ex);
147
148
            return redirect()->back()->with('fails', $ex->getMessage());
149
        }
150
    }
151
152
    public function update($id, Request $request)
153
    {
154
        $this->validate($request, [
155
            'name'           => 'required',
156
            'publish'        => 'required',
157
            'slug'           => 'required',
158
            'url'            => 'required',
159
            'content'        => 'required',
160
            'created_at'     => 'required',
161
        ]);
162
163
        try {
164
            if($request->input('default_page_id') != '') {
165
            $page = $this->page->where('id', $id)->first();
166
            $page->fill($request->except('created_at'))->save();
167
            $date = \DateTime::createFromFormat('d/m/Y', $request->input('created_at'));
168
            $page->created_at = $date->format('Y-m-d H:i:s');
169
            $page->save();
170
            $defaultUrl = $this->page->where('id', $request->input('default_page_id'))->pluck('url')->first();
171
            DefaultPage::find(1)->update(['page_id'=>$request->input('default_page_id'), 'page_url'=>$defaultUrl]);  
172
            } else {
173
                DefaultPage::find(1)->update(['page_id'=>1, 'page_url'=>url('my-invoices')]);
174
            }
175
            
176
177
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
178
        } catch (\Exception $ex) {
179
            return redirect()->back()->with('fails', $ex->getMessage());
180
        }
181
    }
182
183
    public function getPageUrl($slug)
184
    {
185
        $productController = new \App\Http\Controllers\Product\ProductController();
186
        //  $url = url('/');
187
        //  $segment = $this->addSegment(['public/pages']);
188
        $url = url('/');
189
190
        $slug = str_slug($slug, '-');
191
        echo $url.'/pages'.'/'.$slug;
192
    }
193
194
    public function getSlug($slug)
195
    {
196
        $slug = str_slug($slug, '-');
197
        echo $slug;
198
    }
199
200
    public function addSegment($segments = [])
201
    {
202
        $segment = '';
203
        foreach ($segments as $seg) {
204
            $segment .= '/'.$seg;
205
        }
206
207
        return $segment;
208
    }
209
210
    public function generate(Request $request)
211
    {
212
        // dd($request->all());
213
        if ($request->has('slug')) {
214
            $slug = $request->input('slug');
215
216
            return $this->getSlug($slug);
217
        }
218
        if ($request->has('url')) {
219
            $slug = $request->input('url');
220
221
            return $this->getPageUrl($slug);
222
        }
223
    }
224
225
    public function show($slug)
226
    {
227
        try {
228
            $page = $this->page->where('slug', $slug)->where('publish', 1)->first();
229
            if ($page && $page->type == 'cart') {
230
                return $this->cart();
231
            }
232
233
            return view('themes.default1.front.page.show', compact('page'));
234
        } catch (\Exception $ex) {
235
            return redirect()->back()->with('fails', $ex->getMessage());
236
        }
237
    }
238
239
    /**
240
     * Remove the specified resource from storage.
241
     *
242
     * @param int $id
243
     *
244
     * @return \Response
245
     */
246
    public function destroy(Request $request)
247
    {
248
        try {
249
            $ids = $request->input('select');
250
            $defaultPageId = DefaultPage::pluck('page_id')->first();
251
            if (!empty($ids)) {
252
                foreach ($ids as $id) {
253
                    if ($id != $defaultPageId) {
254
                        $page = $this->page->where('id', $id)->first();
255
                        if ($page) {
256
                            // dd($page);
257
                            $page->delete();
258
                        } else {
259
                            echo "<div class='alert alert-danger alert-dismissable'>
260
                    <i class='fa fa-ban'></i>
261
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
262
                    /* @scrutinizer ignore-type */
263
                    \Lang::get('message.failed').'
264
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
265
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
266
                </div>';
267
                            //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
268
                        }
269
                        echo "<div class='alert alert-success alert-dismissable'>
270
                    <i class='fa fa-ban'></i>
271
272
                    <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> '.
273
                    /* @scrutinizer ignore-type */
274
                    \Lang::get('message.success').'
275
276
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
277
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
278
                </div>';
279
                    } else {
280
                        echo "<div class='alert alert-danger alert-dismissable'>
281
                    <i class='fa fa-ban'></i>
282
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
283
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
284
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
285
                        './* @scrutinizer ignore-type */ \Lang::get('message.can-not-delete-default-page').'
286
                </div>';
287
                    }
288
                }
289
            } else {
290
                echo "<div class='alert alert-danger alert-dismissable'>
291
                    <i class='fa fa-ban'></i>
292
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
293
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
294
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
295
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
296
                </div>';
297
                //echo \Lang::get('message.select-a-row');
298
            }
299
        } catch (\Exception $e) {
300
            echo "<div class='alert alert-danger alert-dismissable'>
301
                    <i class='fa fa-ban'></i>
302
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
303
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
304
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
305
                        '.$e->getMessage().'
306
                </div>';
307
        }
308
    }
309
310
    public function search(Request $request)
311
    {
312
        try {
313
            $search = $request->input('q');
314
            $model = $this->result($search, $this->page);
315
316
            return view('themes.default1.front.page.search', compact('model'));
317
        } catch (\Exception $ex) {
318
            return redirect()->back()->with('fails', $ex->getMessage());
319
        }
320
    }
321
322
    public function transform($type, $data, $trasform = [])
323
    {
324
        $config = \Config::get("transform.$type");
325
        $result = '';
326
        $array = [];
327
        foreach ($trasform as $trans) {
328
            $array[] = $this->checkConfigKey($config, $trans);
329
        }
330
        $c = count($array);
331
        for ($i = 0; $i < $c; $i++) {
332
            $array1 = $this->keyArray($array[$i]);
333
            $array2 = $this->valueArray($array[$i]);
334
            $result .= str_replace($array1, $array2, $data);
335
        }
336
337
        return $result;
338
    }
339
340
    public function checkString($data, $string)
341
    {
342
        if (strpos($data, $string) !== false) {
343
            return true;
344
        }
345
    }
346
347
    /**
348
     * Get Page Template when Group in Store Dropdown is
349
     * selected on the basis of Group id.
350
     *
351
     * @author Ashutosh Pathak <[email protected]>
352
     *
353
     * @date   2019-01-10T01:20:52+0530
354
     *
355
     * @param int $groupid    Group id
356
     * @param int $templateid Id of the Template
357
     *
358
     * @return longtext The Template to be displayed
359
     */
360
    public function pageTemplates(int $templateid, int $groupid)
361
    {
362
        try {
363
            $cont = new CartController();
364
            $currency = $cont->currency();
365
            \Session::put('currency', $currency);
366
            if (!\Session::has('currency')) {
367
                \Session::put('currency', 'INR');
368
            }
369
            $data = PricingTemplate::find($templateid)->data;
370
            $headline = ProductGroup::find($groupid)->headline;
371
            $tagline = ProductGroup::find($groupid)->tagline;
372
            $productsRelatedToGroup = ProductGroup::find($groupid)->product()->where('hidden', '!=', 1)
373
            ->orderBy('created_at', 'desc')->get(); //Get ALL the Products Related to the Group
374
            $trasform = [];
375
            $templates = $this->getTemplateOne($productsRelatedToGroup, $data, $trasform);
376
377
            return view('themes.default1.common.template.shoppingcart', compact('templates', 'headline', 'tagline'));
378
        } catch (\Exception $ex) {
379
            app('log')->error($ex->getMessage());
380
            Bugsnag::notifyException($ex);
381
382
            return redirect()->back()->with('fails', $ex->getMessage());
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->back(...ls', $ex->getMessage()) also could return the type Illuminate\Http\Redirect...nate\Routing\Redirector which is incompatible with the documented return type App\Http\Controllers\Front\longtext.
Loading history...
383
        }
384
    }
385
}
386