Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
NamespacedVersionedKeys
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
3 / 3
4
100.00% covered (success)
100.00%
1 / 1
 fetchVersion
n/a
0 / 0
n/a
0 / 0
0
 versionKey
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 resolveVersion
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 key
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2declare(strict_types=1);
3/**
4 * Pop PHP Framework (https://www.popphp.org/)
5 *
6 * @link       https://github.com/popphp/popphp-framework
7 * @author     Nick Sagona, III <nick@popphp.org>
8 * @copyright  Copyright (c) 2009-2026 Nick Sagona, III
9 * @license    https://www.popphp.org/license     New BSD License
10 */
11
12/**
13 * @namespace
14 */
15namespace Pop\Cache\Adapter;
16
17/**
18 * Shared namespace/version key-building for adapters that scope clear()/destroy() to a namespace via
19 * generational versioning (Apc, Memcached, Redis) rather than wiping the whole shared backend
20 *
21 * Using classes must have a `protected string $namespace` property and implement fetchVersion() to read
22 * the raw version value back from their own backend.
23 *
24 * @category   Pop
25 * @package    Pop\Cache
26 * @author     Nick Sagona, III <nick@popphp.org>
27 * @copyright  Copyright (c) 2009-2026 Nick Sagona, III
28 * @license    https://www.popphp.org/license     New BSD License
29 * @version    5.0.0
30 */
31trait NamespacedVersionedKeys
32{
33
34    /**
35     * Fetch the raw version value from the backend, or false if it isn't set
36     *
37     * @param  string $key
38     * @return mixed
39     */
40    abstract protected function fetchVersion(string $key): mixed;
41
42    /**
43     * Get the storage key for this namespace's version counter
44     *
45     * @return string
46     */
47    protected function versionKey(): string
48    {
49        return $this->namespace . '::version';
50    }
51
52    /**
53     * Resolve the current version for this namespace, defaulting to 1
54     *
55     * @return int
56     */
57    protected function resolveVersion(): int
58    {
59        $version = $this->fetchVersion($this->versionKey());
60        return ($version !== false) ? (int)$version : 1;
61    }
62
63    /**
64     * Build the versioned, namespaced storage key for an item id
65     *
66     * @param  string $id
67     * @return string
68     */
69    protected function key(string $id): string
70    {
71        return $this->namespace . ':v' . $this->resolveVersion() . ':' . sha1($id);
72    }
73
74}