CacheableTrait::setRepository()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php namespace Valeryq\Cacheable\Traits;
2
3
use Closure;
4
use Illuminate\Contracts\Cache\Repository;
5
6
/**
7
 * Class CacheableTrait
8
 * @package Valeryq\Cacheable\Traits
9
 */
10
trait CacheableTrait
11
{
12
    /**
13
     * Force by default is false
14
     *
15
     * @var bool
16
     */
17
    private $force = false;
18
19
    /**
20
     * @var Repository
21
     */
22
    private $repository;
23
24
    /**
25
     * Check if force is on or off
26
     *
27
     * @return boolean
28
     */
29
    public function isForce()
30
    {
31
        return $this->force;
32
    }
33
34
    /**
35
     * Set flag as get a data. If with force it will without cached
36
     *
37
     * @param boolean $force
38
     *
39
     * @return $this
40
     */
41
    public function setForce($force)
42
    {
43
        $this->force = $force;
44
45
        return $this;
46
    }
47
48
    /**
49
     * Set cache repository
50
     *
51
     * @param Repository $repository
52
     */
53
    public function setRepository(Repository $repository)
54
    {
55
        $this->repository = $repository;
56
    }
57
58
    /**
59
     * Get cache repository
60
     *
61
     * @return Repository
62
     */
63
    public function cache()
64
    {
65
        if (!$this->repository) {
66
            $this->repository = app(Repository::class);
67
        }
68
69
        return $this->repository;
70
    }
71
72
    /**
73
     * Get an item from the cache, or store the default value.
74
     *
75
     * @param  string $key
76
     * @param  \DateTime|int $minutes
77
     * @param  \Closure $callback
78
     *
79
     * @return mixed
80
     */
81
    public function remember($key, $minutes, Closure $callback)
82
    {
83
        if ($this->isForce()) {
84
            return $callback();
85
        }
86
87
        return $this->cache()->remember($key, $minutes, $callback);
88
    }
89
90
    /**
91
     * Get an item from the cache, or store the default value forever.
92
     *
93
     * @param  string $key
94
     * @param \Closure $callback
95
     *
96
     * @return mixed
97
     */
98
    public function rememberForever($key, Closure $callback)
99
    {
100
        if ($this->isForce()) {
101
            return $callback();
102
        }
103
104
        return $this->cache()->rememberForever($key, $callback);
105
    }
106
}
107