aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/globalsearch/GlobalSearchCacheTrait.php
blob: adecd42e012fa80576912846f57cc36bef4a6857 (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
<?php
/**
 * Generic cache trait for search module
 *
 * @author  Jan-Hendrik Willms <tleilax+studip@gmail.com>
 * @license GPL2 or any later version
 */
trait GlobalSearchCacheTrait
{
    protected static $cache = [];

    /**
     * Convenience method for getting and setting value at once.
     * @param  string  $index     Index to look up/set
     * @param  Closure $generator Generator for the value
     * @return mixed value
     */
    protected static function fromCache($index, Closure $generator)
    {
        if (static::hasCachedItem($index)) {
            return static::getCachedItem($index);
        }

        return static::setCachedItem($index, $generator());
    }

    /**
     * Returns whether the cache has the item
     * @param  string  $index Index to look up
     * @return boolean
     */
    protected static function hasCachedItem($index)
    {
        return array_key_exists($index, static::$cache);
    }

    /**
     * Returns the cached item
     * @param  string  $index Index to look up
     * @return mixed value of item or null if not found
     */
    protected static function getCachedItem($index)
    {
        return static::hasCachedItem($index) ? static::$cache[$index] : null;
    }

    /**
     * Stored an item in cache
     * @param  string  $index Index to store
     * @param  string  $value Value to store
     * @return mixed value
     */
    protected static function setCachedItem($index, $value)
    {
        return static::$cache[$index] = $value;
    }

    /**
     * Clears the cache.
     */
    public static function clearCache()
    {
        static::$cache = [];
    }
}