group = $group; } if ($defaultTtl !== null) { $this->defaultTtl = $defaultTtl; } } public static function store(?string $group = null): self { return new self($group); } public function has(string $key): bool { $found = false; wp_cache_get($key, $this->group, false, $found); return (bool) $found; } /** * @param mixed $default * @return mixed */ public function get(string $key, $default = null) { $found = false; $value = wp_cache_get($key, $this->group, false, $found); if ($found) { return $value; } return $default instanceof \Closure ? $default() : $default; } /** * @param mixed $value */ public function put(string $key, $value, ?int $ttl = null): bool { return wp_cache_set($key, $value, $this->group, $ttl ?? $this->defaultTtl); } public function set(string $key, $value, ?int $ttl = null): bool { return $this->put($key, $value, $ttl); } /** * Store only if the key is not already present. * * @param mixed $value */ public function add(string $key, $value, ?int $ttl = null): bool { if ($this->has($key)) { return false; } return $this->put($key, $value, $ttl); } public function forever(string $key, $value): bool { return $this->put($key, $value, 0); } /** * Return the cached value or compute, store, and return it. * * @return mixed */ public function remember(string $key, callable $callback, ?int $ttl = null) { $found = false; $value = wp_cache_get($key, $this->group, false, $found); if ($found) { return $value; } $value = $callback(); $this->put($key, $value, $ttl); return $value; } public function rememberForever(string $key, callable $callback) { return $this->remember($key, $callback, 0); } /** * Retrieve and delete a key in one call. * * @param mixed $default * @return mixed */ public function pull(string $key, $default = null) { $value = $this->get($key, self::MISS); if ($value === self::MISS) { return $default instanceof \Closure ? $default() : $default; } $this->forget($key); return $value; } public function increment(string $key, int $by = 1) { return wp_cache_incr($key, $by, $this->group); } public function decrement(string $key, int $by = 1) { return wp_cache_decr($key, $by, $this->group); } public function forget(string $key): bool { return wp_cache_delete($key, $this->group); } /** * Flush this cache group. Returns false when the object cache cannot flush * a single group (WordPress < 6.1, or a drop-in without support): wiping * the whole site's cache from one plugin is never done implicitly. */ public function flush(): bool { if (!function_exists('wp_cache_flush_group')) { return false; } if (function_exists('wp_cache_supports') && !wp_cache_supports('flush_group')) { return false; } return wp_cache_flush_group($this->group); } }