TrackStatistics   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 4
dl 0
loc 64
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A handle() 0 4 1
A terminate() 0 26 4
A configHitsLottery() 0 6 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Rinvex\Statistics\Http\Middleware;
6
7
use Closure;
8
use Carbon\Carbon;
9
use Illuminate\Http\Request;
10
use Rinvex\Statistics\Jobs\CrunchStatistics;
11
use Rinvex\Statistics\Jobs\CleanStatisticsRequests;
12
13
class TrackStatistics
14
{
15
    /**
16
     * Handle an incoming request.
17
     *
18
     * @param \Illuminate\Http\Request $request
19
     * @param \Closure                 $next
20
     *
21
     * @return mixed
22
     */
23
    public function handle(Request $request, Closure $next)
24
    {
25
        return $next($request);
26
    }
27
28
    /**
29
     * Perform any final actions for the request lifecycle.
30
     *
31
     * @param \Illuminate\Http\Request                   $request
32
     * @param \Symfony\Component\HttpFoundation\Response $response
33
     *
34
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
35
     *
36
     * @return void
37
     */
38
    public function terminate($request, $response): void
39
    {
40
        $currentUser = $request->user();
41
42
        app('rinvex.statistics.datum')->fill([
43
            'session_id' => $request->session()->getId(),
44
            'user_id' => optional($currentUser)->getKey(),
45
            'user_type' => optional($currentUser)->getMorphClass(),
46
            'status_code' => $response->getStatusCode(),
47
            'uri' => $request->getUri(),
48
            'method' => $request->getMethod(),
49
            'server' => $request->server() ?: null,
50
            'input' => $request->input() ?: null,
51
            'created_at' => Carbon::now(),
52
        ])->save();
53
54
        // Here we will see if this request hits the statistics crunching lottery by hitting
55
        // the odds needed to perform statistics crunching on any given request. If we do
56
        // hit it, we'll call this handler to let it crunch numbers and the hard work.
57
        if ($this->configHitsLottery()) {
58
            CrunchStatistics::dispatch();
59
60
            // Now let's do some garbage collection and clean old statistics requests
61
            CleanStatisticsRequests::dispatch();
62
        }
63
    }
64
65
    /**
66
     * Determine if the configuration odds hit the lottery.
67
     *
68
     * @return bool
69
     */
70
    protected function configHitsLottery(): bool
71
    {
72
        $config = config('rinvex.statistics.lottery');
73
74
        return $config ? random_int(1, $config[1]) <= $config[0] : false;
75
    }
76
}
77