aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/cache/MemoryCache.php
blob: 7c00753ea9a187ca5543ece8bb9ee7d7b3df1ad9 (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
<?php

namespace Studip\Cache;

use DateTime;
use Psr\Cache\CacheItemInterface;

/**
 * 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 MemoryCache extends Cache
{
    protected array $memory_cache = [];

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

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

    public static function getDisplayName(): string
    {
        return 'Memory cache';
    }

    public function getStats(): array
    {
        return [];
    }

    public static function getConfig(): array
    {
        return [];
    }

    /**
     * @inheritDoc
     */
    public function getItem(string $key): CacheItemInterface
    {
        $item = new Item($key);
        if (!isset($this->memory_cache[$key])) {
            return $item;
        }
        if ($this->memory_cache[$key]['expires'] < time()) {
            $this->expire($key);
            return $item;
        }
        $item->setHit();
        $item->set($this->memory_cache[$key]['data']);
        if (!empty($this->memory_cache[$key]['expires'])) {
            $expiration = new DateTime();
            $expiration->setTimestamp($this->memory_cache[$key]['expires']);
            $item->expiresAt($expiration);
        }
        return $item;
    }

    /**
     * @inheritDoc
     */
    public function hasItem(string $key): bool
    {
        return isset($this->memory_cache[$key])
            && $this->memory_cache[$key]['expires'] < time();
    }

    /**
     * @inheritDoc
     */
    public function save(CacheItemInterface $item): bool
    {
        $expiration = $this->getExpiration($item);

        $this->memory_cache[$item->getKey()] = [
            'expires' => $expiration + time(),
            'data'    => $item->get(),
        ];

        return true;
    }
}