Completed
Pull Request — master (#308)
by ARCANEDEV
04:32
created

LogViewerController   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 286
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Test Coverage

Coverage 98.82%

Importance

Changes 0
Metric Value
dl 0
loc 286
ccs 84
cts 85
cp 0.9882
rs 10
c 0
b 0
f 0
wmc 19
lcom 1
cbo 12

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A index() 0 8 1
A listLogs() 0 8 1
A show() 0 10 1
A showByLevel() 0 12 2
A search() 0 22 2
A download() 0 4 1
A delete() 0 10 2
A view() 0 6 1
A paginate() 0 14 1
A getLogOrFail() 0 13 2
A prepareChartData() 0 15 1
A calcPercentages() 0 15 3
1
<?php namespace Arcanedev\LogViewer\Http\Controllers;
2
3
use Arcanedev\LogViewer\Contracts\LogViewer as LogViewerContract;
4
use Arcanedev\LogViewer\Entities\LogEntry;
5
use Arcanedev\LogViewer\Entities\LogEntryCollection;
6
use Arcanedev\LogViewer\Exceptions\LogNotFoundException;
7
use Arcanedev\LogViewer\Tables\StatsTable;
8
use Illuminate\Http\Request;
9
use Illuminate\Pagination\LengthAwarePaginator;
10
use Illuminate\Routing\Controller;
11
use Illuminate\Support\Arr;
12
use Illuminate\Support\Collection;
13
use Illuminate\Support\Str;
14
15
/**
16
 * Class     LogViewerController
17
 *
18
 * @package  LogViewer\Http\Controllers
19
 * @author   ARCANEDEV <[email protected]>
20
 */
21
class LogViewerController extends Controller
22
{
23
    /* -----------------------------------------------------------------
24
     |  Properties
25
     | -----------------------------------------------------------------
26
     */
27
28
    /**
29
     * The log viewer instance
30
     *
31
     * @var \Arcanedev\LogViewer\Contracts\LogViewer
32
     */
33
    protected $logViewer;
34
35
    /** @var int */
36
    protected $perPage = 30;
37
38
    /** @var string */
39
    protected $showRoute = 'log-viewer::logs.show';
40
41
    /* -----------------------------------------------------------------
42
     |  Constructor
43
     | -----------------------------------------------------------------
44
     */
45
46
    /**
47
     * LogViewerController constructor.
48
     *
49
     * @param  \Arcanedev\LogViewer\Contracts\LogViewer  $logViewer
50
     */
51 28
    public function __construct(LogViewerContract $logViewer)
52
    {
53 28
        $this->logViewer = $logViewer;
54 28
        $this->perPage = config('log-viewer.per-page', $this->perPage);
55 28
    }
56
57
    /* -----------------------------------------------------------------
58
     |  Main Methods
59
     | -----------------------------------------------------------------
60
     */
61
62
    /**
63
     * Show the dashboard.
64
     *
65
     * @return \Illuminate\View\View
66
     */
67 2
    public function index()
68
    {
69 2
        $stats     = $this->logViewer->statsTable();
70 2
        $chartData = $this->prepareChartData($stats);
71 2
        $percents  = $this->calcPercentages($stats->footer(), $stats->header());
72
73 2
        return $this->view('dashboard', compact('chartData', 'percents'));
74
    }
75
76
    /**
77
     * List all logs.
78
     *
79
     * @param  \Illuminate\Http\Request  $request
80
     *
81
     * @return \Illuminate\View\View
82
     */
83 2
    public function listLogs(Request $request)
84
    {
85 2
        $stats   = $this->logViewer->statsTable();
86 2
        $headers = $stats->header();
87 2
        $rows    = $this->paginate($stats->rows(), $request);
88
89 2
        return $this->view('logs', compact('headers', 'rows'));
90
    }
91
92
    /**
93
     * Show the log.
94
     *
95
     * @param  \Illuminate\Http\Request  $request
96
     * @param  string                    $date
97
     *
98
     * @return \Illuminate\View\View
99
     */
100 4
    public function show(Request $request, $date)
101
    {
102 4
        $level   = 'all';
103 4
        $log     = $this->getLogOrFail($date);
104 2
        $query   = $request->get('query');
105 2
        $levels  = $this->logViewer->levelsNames();
106 2
        $entries = $log->entries($level)->paginate($this->perPage);
107
108 2
        return $this->view('show', compact('level', 'log', 'query', 'levels', 'entries'));
109
    }
110
111
    /**
112
     * Filter the log entries by level.
113
     *
114
     * @param  \Illuminate\Http\Request  $request
115
     * @param  string                    $date
116
     * @param  string                    $level
117
     *
118
     * @return \Illuminate\View\View|\Illuminate\Http\RedirectResponse
119
     */
120 4
    public function showByLevel(Request $request, $date, $level)
121
    {
122 4
        if ($level === 'all')
123 2
            return redirect()->route($this->showRoute, [$date]);
124
125 2
        $log     = $this->getLogOrFail($date);
126 2
        $query   = $request->get('query');
127 2
        $levels  = $this->logViewer->levelsNames();
128 2
        $entries = $this->logViewer->entries($date, $level)->paginate($this->perPage);
129
130 2
        return $this->view('show', compact('level', 'log', 'query', 'levels', 'entries'));
131
    }
132
133
    /**
134
     * Show the log with the search query.
135
     *
136
     * @param  \Illuminate\Http\Request  $request
137
     * @param  string                    $date
138
     * @param  string                    $level
139
     *
140
     * @return \Illuminate\View\View|\Illuminate\Http\RedirectResponse
141
     */
142 8
    public function search(Request $request, $date, $level = 'all')
143
    {
144 8
        $query   = $request->get('query');
145
146 8
        if (is_null($query))
147
            return redirect()->route($this->showRoute, [$date]);
148
149 8
        $log     = $this->getLogOrFail($date);
150 8
        $levels  = $this->logViewer->levelsNames();
151
        $needles = array_map(function ($needle) {
152 8
            return Str::lower($needle);
153 8
        }, array_filter(explode(' ', $query)));
154 8
        $entries = $log->entries($level)
155
            ->unless(empty($needles), function (LogEntryCollection $entries) use ($needles) {
156
                return $entries->filter(function (LogEntry $entry) use ($needles) {
157 8
                    return Str::containsAll(Str::lower($entry->header), $needles);
158 8
                });
159 8
            })
160 8
            ->paginate($this->perPage);
161
162 8
        return $this->view('show', compact('level', 'log', 'query', 'levels', 'entries'));
163
    }
164
165
    /**
166
     * Download the log
167
     *
168
     * @param  string  $date
169
     *
170
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
171
     */
172 2
    public function download($date)
173
    {
174 2
        return $this->logViewer->download($date);
175
    }
176
177
    /**
178
     * Delete a log.
179
     *
180
     * @param  \Illuminate\Http\Request  $request
181
     *
182
     * @return \Illuminate\Http\JsonResponse
183
     */
184 6
    public function delete(Request $request)
185
    {
186 6
        abort_unless($request->ajax(), 405, 'Method Not Allowed');
187
188 4
        $date = $request->get('date');
189
190 4
        return response()->json([
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

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...
191 4
            'result' => $this->logViewer->delete($date) ? 'success' : 'error'
192
        ]);
193
    }
194
195
    /* -----------------------------------------------------------------
196
     |  Other Methods
197
     | -----------------------------------------------------------------
198
     */
199
200
    /**
201
     * Get the evaluated view contents for the given view.
202
     *
203
     * @param  string  $view
204
     * @param  array   $data
205
     * @param  array   $mergeData
206
     *
207
     * @return \Illuminate\View\View
208
     */
209 16
    protected function view($view, $data = [], $mergeData = [])
210
    {
211 16
        $theme = config('log-viewer.theme');
212
213 16
        return view()->make("log-viewer::{$theme}.{$view}", $data, $mergeData);
0 ignored issues
show
Bug introduced by
The method make does only exist in Illuminate\Contracts\View\Factory, but not in Illuminate\View\View.

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...
214
    }
215
216
    /**
217
     * Paginate logs.
218
     *
219
     * @param  array                     $data
220
     * @param  \Illuminate\Http\Request  $request
221
     *
222
     * @return \Illuminate\Pagination\LengthAwarePaginator
223
     */
224 2
    protected function paginate(array $data, Request $request)
225
    {
226 2
        $data = new Collection($data);
227 2
        $page = $request->get('page', 1);
228 2
        $path = $request->url();
229
230 2
        return new LengthAwarePaginator(
231 2
            $data->forPage($page, $this->perPage),
232 2
            $data->count(),
233 2
            $this->perPage,
234 1
            $page,
235 2
            compact('path')
236
        );
237
    }
238
239
    /**
240
     * Get a log or fail
241
     *
242
     * @param  string  $date
243
     *
244
     * @return \Arcanedev\LogViewer\Entities\Log|null
245
     */
246 14
    protected function getLogOrFail($date)
247
    {
248 14
        $log = null;
249
250
        try {
251 14
            $log = $this->logViewer->get($date);
252
        }
253 2
        catch (LogNotFoundException $e) {
254 2
            abort(404, $e->getMessage());
255
        }
256
257 12
        return $log;
258
    }
259
260
    /**
261
     * Prepare chart data.
262
     *
263
     * @param  \Arcanedev\LogViewer\Tables\StatsTable  $stats
264
     *
265
     * @return string
266
     */
267 2
    protected function prepareChartData(StatsTable $stats)
268
    {
269 2
        $totals = $stats->totals()->all();
270
271 2
        return json_encode([
272 2
            'labels'   => Arr::pluck($totals, 'label'),
273
            'datasets' => [
274
                [
275 2
                    'data'                 => Arr::pluck($totals, 'value'),
276 2
                    'backgroundColor'      => Arr::pluck($totals, 'color'),
277 2
                    'hoverBackgroundColor' => Arr::pluck($totals, 'highlight'),
278
                ],
279
            ],
280
        ]);
281
    }
282
283
    /**
284
     * Calculate the percentage.
285
     *
286
     * @param  array  $total
287
     * @param  array  $names
288
     *
289
     * @return array
290
     */
291 2
    protected function calcPercentages(array $total, array $names)
292
    {
293 2
        $percents = [];
294 2
        $all      = Arr::get($total, 'all');
295
296 2
        foreach ($total as $level => $count) {
297 2
            $percents[$level] = [
298 2
                'name'    => $names[$level],
299 2
                'count'   => $count,
300 2
                'percent' => $all ? round(($count / $all) * 100, 2) : 0,
301
            ];
302
        }
303
304 2
        return $percents;
305
    }
306
}
307