UtilitiesController::logs()   B
last analyzed

Complexity

Conditions 7
Paths 8

Size

Total Lines 52
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 31
nc 8
nop 2
dl 0
loc 52
rs 7.2396
c 0
b 0
f 0

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 Yajra\CMS\Http\Controllers;
4
5
use Collective\Html\HtmlBuilder;
6
use Illuminate\Contracts\Logging\Log;
7
use Illuminate\Http\Request;
8
use Illuminate\Support\Facades\Artisan;
9
use Illuminate\Support\Facades\File;
10
use Rap2hpoutre\LaravelLogViewer\LaravelLogViewer;
11
use Yajra\CMS\Entities\Category;
12
use Yajra\CMS\Entities\Menu;
13
use Yajra\Datatables\Datatables;
14
15
class UtilitiesController extends Controller
16
{
17
    /**
18
     * @var \Illuminate\Contracts\Console\Kernel
19
     */
20
    protected $command;
21
22
    /**
23
     * @var \Collective\Html\HtmlBuilder
24
     */
25
    protected $html;
26
27
    /**
28
     * @var \Illuminate\Contracts\Logging\Log
29
     */
30
    protected $log;
31
32
    /**
33
     * Controller specific permission ability map.
34
     *
35
     * @var array
36
     */
37
    protected $customPermissionMap = [
38
        'backup' => 'view',
39
        'config' => 'view',
40
        'cache'  => 'view',
41
        'logs'   => 'view',
42
        'views'  => 'view',
43
        'index'  => 'view',
44
    ];
45
46
    /**
47
     * UtilitiesController constructor.
48
     *
49
     * @param \Illuminate\Contracts\Logging\Log $log
50
     * @param \Collective\Html\HtmlBuilder $html
51
     */
52
    public function __construct(Log $log, HtmlBuilder $html)
53
    {
54
        $this->html = $html;
55
        $this->log  = $log;
56
57
        $this->authorizePermissionResource('utilities');
58
    }
59
60
    /**
61
     * Display list of utilities.
62
     *
63
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
64
     */
65
    public function index()
66
    {
67
        return view('administrator.utilities.index');
68
    }
69
70
    /**
71
     * Execute back up manually.
72
     *
73
     * @param string $task
74
     * @return \Illuminate\Http\JsonResponse
75
     */
76
    public function backup($task = 'run')
77
    {
78
        if (! in_array($task, ['backup', 'clean'])) {
79
            $message = trans('cms::utilities.backup.not_allowed',
80
                    ['task' => $task]) . trans('cms::utilities.field.executed_by',
81
                    ['name' => $this->getCurrentUserName()]);
82
            $this->log->info($message);
83
84
            return $this->notifyError($message);
85
        }
86
87
        Artisan::call('backup:' . $task);
88
        $message = $task == 'clean' ? trans('cms::utilities.backup.cleanup_complete') : trans('cms::utilities.backup.complete');
89
        $this->log->info($message . trans('cms::utilities.field.executed_by', ['name' => $this->getCurrentUserName()]));
90
91
        return $this->notifySuccess($message);
92
    }
93
94
    /**
95
     * Get name of the current user.
96
     *
97
     * @return string
98
     */
99
    protected function getCurrentUserName()
100
    {
101
        return auth('administrator')->user()->present()->name();
0 ignored issues
show
Bug introduced by
The method user does only exist in Illuminate\Contracts\Auth\Guard, but not in Illuminate\Contracts\Auth\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
102
    }
103
104
    /**
105
     * Clear cache manually.
106
     *
107
     * @return \Illuminate\Http\JsonResponse
108
     */
109 View Code Duplication
    public function cache()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
110
    {
111
        Artisan::call('cache:clear');
112
        $this->log->info(trans('cms::utilities.cache.success') . trans('cms::utilities.field.executed_by',
113
                ['name' => $this->getCurrentUserName()]));
114
115
        return $this->notifySuccess(trans('cms::utilities.cache.success'));
116
    }
117
118
    /**
119
     * Run config artisan command manually.
120
     *
121
     * @param string $task
122
     * @return \Illuminate\Http\JsonResponse
123
     */
124
    public function config($task)
125
    {
126
        if (! in_array($task, ['cache', 'clear'])) {
127
            $this->log->info(sprintf("%s %s",
128
                trans('cms::utilities.config.not_allowed', ['task' => $task]),
129
                trans('cms::utilities.field.executed_by', ['name' => $this->getCurrentUserName()])
130
            ));
131
132
            return $this->notifyError($message);
0 ignored issues
show
Bug introduced by
The variable $message seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
133
        }
134
135
        $message = $task == 'cache' ? trans('cms::utilities.config.cache') : trans('cms::utilities.config.cache_cleared');
136
        $this->log->info(sprintf("%s %s",
137
            $message,
138
            trans('cms::utilities.field.executed_by', ['name' => $this->getCurrentUserName()])
139
        ));
140
        Artisan::call('config:' . $task);
141
142
        return $this->notifySuccess($message);
143
    }
144
145
    /**
146
     * Clear views manually.
147
     *
148
     * @return \Illuminate\Http\JsonResponse
149
     */
150 View Code Duplication
    public function views()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
151
    {
152
        Artisan::call('view:clear');
153
        $this->log->info(sprintf("%s %s",
154
            trans('cms::utilities.views.success'),
155
            trans('cms::utilities.field.executed_by', ['name' => $this->getCurrentUserName()])
156
        ));
157
158
        return $this->notifySuccess(trans('cms::utilities.views.success'));
159
    }
160
161
    /**
162
     * Log viewer.
163
     *
164
     * @param \Illuminate\Http\Request $request
165
     * @param \Yajra\Datatables\Datatables $datatables
166
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View|\Symfony\Component\HttpFoundation\BinaryFileResponse
167
     * @throws \Exception
168
     */
169
    public function logs(Request $request, Datatables $datatables)
170
    {
171
        if ($request->input('l')) {
172
            LaravelLogViewer::setFile(base64_decode($request->input('l')));
173
        }
174
175
        if ($request->input('dl')) {
176
            return response()->download(LaravelLogViewer::pathToLogFile(base64_decode($request->input('dl'))));
177
        } elseif ($request->has('del')) {
178
            File::delete(LaravelLogViewer::pathToLogFile(base64_decode($request->input('del'))));
179
180
            return redirect()->to($request->url());
181
        }
182
183
        $logs = LaravelLogViewer::all();
184
185
        if ($request->wantsJson()) {
186
            return $datatables->collection(collect($logs))
187
                              ->editColumn('stack', '{!! nl2br($stack) !!}')
188
                              ->editColumn('level', function ($log) {
189
                                  $content = $this->html->tag('span', '', [
190
                                      'class' => "glyphicon glyphicon-{$log['level_img']}-sign",
191
                                  ]);
192
193
                                  $content .= '&nbsp;' . $log['level'];
194
195
                                  return $this->html->tag('span', $content, ['class' => "text-{$log['level_class']}"]);
196
                              })
197
                              ->addColumn('content', function ($log) {
198
                                  $html = '';
199
                                  if ($log['stack']) {
200
                                      $html = '<a class="pull-right expand btn btn-default btn-xs"><span class="glyphicon glyphicon-search"></span></a>';
201
                                  }
202
203
                                  $html .= $log['text'];
204
205
                                  if (isset($log['in_file'])) {
206
                                      $html .= '<br>' . $log['in_file'];
207
                                  }
208
209
                                  return $html;
210
                              })
211
                              ->rawColumns(['content'])
212
                              ->make(true);
213
        }
214
215
        return view('administrator.utilities.log', [
216
            'logs'         => $logs,
217
            'files'        => LaravelLogViewer::getFiles(true),
218
            'current_file' => LaravelLogViewer::getFileName(),
219
        ]);
220
    }
221
222
    /**
223
     * Rebuild menu entity nested set tree.
224
     */
225
    public function rebuildMenu()
226
    {
227
        Menu::rebuild(true);
228
229
        return $this->notifySuccess(trans('cms::utilities.menu.success'));
230
    }
231
232
    /**
233
     * Rebuild category entity nested set tree.
234
     */
235
    public function rebuildCategory()
236
    {
237
        Category::rebuild(true);
238
239
        return $this->notifySuccess(trans('cms::utilities.category.success'));
240
    }
241
}
242