Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
5 / 5
CRAP
100.00% covered (success)
100.00%
1 / 1
CachedConfig
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
5 / 5
9
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 __invoke
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 set
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 remove
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 persistConfig
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3declare(strict_types=1);
4
5/**
6 * This file is part of php-fast-forward/config.
7 *
8 * This source file is subject to the license bundled
9 * with this source code in the file LICENSE.
10 *
11 * @copyright Copyright (c) 2025-2026 Felipe SayĆ£o Lobato Abreu <github@mentordosnerds.com>
12 * @license   https://opensource.org/licenses/MIT MIT License
13 *
14 * @see       https://github.com/php-fast-forward/config
15 * @see       https://github.com/php-fast-forward
16 * @see       https://datatracker.ietf.org/doc/html/rfc2119
17 */
18
19namespace FastForward\Config;
20
21use Psr\SimpleCache\CacheInterface;
22use Psr\SimpleCache\InvalidArgumentException;
23use RuntimeException;
24
25/**
26 * Class CachedConfig.
27 *
28 * Provides a cached implementation of a configuration source.
29 * This class SHALL attempt to cache the configuration output of the decorated ConfigInterface instance.
30 * It SHALL lazily initialize and retrieve cached configuration data upon invocation.
31 */
32 class CachedConfig implements ConfigInterface
33{
34    use LazyLoadConfigTrait;
35
36    private  string $cacheKey;
37
38    private  ?int $cacheTtl;
39
40    /**
41     * Constructs a CachedConfig wrapper.
42     *
43     * This constructor SHALL accept a PSR-16 cache implementation and a configuration instance
44     * to be cached. It MUST defer reading and writing the configuration until invoked.
45     *
46     * @param CacheInterface $cache the cache implementation used for storing configuration data
47     * @param ConfigInterface $defaultConfig the configuration source to be cached
48     * @param bool $persistent whether the cache should be persistent or not
49     * @param string|null $cacheKey a shared cache key, or null for an isolated key whose entries expire after 300 seconds
50     */
51    public function __construct(
52        private  CacheInterface $cache,
53        private  ConfigInterface $defaultConfig,
54        private  bool $persistent = false,
55        ?string $cacheKey = null,
56    ) {
57        $this->cacheKey = $cacheKey ?? 'ff_config_' . bin2hex(random_bytes(16));
58        $this->cacheTtl = null === $cacheKey ? 300 : null;
59    }
60
61    /**
62     * Invokes the configuration and returns the cached configuration data.
63     *
64     * A usable cache entry MUST be returned without resolving the source. A miss or unusable entry
65     * SHALL resolve the source and attempt to cache it. A failed initial write MUST NOT discard source data.
66     * This method MUST return a ConfigInterface implementation containing the cached configuration data.
67     *
68     * @return ConfigInterface a ConfigInterface implementation containing the cached configuration data
69     *
70     * @throws InvalidArgumentException if the cache key is invalid
71     */
72    public function __invoke(): ConfigInterface
73    {
74        $data = $this->cache->get($this->cacheKey);
75        if (! \is_array($data)) {
76            $data = $this->defaultConfig->toArray();
77            $this->cache->set($this->cacheKey, $data, $this->cacheTtl);
78        }
79
80        return new ArrayConfig($data);
81    }
82
83    /**
84     * Sets configuration data.
85     *
86     * This method MUST update the cached configuration data in the cache if the persistent flag is set to true.
87     *
88     * @param array|ConfigInterface|string $key the configuration key or an array of key-value pairs to set
89     * @param mixed $value the value to set for the specified key
90     *
91     * @return void
92     *
93     * @throws InvalidArgumentException if the key is invalid
94     * @throws RuntimeException if a persistent write fails; the local change is retained
95     */
96    public function set(array|ConfigInterface|string $key, mixed $value = null): void
97    {
98        $config = $this->getConfig();
99        $config->set($key, $value);
100
101        $this->persistConfig($config);
102    }
103
104    /**
105     * Removes a configuration value by key.
106     *
107     * This method MUST update the backend when persistent mode is enabled.
108     *
109     * @param mixed $key the configuration key to remove
110     *
111     * @return void
112     *
113     * @throws InvalidArgumentException if the cache key is invalid
114     * @throws RuntimeException if a persistent write fails; the local change is retained
115     */
116    public function remove(mixed $key): void
117    {
118        $config = $this->getConfig();
119        $config->remove($key);
120
121        $this->persistConfig($config);
122    }
123
124    /**
125     * Persists a local mutation when write-through mode is enabled.
126     *
127     * @param ConfigInterface $config the locally updated configuration
128     *
129     * @return void
130     *
131     * @throws RuntimeException if the backend refuses the write
132     */
133    private function persistConfig(ConfigInterface $config): void
134    {
135        if ($this->persistent && ! $this->cache->set($this->cacheKey, $config->toArray(), $this->cacheTtl)) {
136            throw new RuntimeException('Unable to persist configuration to the cache.');
137        }
138    }
139}