Completed
Push — master ( 46643f...f8548b )
by ARCANEDEV
20s queued 14s
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
2
3
declare(strict_types=1);
4
5
namespace Arcanedev\LogViewer\Http\Controllers;
6
7
use Arcanedev\LogViewer\Contracts\LogViewer as LogViewerContract;
8
use Arcanedev\LogViewer\Entities\{LogEntry, LogEntryCollection};
9
use Arcanedev\LogViewer\Exceptions\LogNotFoundException;
10
use Arcanedev\LogViewer\Tables\StatsTable;
11
use Illuminate\Http\Request;
12
use Illuminate\Pagination\LengthAwarePaginator;
13
use Illuminate\Routing\Controller;
14
use Illuminate\Support\{Arr, Collection, Str};
15
16
/**
17
 * Class     LogViewerController
18
 *
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 60
    public function __construct(LogViewerContract $logViewer)
52
    {
53 60
        $this->logViewer = $logViewer;
54 60
        $this->perPage = config('log-viewer.per-page', $this->perPage);
55 60
    }
56
57
    /* -----------------------------------------------------------------
58
     |  Main Methods
59
     | -----------------------------------------------------------------
60
     */
61
62
    /**
63
     * Show the dashboard.
64
     *
65
     * @return \Illuminate\View\View
66
     */
67 4
    public function index()
68
    {
69 4
        $stats     = $this->logViewer->statsTable();
70 4
        $chartData = $this->prepareChartData($stats);
71 4
        $percents  = $this->calcPercentages($stats->footer(), $stats->header());
72
73 4
        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 4
    public function listLogs(Request $request)
84
    {
85 4
        $stats   = $this->logViewer->statsTable();
86 4
        $headers = $stats->header();
87 4
        $rows    = $this->paginate($stats->rows(), $request);
88
89 4
        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 8
    public function show(Request $request, $date)
101
    {
102 8
        $level   = 'all';
103 8
        $log     = $this->getLogOrFail($date);
104 4
        $query   = $request->get('query');
105 4
        $levels  = $this->logViewer->levelsNames();
106 4
        $entries = $log->entries($level)->paginate($this->perPage);
107
108 4
        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 8
    public function showByLevel(Request $request, $date, $level)
121
    {
122 8
        if ($level === 'all')
123 4
            return redirect()->route($this->showRoute, [$date]);
124
125 4
        $log     = $this->getLogOrFail($date);
126 4
        $query   = $request->get('query');
127 4
        $levels  = $this->logViewer->levelsNames();
128 4
        $entries = $this->logViewer->entries($date, $level)->paginate($this->perPage);
129
130 4
        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 20
    public function search(Request $request, $date, $level = 'all')
143
    {
144 20
        $query   = $request->get('query');
145
146 20
        if (is_null($query))
147 4
            return redirect()->route($this->showRoute, [$date]);
148
149 16
        $log     = $this->getLogOrFail($date);
150 16
        $levels  = $this->logViewer->levelsNames();
151 16
        $needles = array_map(function ($needle) {
152 16
            return Str::lower($needle);
153 16
        }, array_filter(explode(' ', $query)));
154 16
        $entries = $log->entries($level)
155 16
            ->unless(empty($needles), function (LogEntryCollection $entries) use ($needles) {
156 16
                return $entries->filter(function (LogEntry $entry) use ($needles) {
157 16
                    return Str::containsAll(Str::lower($entry->header), $needles);
158 16
                });
159 16
            })
160 16
            ->paginate($this->perPage);
161
162 16
        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 4
    public function download($date)
173
    {
174 4
        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 12
    public function delete(Request $request)
185
    {
186 12
        abort_unless($request->ajax(), 405, 'Method Not Allowed');
187
188 8
        $date = $request->input('date');
189
190 8
        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 8
            '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 32
    protected function view($view, $data = [], $mergeData = [])
210
    {
211 32
        $theme = config('log-viewer.theme');
212
213 32
        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 4
    protected function paginate(array $data, Request $request)
225
    {
226 4
        $data = new Collection($data);
227 4
        $page = $request->get('page', 1);
228 4
        $path = $request->url();
229
230 4
        return new LengthAwarePaginator(
231 4
            $data->forPage($page, $this->perPage),
232 4
            $data->count(),
233 4
            $this->perPage,
234
            $page,
235 4
            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 28
    protected function getLogOrFail($date)
247
    {
248 28
        $log = null;
249
250
        try {
251 28
            $log = $this->logViewer->get($date);
252
        }
253 4
        catch (LogNotFoundException $e) {
254 4
            abort(404, $e->getMessage());
255
        }
256
257 24
        return $log;
258
    }
259
260
    /**
261
     * Prepare chart data.
262
     *
263
     * @param  \Arcanedev\LogViewer\Tables\StatsTable  $stats
264
     *
265
     * @return string
266
     */
267 4
    protected function prepareChartData(StatsTable $stats)
268
    {
269 4
        $totals = $stats->totals()->all();
270
271 4
        return json_encode([
272 4
            'labels'   => Arr::pluck($totals, 'label'),
0 ignored issues
show
Documentation introduced by
$totals is of type array, but the function expects a object<Illuminate\Support\iterable>.

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...
273
            'datasets' => [
274
                [
275 4
                    'data'                 => Arr::pluck($totals, 'value'),
0 ignored issues
show
Documentation introduced by
$totals is of type array, but the function expects a object<Illuminate\Support\iterable>.

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...
276 4
                    'backgroundColor'      => Arr::pluck($totals, 'color'),
0 ignored issues
show
Documentation introduced by
$totals is of type array, but the function expects a object<Illuminate\Support\iterable>.

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 4
                    'hoverBackgroundColor' => Arr::pluck($totals, 'highlight'),
0 ignored issues
show
Documentation introduced by
$totals is of type array, but the function expects a object<Illuminate\Support\iterable>.

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...
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 4
    protected function calcPercentages(array $total, array $names)
292
    {
293 4
        $percents = [];
294 4
        $all      = Arr::get($total, 'all');
295
296 4
        foreach ($total as $level => $count) {
297 4
            $percents[$level] = [
298 4
                'name'    => $names[$level],
299 4
                'count'   => $count,
300 4
                'percent' => $all ? round(($count / $all) * 100, 2) : 0,
301
            ];
302
        }
303
304 4
        return $percents;
305
    }
306
}
307