Commit | Line | Data |
---|---|---|
92ee7b19 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
4 | | Copyright CiviCRM LLC. All rights reserved. | | |
5 | | | | |
6 | | This work is published under the GNU AGPLv3 license with some | | |
7 | | permitted exceptions and without any warranty. For full license | | |
8 | | and copyright information, see https://civicrm.org/licensing | | |
9 | +--------------------------------------------------------------------+ | |
10 | */ | |
11 | ||
12 | /** | |
13 | */ | |
14 | class CRM_Extension_BootCache { | |
15 | ||
16 | protected $locked = FALSE; | |
17 | ||
18 | protected $data; | |
19 | ||
20 | /** | |
21 | * Define a persistent value in the extension's boot-cache. | |
22 | * | |
23 | * This value is retained as part of the boot-cache. It will be loaded | |
24 | * very quickly (eg via php op-code caching). However, as a trade-off, | |
25 | * you will not be able to change/reset at runtime - it will only | |
26 | * reset in response to a system-wide flush or redeployment. | |
27 | * | |
28 | * Ex: $mix->define('initTime', function() { return time(); }); | |
29 | * | |
30 | * @param string $key | |
31 | * @param mixed $callback | |
32 | * @return mixed | |
33 | * The value of $callback (either cached or fresh) | |
34 | */ | |
35 | public function define($key, $callback) { | |
36 | if (!isset($this->data[$key])) { | |
37 | $this->set($key, $callback($this)); | |
38 | } | |
39 | return $this->data[$key]; | |
40 | } | |
41 | ||
42 | /** | |
43 | * Determine if $key has been set. | |
44 | * | |
45 | * @param string $key | |
46 | * @return bool | |
47 | */ | |
48 | public function has($key) { | |
49 | return isset($this->data[$key]); | |
50 | } | |
51 | ||
52 | /** | |
53 | * Get the value of $key. | |
54 | * | |
55 | * @param string $key | |
56 | * @param mixed $default | |
57 | * @return mixed | |
58 | */ | |
59 | public function get($key, $default = NULL) { | |
60 | return $this->data[$key] ?? $default; | |
61 | } | |
62 | ||
63 | /** | |
64 | * Set a value in the cache. | |
65 | * | |
66 | * This operation is only valid on the first page-load when a cache is built. | |
67 | * | |
68 | * @param string $key | |
69 | * @param mixed $value | |
70 | * @return static | |
71 | * @throws \Exception | |
72 | */ | |
73 | public function set($key, $value) { | |
74 | if ($this->locked) { | |
75 | throw new \Exception("Cannot modify a locked boot-cache."); | |
76 | } | |
77 | $this->data[$key] = $value; | |
78 | return $this; | |
79 | } | |
80 | ||
81 | public function lock() { | |
82 | $this->locked = TRUE; | |
83 | } | |
84 | ||
85 | } |