aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/cache/RedisCache.class.php
blob: 9ea871146222b71444b0d1c48248323c46df83d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
<?php

namespace Studip\Cache;

use BadMethodCallException;
use Config;
use DateTime;
use Exception;
use Psr\Cache\CacheItemInterface;
use Redis;
use RedisException;

/**
 * Cache implementation using redis.
 *
 * @author      Jan-Hendrik Willms <tleilax+studip@gmail.com>
 * @license     GPL2 or any later version
 * @package     studip
 * @subpackage  cache
 * @since       Stud.IP 5.0
 */
class RedisCache extends Cache
{
    use KeyTrait;

    private $redis;

    /**
     * @return string A translateable display name for this cache class.
     */
    public static function getDisplayName(): string
    {
        return _('Redis');
    }

    /**
     * Construct a cache instance.
     *
     * @param string $hostname Hostname of redis server
     * @param int    $port     Port of redis server
     * @param string $auth     Optional auth token/password
     *
     * @throws RedisException
     */
    public function __construct($hostname, $port, string $auth = '')
    {
        if (!extension_loaded('redis')) {
            throw new Exception('Redis extension missing.');
        }

        $this->redis = new Redis();
        $status = $this->redis->connect($hostname, $port, 1);

        if (!$status) {
            throw new Exception('Could not add cache.');
        }

        if ($auth !== '') {
            $this->redis->auth($auth);
        }
    }

    /**
     * Returns the instance of the redis server connection.
     *
     * @return Redis instance
     */
    public function getRedis()
    {
        return $this->redis;
    }

    /**
     * Expire item from the cache.
     *
     * Example:
     *
     *   # expires foo
     *   $cache->expire('foo');
     *
     * @param   string $arg a single key.
     */
    public function expire($arg)
    {
        $key = $this->getCacheKey($arg);
        $this->redis->unlink($key);
    }

    /**
     * Expire all items from the cache.
     */
    public function flush()
    {
        $pattern = $this->getCacheKey('*');
        foreach ($this->redis->keys($pattern) as $key) {
            $this->redis->unlink($key);
        }
    }

    /**
     * @param string $method Method to call
     * @param array $args Arguments to pass
     * @return false|mixed
     */
    public function __call($method, $args)
    {
        if (is_callable([$this->redis, $method])) {
            return call_user_func_array([$this->redis, $method], $args);
        }
        throw new BadMethodCallException("Method {$method} does not exist");
    }

    /**
     * Return statistics.
     *
     * @StudipCache::getStats()
     *
     * @return array|array[]
     */
    public function getStats(): array
    {
        $stats = $this->redis->info();
        $stats['size'] = count($this->redis->keys($this->getCacheKey('*')));
        return ["{$this->redis->getHost()}:{$this->redis->getPort()}" => $stats];
    }

    /*
     * Return the Vue component name and props that handle configuration.
     *
     * @see StudipCache::getConfig()
     *
     * @return array
     */
    public static function getConfig(): array
    {
        $currentCache = Config::get()->SYSTEMCACHE;

        // Set default config for this cache
        $currentConfig = [
            'hostname' => '',
            'port' => null
        ];

        // If this cache is set as system cache, use config from global settings.
        if ($currentCache['type'] == __CLASS__) {
            $currentConfig = $currentCache['config'];
            $currentConfig['port'] = $currentConfig['port'] ? (int) $currentConfig['port'] : null;
        }

        return [
            'component' => 'RedisCacheConfig',
            'props' => $currentConfig
        ];
    }

    /**
     * @inheritDoc
     */
    public function getItem($key)
    {
        $item = new Item($key);
        $real_key = $this->getCacheKey($key);
        $result = $this->redis->get($real_key);
        if ($result === null) {
            return $item;
        }
        $item->setHit();
        $item->set(unserialize($result));
        $expiration = new DateTime();
        $expiration->setTimestamp($this->redis->expiretime($real_key));
        $item->expiresAt($expiration);
        return $item;
    }

    /**
     * @inheritDoc
     */
    public function hasItem($key)
    {
        $real_key = $this->getCacheKey($key);
        return $this->redis->get($real_key) !== null;
    }

    /**
     * @inheritDoc
     */
    public function save(CacheItemInterface $item)
    {
        $expiration = $this->getExpiration($item);
        if ($expiration < 1) {
            // The item would expire immediately.
            return false;
        }

        $real_key = $this->getCacheKey($item->getKey());
        return $this->redis->setEx($real_key, $expiration, serialize($item->get()));
    }
}