Test Setup Failed
Push — master ( 90378d...afbbde )
by Gabriel
06:45
created

CanCache::checkSaveCache()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 8
ccs 0
cts 6
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Nip\Cache\Cacheable;
4
5
use DateInterval;
6
use Nip\Utility\Str;
7
8
/**
9
 * Trait CanCache
10
 * @package Nip\Cache\Cacheable
11
 */
12
trait CanCache
13
{
14
    use HasCacheStore;
15
16
    protected $needsCaching = false;
17
18
    /**
19
     * @param null $needCaching
20
     * @return bool
21
     */
22
    public function needsCaching($needCaching = null): bool
23
    {
24
        if (is_bool($needCaching)) {
25
            $this->needsCaching = $needCaching;
26
        }
27
        return $this->needsCaching;
28
    }
29
30
    protected function checkSaveCache()
31
    {
32
        if ($this->needsCaching() !== true) {
33
            return;
34
        }
35
        $data = $this->generateCacheData();
36
        $this->saveDataToCache($data);
37
    }
38
39
    abstract function generateCacheData();
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
40
41
    /**
42
     * @param null $key
43
     * @return mixed|null
44
     * @throws \Psr\SimpleCache\InvalidArgumentException
45
     */
46
    protected function getDataFromCache($key = null)
47
    {
48
        return $this->cacheStore()->get($this->dataCacheKey($key));
49
    }
50
51
    /**
52
     * @param $data
53
     * @param null $key
54
     * @noinspection PhpDocMissingThrowsInspection
55
     */
56
    protected function saveDataToCache($data, $key = null)
57
    {
58
        /** @noinspection PhpUnhandledExceptionInspection */
59
        $this->cacheStore()->set($this->dataCacheKey($key), $data,$this->dataCacheTtl($key));
60
    }
61
62
    /**
63
     * @param $key
64
     * @return string
65
     */
66
    protected function dataCacheKey($key= null)
67
    {
68
        if ($key !== null) {
69
            return $key;
70
        }
71
        return Str::slug(__CLASS__);
72
    }
73
74
    /**
75
     * @param null $key
76
     * @return DateInterval
77
     */
78
    protected function dataCacheTtl($key= null)
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
79
    {
80
        return DateInterval::createFromDateString('10 years');
81
    }
82
}