ResultCache::get()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 10
ccs 5
cts 5
cp 1
crap 2
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
namespace Tequilarapido\ResultCache;
4
5
use Illuminate\Contracts\Cache\Repository as CacheRepository;
6
7
abstract class ResultCache
8
{
9
    /** @var int */
10
    protected $minutes = 1440;
11
12
    /** @var CacheRepository */
13
    protected $cache;
14
15
    /**
16
     * Return / defines a unique cache key across the application.
17
     *
18
     * @return string
19
     */
20
    abstract public function key();
21
22
    /**
23
     * This methods must is responsible for returning the data
24
     * that will be saved in cache.
25
     *
26
     * @return mixed
27
     */
28
    abstract public function data();
29
30
    /**
31
     * Return concrete used cache key.
32
     *
33
     * @return string
34
     */
35 4
    protected function getCacheKey()
36
    {
37 4
        return $this->key();
38
    }
39
40
    /**
41
     * Return object from the cache.
42
     *
43
     * @return mixed
44
     */
45 7
    public function get()
46
    {
47 7
        if ($this->getCache()->has($key = $this->getCacheKey())) {
48 2
            return $this->getCache()->get($key);
49
        }
50
51 7
        $this->getCache()->put($key, $data = $this->data(), $this->minutes);
52
53 7
        return $data;
54
    }
55
56
    /**
57
     * Removes cache.
58
     *
59
     * @return void
60
     */
61 1
    public function forget()
62
    {
63 1
        $this->getCache()->forget($this->getCacheKey());
64 1
    }
65
66
    /**
67
     * Set cache repository.
68
     *
69
     * @param CacheRepository $cache
70
     *
71
     * @return $this
72
     */
73 1
    public function setCache(CacheRepository $cache)
74
    {
75 1
        $this->cache = $cache;
76
77 1
        return $this;
78
    }
79
80
    /**
81
     * Return cache implementation.
82
     *
83
     * @return CacheRepository
84
     */
85 8
    public function getCache()
86
    {
87 8
        return $this->cache ?: app(CacheRepository::class);
88
    }
89
}
90