Completed
Pull Request — master (#292)
by
unknown
05:09
created

LogViewerController::search()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4.0072

Importance

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