QueryListener   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Importance

Changes 8
Bugs 2 Features 2
Metric Value
wmc 10
eloc 28
c 8
b 2
f 2
dl 0
loc 70
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getFromCache() 0 12 3
A putToCache() 0 13 2
A listen() 0 23 4
A getSessionKey() 0 3 1
1
<?php
2
3
namespace Socialblue\LaravelQueryAdviser\DataListener;
4
5
use Illuminate\Database\Events\QueryExecuted;
6
use Illuminate\Support\Facades\Cache;
7
use Socialblue\LaravelQueryAdviser\DataListener\Services\SessionFormatter;
8
9
class QueryListener
10
{
11
    public static function listen(QueryExecuted $query)
12
    {
13
        if (config('laravel-query-adviser.enable_query_logging') === false) {
14
            return;
15
        }
16
17
        $sessionKey = self::getSessionKey();
18
19
        if (empty($sessionKey)) {
20
            return;
21
        }
22
23
        $url = url()->current();
24
        if (str_contains($url, '/query-adviser')) {
25
            return;
26
        }
27
28
        $time = time();
29
        $data = self::getFromCache($time, $sessionKey);
30
31
        self::putToCache(
32
            (new SessionFormatter())->format($time, $data, $query),
33
            $sessionKey
34
        );
35
    }
36
37
    /**
38
     * @param $sessionKey
39
     */
40
    protected static function putToCache(array $data, $sessionKey): array
41
    {
42
        if (count($data) > config('laravel-query-adviser.cache.max_entries')) {
43
            array_shift($data);
44
        }
45
46
        Cache::put(
47
            $sessionKey,
48
            $data,
49
            config('laravel-query-adviser.cache.ttl')
50
        );
51
52
        return $data;
53
    }
54
55
    /**
56
     * @param $sessionKey
57
     * @return array|mixed
58
     */
59
    protected static function getFromCache(int $time, $sessionKey)
60
    {
61
        $data = Cache::get($sessionKey, []);
62
        if (! is_array($data)) {
63
            $data = [];
64
        }
65
66
        if (! isset($data[$time])) {
67
            $data[$time] = [];
68
        }
69
70
        return $data;
71
    }
72
73
    /**
74
     * @return \Illuminate\Config\Repository|mixed
75
     */
76
    protected static function getSessionKey()
77
    {
78
        return Cache::get(config('laravel-query-adviser.cache.session_id'), false);
79
    }
80
}
81