Completed
Pull Request — master (#243)
by ARCANEDEV
08:39
created

LogViewerController::showByLevel()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 3
dl 0
loc 12
ccs 8
cts 8
cp 1
crap 2
rs 9.8666
c 0
b 0
f 0
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\Exceptions\LogNotFoundException;
6
use Arcanedev\LogViewer\Tables\StatsTable;
7
use Illuminate\Http\Request;
8
use Illuminate\Pagination\LengthAwarePaginator;
9
use Illuminate\Routing\Controller;
10
use Illuminate\Support\Arr;
11
use Illuminate\Support\Collection;
12
use Illuminate\Support\Str;
13
14
/**
15
 * Class     LogViewerController
16
 *
17
 * @package  LogViewer\Http\Controllers
18
 * @author   ARCANEDEV <[email protected]>
19
 */
20
class LogViewerController extends Controller
21
{
22
    /* -----------------------------------------------------------------
23
     |  Properties
24
     | -----------------------------------------------------------------
25
     */
26
27
    /**
28
     * The log viewer instance
29
     *
30
     * @var \Arcanedev\LogViewer\Contracts\LogViewer
31
     */
32
    protected $logViewer;
33
34
    /** @var int */
35
    protected $perPage = 30;
36
37
    /** @var string */
38
    protected $showRoute = 'log-viewer::logs.show';
39
40
    /* -----------------------------------------------------------------
41
     |  Constructor
42
     | -----------------------------------------------------------------
43
     */
44
45
    /**
46
     * LogViewerController constructor.
47
     *
48
     * @param  \Arcanedev\LogViewer\Contracts\LogViewer  $logViewer
49
     */
50 33
    public function __construct(LogViewerContract $logViewer)
51
    {
52 33
        $this->logViewer = $logViewer;
53 33
        $this->perPage = config('log-viewer.per-page', $this->perPage);
54 33
    }
55
56
    /* -----------------------------------------------------------------
57
     |  Main Methods
58
     | -----------------------------------------------------------------
59
     */
60
61
    /**
62
     * Show the dashboard.
63
     *
64
     * @return \Illuminate\View\View
65
     */
66 3
    public function index()
67
    {
68 3
        $stats     = $this->logViewer->statsTable();
69 3
        $chartData = $this->prepareChartData($stats);
70 3
        $percents  = $this->calcPercentages($stats->footer(), $stats->header());
71
72 3
        return $this->view('dashboard', compact('chartData', 'percents'));
73
    }
74
75
    /**
76
     * List all logs.
77
     *
78
     * @param  \Illuminate\Http\Request  $request
79
     *
80
     * @return \Illuminate\View\View
81
     */
82 3
    public function listLogs(Request $request)
83
    {
84 3
        $stats   = $this->logViewer->statsTable();
85 3
        $headers = $stats->header();
86 3
        $rows    = $this->paginate($stats->rows(), $request);
87
88 3
        return $this->view('logs', compact('headers', 'rows'));
89
    }
90
91
    /**
92
     * Show the log.
93
     *
94
     * @param  string                    $date
95
     * @param  \Illuminate\Http\Request  $request
96
     *
97
     * @return \Illuminate\View\View
98
     */
99 6
    public function show($date, Request $request)
100
    {
101 6
        $level   = 'all';
102 6
        $log     = $this->getLogOrFail($date);
103 3
        $query   = $request->get('query');
104 3
        $levels  = $this->logViewer->levelsNames();
105 3
        $entries = $log->entries($level)->paginate($this->perPage);
106
107 3
        return $this->view('show', compact('level', 'log', 'query', 'levels', 'entries'));
108
    }
109
110
    /**
111
     * Filter the log entries by level.
112
     *
113
     * @param  string                    $date
114
     * @param  string                    $level
115
     * @param  \Illuminate\Http\Request  $request
116
     *
117
     * @return \Illuminate\View\View|\Illuminate\Http\RedirectResponse
118
     */
119 6
    public function showByLevel($date, $level, Request $request)
120
    {
121 6
        if ($level === 'all')
122 3
            return redirect()->route($this->showRoute, [$date]);
123
124 3
        $log     = $this->getLogOrFail($date);
125 3
        $query   = $request->get('query');
126 3
        $levels  = $this->logViewer->levelsNames();
127 3
        $entries = $this->logViewer->entries($date, $level)->paginate($this->perPage);
128
129 3
        return $this->view('show', compact('level', 'log', 'query', 'levels', 'entries'));
130
    }
131
132
    /**
133
     * Show the log with the search query.
134
     *
135
     * @param  string                    $date
136
     * @param  string                    $level
137
     * @param  \Illuminate\Http\Request  $request
138
     *
139
     * @return \Illuminate\View\View|\Illuminate\Http\RedirectResponse
140
     */
141 3
    public function search($date, $level = 'all', Request $request)
142
    {
143 3
        if (is_null($query = $request->get('query')))
144
            return redirect()->route($this->showRoute, [$date]);
145
146 3
        $log     = $this->getLogOrFail($date);
147 3
        $levels  = $this->logViewer->levelsNames();
148
        $entries = $log->entries($level)->filter(function (LogEntry $value) use ($query) {
149 3
            return Str::contains($value->header, $query);
150 3
        })->paginate($this->perPage);
151
152 3
        return $this->view('show', compact('level', 'log', 'query', 'levels', 'entries'));
153
    }
154
155
    /**
156
     * Download the log
157
     *
158
     * @param  string  $date
159
     *
160
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
161
     */
162 3
    public function download($date)
163
    {
164 3
        return $this->logViewer->download($date);
165
    }
166
167
    /**
168
     * Delete a log.
169
     *
170
     * @param  \Illuminate\Http\Request  $request
171
     *
172
     * @return \Illuminate\Http\JsonResponse
173
     */
174 9
    public function delete(Request $request)
175
    {
176 9
        if ( ! $request->ajax())
177 3
            abort(405, 'Method Not Allowed');
178
179 6
        $date = $request->get('date');
180
181 6
        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...
182 6
            'result' => $this->logViewer->delete($date) ? 'success' : 'error'
183
        ]);
184
    }
185
186
    /* -----------------------------------------------------------------
187
     |  Other Methods
188
     | -----------------------------------------------------------------
189
     */
190
191
    /**
192
     * Get the evaluated view contents for the given view.
193
     *
194
     * @param  string  $view
195
     * @param  array   $data
196
     * @param  array   $mergeData
197
     *
198
     * @return \Illuminate\View\View
199
     */
200 15
    protected function view($view, $data = [], $mergeData = [])
201
    {
202 15
        $theme = config('log-viewer.theme');
203
204 15
        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...
205
    }
206
207
    /**
208
     * Paginate logs.
209
     *
210
     * @param  array                     $data
211
     * @param  \Illuminate\Http\Request  $request
212
     *
213
     * @return \Illuminate\Pagination\LengthAwarePaginator
214
     */
215 3
    protected function paginate(array $data, Request $request)
216
    {
217 3
        $data = new Collection($data);
218 3
        $page = $request->get('page', 1);
219 3
        $path = $request->url();
220
221 3
        return new LengthAwarePaginator(
222 3
            $data->forPage($page, $this->perPage),
223 3
            $data->count(),
224 3
            $this->perPage,
225 2
            $page,
226 3
            compact('path')
227
        );
228
    }
229
230
    /**
231
     * Get a log or fail
232
     *
233
     * @param  string  $date
234
     *
235
     * @return \Arcanedev\LogViewer\Entities\Log|null
236
     */
237 12
    protected function getLogOrFail($date)
238
    {
239 12
        $log = null;
240
241
        try {
242 12
            $log = $this->logViewer->get($date);
243
        }
244 3
        catch (LogNotFoundException $e) {
245 3
            abort(404, $e->getMessage());
246
        }
247
248 9
        return $log;
249
    }
250
251
    /**
252
     * Prepare chart data.
253
     *
254
     * @param  \Arcanedev\LogViewer\Tables\StatsTable  $stats
255
     *
256
     * @return string
257
     */
258 3
    protected function prepareChartData(StatsTable $stats)
259
    {
260 3
        $totals = $stats->totals()->all();
261
262 3
        return json_encode([
263 3
            'labels'   => Arr::pluck($totals, 'label'),
264
            'datasets' => [
265
                [
266 3
                    'data'                 => Arr::pluck($totals, 'value'),
267 3
                    'backgroundColor'      => Arr::pluck($totals, 'color'),
268 3
                    'hoverBackgroundColor' => Arr::pluck($totals, 'highlight'),
269
                ],
270
            ],
271
        ]);
272
    }
273
274
    /**
275
     * Calculate the percentage.
276
     *
277
     * @param  array  $total
278
     * @param  array  $names
279
     *
280
     * @return array
281
     */
282 3
    protected function calcPercentages(array $total, array $names)
283
    {
284 3
        $percents = [];
285 3
        $all      = Arr::get($total, 'all');
286
287 3
        foreach ($total as $level => $count) {
288 3
            $percents[$level] = [
289 3
                'name'    => $names[$level],
290 3
                'count'   => $count,
291 3
                'percent' => $all ? round(($count / $all) * 100, 2) : 0,
292
            ];
293
        }
294
295 3
        return $percents;
296
    }
297
}
298