3
declare(strict_types=1);
6
* This file is part of CodeIgniter 4 framework.
8
* (c) CodeIgniter Foundation <admin@codeigniter.com>
10
* For the full copyright and license information, please view
11
* the LICENSE file that was distributed with this source code.
14
namespace CodeIgniter\Cache;
16
use CodeIgniter\Cache\Exceptions\CacheException;
17
use CodeIgniter\Exceptions\CriticalError;
18
use CodeIgniter\Test\Mock\MockCache;
22
* A factory for loading the desired
24
* @see \CodeIgniter\Cache\CacheFactoryTest
29
* The class to use when mocking
33
public static $mockClass = MockCache::class;
36
* The service to inject the mock as
40
public static $mockServiceName = 'cache';
43
* Attempts to create the desired cache handler, based upon the
45
* @param non-empty-string|null $handler
46
* @param non-empty-string|null $backup
48
* @return CacheInterface
50
public static function getHandler(Cache $config, ?string $handler = null, ?string $backup = null)
52
if (! isset($config->validHandlers) || $config->validHandlers === []) {
53
throw CacheException::forInvalidHandlers();
56
if (! isset($config->handler) || ! isset($config->backupHandler)) {
57
throw CacheException::forNoBackup();
60
$handler ??= $config->handler;
61
$backup ??= $config->backupHandler;
63
if (! array_key_exists($handler, $config->validHandlers) || ! array_key_exists($backup, $config->validHandlers)) {
64
throw CacheException::forHandlerNotFound();
67
$adapter = new $config->validHandlers[$handler]($config);
69
if (! $adapter->isSupported()) {
70
$adapter = new $config->validHandlers[$backup]($config);
72
if (! $adapter->isSupported()) {
73
// Fall back to the dummy adapter.
74
$adapter = new $config->validHandlers['dummy']();
78
// If $adapter->initialization throws a CriticalError exception, we will attempt to
79
// use the $backup handler, if that also fails, we resort to the dummy handler.
81
$adapter->initialize();
82
} catch (CriticalError $e) {
83
log_message('critical', $e . ' Resorting to using ' . $backup . ' handler.');
85
// get the next best cache handler (or dummy if the $backup also fails)
86
$adapter = self::getHandler($config, $backup, 'dummy');