Test Setup Failed
Push — master ( d37a6a...512c0e )
by Carlos
03:19
created

Caches::getCache()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Trait Caches.php.
4
 *
5
 * Part of Overtrue\WeChat.
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @author    lixiao <[email protected]>
11
 * @copyright 2016
12
 *
13
 * @see      https://github.com/overtrue
14
 * @see      http://overtrue.me
15
 */
16
17
namespace EasyWeChat\OpenPlatform\Traits;
18
19
use Doctrine\Common\Cache\Cache;
20
use Doctrine\Common\Cache\FilesystemCache;
21
22
trait Caches
23
{
24
    /**
25
     * @var Cache
26
     */
27
    protected $cache;
28
29
    /**
30
     * Sets cache store.
31
     *
32
     * @param Cache $cache
33
     *
34
     * @return $this
35
     */
36
    public function setCache(Cache $cache)
37
    {
38
        $this->cache = $cache;
39
40
        return $this;
41
    }
42
43
    /**
44
     * Gets cache store. Defaults to file system in system temp folder.
45
     *
46
     * @return Cache
47
     */
48
    public function getCache()
49
    {
50
        return $this->cache ?: $this->cache = new FilesystemCache(sys_get_temp_dir());
51
    }
52
53
    /**
54
     * Gets the cached data.
55
     *
56
     * @param string $key
57
     * @param mixed $default A default value or a callable to return the value.
58
     *
59
     * @return mixed
60
     */
61
    public function get($key, $default = null)
62
    {
63
        if ($cached = $this->getCache()->fetch($key)) {
64
            return $cached;
65
        }
66
67
        if (is_callable($default)) {
68
            return $default();
69
        }
70
71
        return $default;
72
    }
73
74
    /**
75
     * Sets the cached data.
76
     *
77
     * @param string $key
78
     * @param mixed $value
79
     * @param int $life Cache life time in seconds.
80
     *
81
     * @return bool
82
     */
83
    public function set($key, $value, $life = 0)
84
    {
85
        return $this->getCache()->save($key, $value, $life);
86
    }
87
88
    /**
89
     * Removes the cached data.
90
     *
91
     * @param string $key
92
     *
93
     * @return bool
94
     */
95
    public function remove($key)
96
    {
97
        return $this->getCache()->delete($key);
98
    }
99
100
}