aboutsummaryrefslogtreecommitdiff
path: root/lib/Cache.php
diff options
context:
space:
mode:
Diffstat (limited to 'lib/Cache.php')
-rw-r--r--lib/Cache.php73
1 files changed, 73 insertions, 0 deletions
diff --git a/lib/Cache.php b/lib/Cache.php
index a0d2ac77..6826d4cc 100644
--- a/lib/Cache.php
+++ b/lib/Cache.php
@@ -64,6 +64,8 @@ class Cache {
* @return object|bool The cache object or false if the class is not instantiable.
*/
public static function create($name){
+ $name = self::sanitizeCacheName($name) . 'Cache';
+
if(!self::isCacheName($name)) {
throw new \InvalidArgumentException('Cache name invalid!');
}
@@ -137,4 +139,75 @@ class Cache {
public static function isCacheName($name){
return is_string($name) && preg_match('/^[A-Z][a-zA-Z0-9-]*$/', $name) === 1;
}
+
+ /**
+ * Returns a list of cache names from the working directory.
+ *
+ * The list is cached internally to allow for successive calls.
+ *
+ * @return array List of cache names
+ */
+ public static function getCacheNames(){
+
+ static $cacheNames = array(); // Initialized on first call
+
+ if(empty($cacheNames)) {
+ $files = scandir(self::getWorkingDir());
+
+ if($files !== false) {
+ foreach($files as $file) {
+ if(preg_match('/^([^.]+)Cache\.php$/U', $file, $out)) {
+ $cacheNames[] = $out[1];
+ }
+ }
+ }
+ }
+
+ return $cacheNames;
+ }
+
+ /**
+ * Returns the sanitized cache name.
+ *
+ * The cache name can be specified in various ways:
+ * * The PHP file name (i.e. `FileCache.php`)
+ * * The PHP file name without file extension (i.e. `FileCache`)
+ * * The cache name (i.e. `file`)
+ *
+ * Casing is ignored (i.e. `FILE` and `fIlE` are the same).
+ *
+ * A cache file matching the given cache name must exist in the working
+ * directory!
+ *
+ * @param string $name The cache name
+ * @return string|null The sanitized cache name if the provided name is
+ * valid, null otherwise.
+ */
+ protected static function sanitizeCacheName($name) {
+
+ if(is_string($name)) {
+
+ // Trim trailing '.php' if exists
+ if(preg_match('/(.+)(?:\.php)/', $name, $matches)) {
+ $name = $matches[1];
+ }
+
+ // Trim trailing 'Cache' if exists
+ if(preg_match('/(.+)(?:Cache)/i', $name, $matches)) {
+ $name = $matches[1];
+ }
+
+ // The name is valid if a corresponding file is found on disk
+ if(in_array(strtolower($name), array_map('strtolower', self::getCacheNames()))) {
+ $index = array_search(strtolower($name), array_map('strtolower', self::getCacheNames()));
+ return self::getCacheNames()[$index];
+ }
+
+ Debug::log('Invalid cache name specified: "' . $name . '"!');
+
+ }
+
+ return null; // Bad parameter
+
+ }
}