HasCachedResults::getCacheKey()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 9
cts 9
cp 1
rs 9.8333
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Arcanedev\LaravelMetrics\Metrics\Concerns;
6
7
use Closure;
8
use DateInterval;
9
use Illuminate\Support\Facades\Cache;
10
use Illuminate\Support\Str;
11
12
/**
13
 * Trait     HasCachedResults
14
 *
15
 * @author   ARCANEDEV <[email protected]>
16
 */
17
trait HasCachedResults
18
{
19
    /* -----------------------------------------------------------------
20
     |  Getters
21
     | -----------------------------------------------------------------
22
     */
23
24
    /**
25
     * Get the Http request instance.
26
     *
27
     * @return \Illuminate\Http\Request
28
     */
29
    abstract public function getRequest();
30
31
    /* -----------------------------------------------------------------
32
     |  Main Methods
33
     | -----------------------------------------------------------------
34
     */
35
36
    /**
37
     * Determine for how many minutes the metric should be cached.
38
     *
39
     * @return \DateTimeInterface|\DateInterval|float|int|void
40
     */
41 124
    public function cacheFor()
42
    {
43
        //
44 124
    }
45
46
    /**
47
     * Cache the result.
48
     *
49
     * @param  mixed     $cacheFor
50
     * @param  \Closure  $callback
51
     *
52
     * @return mixed
53
     */
54 8
    protected function cacheResult($cacheFor, Closure $callback)
55
    {
56 8
        if (is_numeric($cacheFor))
57 4
            $cacheFor = new DateInterval(sprintf('PT%dS', $cacheFor * 60));
58
59 8
        return Cache::remember($this->getCacheKey(), $cacheFor, $callback);
60
    }
61
62
    /**
63
     * Get the cache's key.
64
     *
65
     * @return string
66
     */
67 8
    protected function getCacheKey(): string
68
    {
69 8
        $request = $this->getRequest();
70
71 8
        return sprintf(
72 8
            '%s.%s.%s.%s.%s',
73 8
            Str::slug($this->getCachePrefix(), '.'),
74 4
            Str::slug(str_replace('\\', '_', static::class)),
75 8
            $request->input('range', 'no-range'),
76 8
            $request->input('timezone', 'no-timezone'),
77 8
            $request->input('twelveHourTime', '24-hour-time')
78
        );
79
    }
80
81
    /**
82
     * Get the cache's prefix.
83
     *
84
     * @return string
85
     */
86 8
    protected function getCachePrefix(): string
87
    {
88 8
        return config()->get('metrics.cache.prefix', 'arcanedev.metrics');
89
    }
90
}
91