2013-08-11 13:30:41 +02:00
|
|
|
<?php
|
2022-07-01 15:10:30 +02:00
|
|
|
|
2023-02-15 21:22:37 +01:00
|
|
|
declare(strict_types=1);
|
2018-11-06 19:23:32 +01:00
|
|
|
|
2022-06-22 18:29:28 +02:00
|
|
|
class CacheFactory
|
|
|
|
{
|
2022-07-05 13:20:01 +02:00
|
|
|
public function create(string $name = null): CacheInterface
|
2022-06-22 18:29:28 +02:00
|
|
|
{
|
2022-07-05 13:20:01 +02:00
|
|
|
$name ??= Configuration::getConfig('cache', 'type');
|
2023-02-15 21:22:37 +01:00
|
|
|
if (!$name) {
|
|
|
|
throw new \Exception('No cache type configured');
|
2016-09-10 20:41:11 +02:00
|
|
|
}
|
2023-02-15 21:22:37 +01:00
|
|
|
$cacheNames = [];
|
|
|
|
foreach (scandir(PATH_LIB_CACHES) as $file) {
|
|
|
|
if (preg_match('/^([^.]+)Cache\.php$/U', $file, $m)) {
|
|
|
|
$cacheNames[] = $m[1];
|
|
|
|
}
|
2016-09-10 20:41:11 +02:00
|
|
|
}
|
2022-06-22 18:29:28 +02:00
|
|
|
// Trim trailing '.php' if exists
|
|
|
|
if (preg_match('/(.+)(?:\.php)/', $name, $matches)) {
|
|
|
|
$name = $matches[1];
|
2019-02-06 18:52:44 +01:00
|
|
|
}
|
2022-06-22 18:29:28 +02:00
|
|
|
// Trim trailing 'Cache' if exists
|
|
|
|
if (preg_match('/(.+)(?:Cache)$/i', $name, $matches)) {
|
|
|
|
$name = $matches[1];
|
2019-02-06 18:52:44 +01:00
|
|
|
}
|
2023-03-06 21:50:40 +01:00
|
|
|
|
|
|
|
$index = array_search(strtolower($name), array_map('strtolower', $cacheNames));
|
|
|
|
if ($index === false) {
|
2023-02-15 21:22:37 +01:00
|
|
|
throw new \InvalidArgumentException(sprintf('Invalid cache name: "%s"', $name));
|
|
|
|
}
|
2023-03-06 21:50:40 +01:00
|
|
|
$className = $cacheNames[$index] . 'Cache';
|
|
|
|
if (!preg_match('/^[A-Z][a-zA-Z0-9-]*$/', $className)) {
|
|
|
|
throw new \InvalidArgumentException(sprintf('Invalid cache classname: "%s"', $className));
|
2022-06-22 18:29:28 +02:00
|
|
|
}
|
2023-03-06 21:50:40 +01:00
|
|
|
|
|
|
|
switch ($className) {
|
|
|
|
case NullCache::class:
|
|
|
|
return new NullCache();
|
|
|
|
case FileCache::class:
|
|
|
|
return new FileCache([
|
|
|
|
'enable_purge' => Configuration::getConfig('FileCache', 'enable_purge'),
|
|
|
|
]);
|
|
|
|
case SQLiteCache::class:
|
|
|
|
return new SQLiteCache();
|
|
|
|
case MemcachedCache::class:
|
|
|
|
return new MemcachedCache();
|
|
|
|
default:
|
|
|
|
if (!file_exists(PATH_LIB_CACHES . $className . '.php')) {
|
|
|
|
throw new \Exception('Unable to find the cache file');
|
|
|
|
}
|
|
|
|
return new $className();
|
2023-02-15 21:22:37 +01:00
|
|
|
}
|
2019-02-06 18:52:44 +01:00
|
|
|
}
|
2015-12-04 09:19:05 +00:00
|
|
|
}
|