PluginProbe
User Access Manager / 2.3.12
User Access Manager v2.3.12
2.3.20 2.3.19 2.3.18 2.3.17 2.3.16 2.3.15 2.3.14 2.3.13 trunk 0.6 0.6.1 0.6.2 0.7 0.7 Beta 0.7.0.1 0.8 0.8.0.1 0.8.0.2 0.9 0.9.1 0.9.1.1 0.9.1.2 0.9.1.3 0.9.1.4 1.0 All 136 releases
user-access-manager / src / Cache / RedisCacheProvider.php

RedisCacheProvider.php in User Access Manager 2.3.12, at src/Cache/RedisCacheProvider.php

97 lines 2.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 declare(strict_types=1);
4
5 namespace UserAccessManager\Cache;
6
7 use Exception;
8 use UserAccessManager\Config\Config;
9 use UserAccessManager\Config\ConfigFactory;
10 use UserAccessManager\Config\ConfigParameterFactory;
11
12 class RedisCacheProvider implements CacheProviderInterface
13 {
14 const ID = 'RedisCacheProvider';
15 const CONFIG_KEY = 'uam_redis_cache_provider';
16 const CONFIG_PREFIX = 'redis_prefix';
17 const CONFIG_TTL = 'redis_ttl';
18 const DEFAULT_PREFIX = 'uam_cache';
19 const DEFAULT_TTL = 0;
20
21 private ?Config $config = null;
22
23 public function __construct(
24 private ConfigFactory $configFactory,
25 private ConfigParameterFactory $configParameterFactory
26 ) {
27 }
28
29 public function getId(): string
30 {
31 return self::ID;
32 }
33
34 public function init(): void
35 {
36 // WordPress object cache is already set up — nothing to initialize here.
37 }
38
39 /**
40 * @throws Exception
41 */
42 public function getConfig(): Config
43 {
44 if ($this->config === null) {
45 $this->config = $this->configFactory->createConfig(self::CONFIG_KEY);
46
47 $configParameters = [
48 self::CONFIG_PREFIX => $this->configParameterFactory->createStringConfigParameter(
49 self::CONFIG_PREFIX,
50 self::DEFAULT_PREFIX
51 ),
52 self::CONFIG_TTL => $this->configParameterFactory->createStringConfigParameter(
53 self::CONFIG_TTL,
54 (string) self::DEFAULT_TTL
55 ),
56 ];
57
58 $this->config->setDefaultConfigParameters($configParameters);
59 }
60
61 return $this->config;
62 }
63
64 private function getPrefix(): string
65 {
66 return (string) ($this->config?->getParameterValue(self::CONFIG_PREFIX) ?? self::DEFAULT_PREFIX);
67 }
68
69 private function getTtl(): int
70 {
71 return (int) ($this->config?->getParameterValue(self::CONFIG_TTL) ?? self::DEFAULT_TTL);
72 }
73
74 private function buildKey(string $key): string
75 {
76 return $this->getPrefix() . '|' . $key;
77 }
78
79 public function add(string $key, mixed $value): void
80 {
81 wp_cache_set($this->buildKey($key), $value, self::ID, $this->getTtl());
82 }
83
84 public function get(string $key): mixed
85 {
86 $value = wp_cache_get($this->buildKey($key), self::ID);
87
88 // wp_cache_get returns false on a miss; normalize to null per interface contract.
89 return ($value === false) ? null : $value;
90 }
91
92 public function invalidate(string $key): void
93 {
94 wp_cache_delete($this->buildKey($key), self::ID);
95 }
96 }
97