Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
| PersistentCacheHelperTrait | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 | |
100.00% |
1 / 1 |
| safeGetOrSet | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | /** @license For full copyright and license information, please see the LICENSE.md file. */ |
| 6 | |
| 7 | namespace App\Core\Engine\Infrastructure\Cache; |
| 8 | |
| 9 | defined('AMMONLY_APP') || exit('Direct script access is forbidden.'); |
| 10 | |
| 11 | use Yiisoft\Cache\CacheInterface; |
| 12 | |
| 13 | /** |
| 14 | * Trait providing safe cache get-or-set operations with graceful exception fallback. |
| 15 | * |
| 16 | * @package App\Core\Engine\Infrastructure\Cache |
| 17 | */ |
| 18 | trait PersistentCacheHelperTrait |
| 19 | { |
| 20 | /** |
| 21 | * Safely retrieves or sets cached metadata item with graceful fallback on cache failure. |
| 22 | * |
| 23 | * @template T |
| 24 | * @param CacheInterface $cache Cache backend implementation. |
| 25 | * @param string $key Cache key. |
| 26 | * @param callable(): T $callback Fallback generator. |
| 27 | * @param int $ttl Cache TTL in seconds. |
| 28 | * |
| 29 | * @return T Cached or newly generated metadata value. |
| 30 | */ |
| 31 | private function safeGetOrSet(CacheInterface $cache, string $key, callable $callback, int $ttl): mixed |
| 32 | { |
| 33 | try { |
| 34 | return $cache->getOrSet($key, $callback, $ttl); |
| 35 | } catch (\Throwable) { |
| 36 | return $callback(); |
| 37 | } |
| 38 | } |
| 39 | } |