aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/StudipMemoryCache.class.php
blob: 3946b345477ac93871ac0fa70a8f2e4a36171063 (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
<?php
/**
 * The php memory implementation of the StudipCache interface.
 *
 * @author  Jan-Hendrik Willms <tleilax+studip@gmail.com>
 * @license GPL2 or any later version
 * @since   Stud.IP 5.0
 */
class StudipMemoryCache implements StudipCache
{
    protected $memory_cache = [];

    /**
     * Expires just a single key.
     *
     * @param  string  the key
     */
    public function expire($key)
    {
        unset($this->memory_cache[$key]);
    }

    /**
     * Expire all items from the cache.
     */
    public function flush()
    {
        $this->memory_cache = [];
    }

    /**
     * Reads just a single key from the cache.
     *
     * @param  string  the key
     *
     * @return mixed   the corresponding value
     */
    public function read($key)
    {
        if (!isset($this->memory_cache[$key])) {
            return false;
        }
        if ($this->memory_cache[$key]['expires'] < time()) {
            $this->expire($key);
            return false;
        }
        return $this->memory_cache[$key]['data'];
    }

    /**
     * Store data at the server.
     *
     * @param string   the item's key.
     * @param mixed    the item's content (will be serialized if necessary).
     * @param int      the item's expiry time in seconds. Defaults to 12h.
     *
     * @returns mixed  returns TRUE on success or FALSE on failure.
     *
     */
    public function write($name, $content, $expire = self::DEFAULT_EXPIRATION)
    {
        $this->memory_cache[$name] = [
            'expires' => time() + $expire,
            'data'    => $content,
        ];
    }
}