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