Initial
This commit is contained in:
84
system/Cache/CacheFactory.php
Normal file
84
system/Cache/CacheFactory.php
Normal file
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Cache;
|
||||
|
||||
use CodeIgniter\Cache\Exceptions\CacheException;
|
||||
use CodeIgniter\Exceptions\CriticalError;
|
||||
use CodeIgniter\Test\Mock\MockCache;
|
||||
use Config\Cache;
|
||||
|
||||
/**
|
||||
* A factory for loading the desired
|
||||
*/
|
||||
class CacheFactory
|
||||
{
|
||||
/**
|
||||
* The class to use when mocking
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public static $mockClass = MockCache::class;
|
||||
|
||||
/**
|
||||
* The service to inject the mock as
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public static $mockServiceName = 'cache';
|
||||
|
||||
/**
|
||||
* Attempts to create the desired cache handler, based upon the
|
||||
*
|
||||
* @return CacheInterface
|
||||
*/
|
||||
public static function getHandler(Cache $config, ?string $handler = null, ?string $backup = null)
|
||||
{
|
||||
if (! isset($config->validHandlers) || ! is_array($config->validHandlers)) {
|
||||
throw CacheException::forInvalidHandlers();
|
||||
}
|
||||
|
||||
if (! isset($config->handler) || ! isset($config->backupHandler)) {
|
||||
throw CacheException::forNoBackup();
|
||||
}
|
||||
|
||||
$handler = ! empty($handler) ? $handler : $config->handler;
|
||||
$backup = ! empty($backup) ? $backup : $config->backupHandler;
|
||||
|
||||
if (! array_key_exists($handler, $config->validHandlers) || ! array_key_exists($backup, $config->validHandlers)) {
|
||||
throw CacheException::forHandlerNotFound();
|
||||
}
|
||||
|
||||
$adapter = new $config->validHandlers[$handler]($config);
|
||||
|
||||
if (! $adapter->isSupported()) {
|
||||
$adapter = new $config->validHandlers[$backup]($config);
|
||||
|
||||
if (! $adapter->isSupported()) {
|
||||
// Fall back to the dummy adapter.
|
||||
$adapter = new $config->validHandlers['dummy']();
|
||||
}
|
||||
}
|
||||
|
||||
// If $adapter->initialization throws a CriticalError exception, we will attempt to
|
||||
// use the $backup handler, if that also fails, we resort to the dummy handler.
|
||||
try {
|
||||
$adapter->initialize();
|
||||
} catch (CriticalError $e) {
|
||||
log_message('critical', $e->getMessage() . ' Resorting to using ' . $backup . ' handler.');
|
||||
|
||||
// get the next best cache handler (or dummy if the $backup also fails)
|
||||
$adapter = self::getHandler($config, $backup, 'dummy');
|
||||
}
|
||||
|
||||
return $adapter;
|
||||
}
|
||||
}
|
||||
106
system/Cache/CacheInterface.php
Normal file
106
system/Cache/CacheInterface.php
Normal file
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Cache;
|
||||
|
||||
/**
|
||||
* Cache interface
|
||||
*/
|
||||
interface CacheInterface
|
||||
{
|
||||
/**
|
||||
* Takes care of any handler-specific setup that must be done.
|
||||
*/
|
||||
public function initialize();
|
||||
|
||||
/**
|
||||
* Attempts to fetch an item from the cache store.
|
||||
*
|
||||
* @param string $key Cache item name
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function get(string $key);
|
||||
|
||||
/**
|
||||
* Saves an item to the cache store.
|
||||
*
|
||||
* @param string $key Cache item name
|
||||
* @param mixed $value The data to save
|
||||
* @param int $ttl Time To Live, in seconds (default 60)
|
||||
*
|
||||
* @return bool Success or failure
|
||||
*/
|
||||
public function save(string $key, $value, int $ttl = 60);
|
||||
|
||||
/**
|
||||
* Deletes a specific item from the cache store.
|
||||
*
|
||||
* @param string $key Cache item name
|
||||
*
|
||||
* @return bool Success or failure
|
||||
*/
|
||||
public function delete(string $key);
|
||||
|
||||
/**
|
||||
* Performs atomic incrementation of a raw stored value.
|
||||
*
|
||||
* @param string $key Cache ID
|
||||
* @param int $offset Step/value to increase by
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function increment(string $key, int $offset = 1);
|
||||
|
||||
/**
|
||||
* Performs atomic decrementation of a raw stored value.
|
||||
*
|
||||
* @param string $key Cache ID
|
||||
* @param int $offset Step/value to increase by
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function decrement(string $key, int $offset = 1);
|
||||
|
||||
/**
|
||||
* Will delete all items in the entire cache.
|
||||
*
|
||||
* @return bool Success or failure
|
||||
*/
|
||||
public function clean();
|
||||
|
||||
/**
|
||||
* Returns information on the entire cache.
|
||||
*
|
||||
* The information returned and the structure of the data
|
||||
* varies depending on the handler.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getCacheInfo();
|
||||
|
||||
/**
|
||||
* Returns detailed information about the specific item in the cache.
|
||||
*
|
||||
* @param string $key Cache item name.
|
||||
*
|
||||
* @return array|false|null
|
||||
* Returns null if the item does not exist, otherwise array<string, mixed>
|
||||
* with at least the 'expire' key for absolute epoch expiry (or null).
|
||||
* Some handlers may return false when an item does not exist, which is deprecated.
|
||||
*/
|
||||
public function getMetaData(string $key);
|
||||
|
||||
/**
|
||||
* Determines if the driver is supported on this system.
|
||||
*/
|
||||
public function isSupported(): bool;
|
||||
}
|
||||
64
system/Cache/Exceptions/CacheException.php
Normal file
64
system/Cache/Exceptions/CacheException.php
Normal file
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Cache\Exceptions;
|
||||
|
||||
use CodeIgniter\Exceptions\DebugTraceableTrait;
|
||||
use CodeIgniter\Exceptions\ExceptionInterface;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* CacheException
|
||||
*/
|
||||
class CacheException extends RuntimeException implements ExceptionInterface
|
||||
{
|
||||
use DebugTraceableTrait;
|
||||
|
||||
/**
|
||||
* Thrown when handler has no permission to write cache.
|
||||
*
|
||||
* @return CacheException
|
||||
*/
|
||||
public static function forUnableToWrite(string $path)
|
||||
{
|
||||
return new static(lang('Cache.unableToWrite', [$path]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when an unrecognized handler is used.
|
||||
*
|
||||
* @return CacheException
|
||||
*/
|
||||
public static function forInvalidHandlers()
|
||||
{
|
||||
return new static(lang('Cache.invalidHandlers'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when no backup handler is setup in config.
|
||||
*
|
||||
* @return CacheException
|
||||
*/
|
||||
public static function forNoBackup()
|
||||
{
|
||||
return new static(lang('Cache.noBackup'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when specified handler was not found.
|
||||
*
|
||||
* @return CacheException
|
||||
*/
|
||||
public static function forHandlerNotFound()
|
||||
{
|
||||
return new static(lang('Cache.handlerNotFound'));
|
||||
}
|
||||
}
|
||||
24
system/Cache/Exceptions/ExceptionInterface.php
Normal file
24
system/Cache/Exceptions/ExceptionInterface.php
Normal file
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Cache\Exceptions;
|
||||
|
||||
/**
|
||||
* Provides a domain-level interface for broad capture
|
||||
* of all framework-related exceptions.
|
||||
*
|
||||
* catch (\CodeIgniter\Cache\Exceptions\ExceptionInterface) { ... }
|
||||
*
|
||||
* @deprecated 4.1.2
|
||||
*/
|
||||
interface ExceptionInterface
|
||||
{
|
||||
}
|
||||
106
system/Cache/Handlers/BaseHandler.php
Normal file
106
system/Cache/Handlers/BaseHandler.php
Normal file
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Cache\Handlers;
|
||||
|
||||
use Closure;
|
||||
use CodeIgniter\Cache\CacheInterface;
|
||||
use Exception;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Base class for cache handling
|
||||
*/
|
||||
abstract class BaseHandler implements CacheInterface
|
||||
{
|
||||
/**
|
||||
* Reserved characters that cannot be used in a key or tag. May be overridden by the config.
|
||||
* From https://github.com/symfony/cache-contracts/blob/c0446463729b89dd4fa62e9aeecc80287323615d/ItemInterface.php#L43
|
||||
*
|
||||
* @deprecated in favor of the Cache config
|
||||
*/
|
||||
public const RESERVED_CHARACTERS = '{}()/\@:';
|
||||
|
||||
/**
|
||||
* Maximum key length.
|
||||
*/
|
||||
public const MAX_KEY_LENGTH = PHP_INT_MAX;
|
||||
|
||||
/**
|
||||
* Prefix to apply to cache keys.
|
||||
* May not be used by all handlers.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $prefix;
|
||||
|
||||
/**
|
||||
* Validates a cache key according to PSR-6.
|
||||
* Keys that exceed MAX_KEY_LENGTH are hashed.
|
||||
* From https://github.com/symfony/cache/blob/7b024c6726af21fd4984ac8d1eae2b9f3d90de88/CacheItem.php#L158
|
||||
*
|
||||
* @param string $key The key to validate
|
||||
* @param string $prefix Optional prefix to include in length calculations
|
||||
*
|
||||
* @throws InvalidArgumentException When $key is not valid
|
||||
*/
|
||||
public static function validateKey($key, $prefix = ''): string
|
||||
{
|
||||
if (! is_string($key)) {
|
||||
throw new InvalidArgumentException('Cache key must be a string');
|
||||
}
|
||||
if ($key === '') {
|
||||
throw new InvalidArgumentException('Cache key cannot be empty.');
|
||||
}
|
||||
|
||||
$reserved = config('Cache')->reservedCharacters ?? self::RESERVED_CHARACTERS;
|
||||
if ($reserved && strpbrk($key, $reserved) !== false) {
|
||||
throw new InvalidArgumentException('Cache key contains reserved characters ' . $reserved);
|
||||
}
|
||||
|
||||
// If the key with prefix exceeds the length then return the hashed version
|
||||
return strlen($prefix . $key) > static::MAX_KEY_LENGTH ? $prefix . md5($key) : $prefix . $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an item from the cache, or execute the given Closure and store the result.
|
||||
*
|
||||
* @param string $key Cache item name
|
||||
* @param int $ttl Time to live
|
||||
* @param Closure $callback Callback return value
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function remember(string $key, int $ttl, Closure $callback)
|
||||
{
|
||||
$value = $this->get($key);
|
||||
|
||||
if ($value !== null) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$this->save($key, $value = $callback(), $ttl);
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes items from the cache store matching a given pattern.
|
||||
*
|
||||
* @param string $pattern Cache items glob-style pattern
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function deleteMatching(string $pattern)
|
||||
{
|
||||
throw new Exception('The deleteMatching method is not implemented.');
|
||||
}
|
||||
}
|
||||
115
system/Cache/Handlers/DummyHandler.php
Normal file
115
system/Cache/Handlers/DummyHandler.php
Normal file
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Cache\Handlers;
|
||||
|
||||
use Closure;
|
||||
|
||||
/**
|
||||
* Dummy cache handler
|
||||
*/
|
||||
class DummyHandler extends BaseHandler
|
||||
{
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function initialize()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function get(string $key)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function remember(string $key, int $ttl, Closure $callback)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function save(string $key, $value, int $ttl = 60)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function delete(string $key)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function deleteMatching(string $pattern)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function increment(string $key, int $offset = 1)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function decrement(string $key, int $offset = 1)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function clean()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getCacheInfo()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getMetaData(string $key)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function isSupported(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
423
system/Cache/Handlers/FileHandler.php
Normal file
423
system/Cache/Handlers/FileHandler.php
Normal file
@@ -0,0 +1,423 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Cache\Handlers;
|
||||
|
||||
use CodeIgniter\Cache\Exceptions\CacheException;
|
||||
use Config\Cache;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* File system cache handler
|
||||
*/
|
||||
class FileHandler extends BaseHandler
|
||||
{
|
||||
/**
|
||||
* Maximum key length.
|
||||
*/
|
||||
public const MAX_KEY_LENGTH = 255;
|
||||
|
||||
/**
|
||||
* Where to store cached files on the disk.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $path;
|
||||
|
||||
/**
|
||||
* Mode for the stored files.
|
||||
* Must be chmod-safe (octal).
|
||||
*
|
||||
* @var int
|
||||
*
|
||||
* @see https://www.php.net/manual/en/function.chmod.php
|
||||
*/
|
||||
protected $mode;
|
||||
|
||||
/**
|
||||
* @throws CacheException
|
||||
*/
|
||||
public function __construct(Cache $config)
|
||||
{
|
||||
if (! property_exists($config, 'file')) {
|
||||
$config->file = [
|
||||
'storePath' => $config->storePath ?? WRITEPATH . 'cache',
|
||||
'mode' => 0640,
|
||||
];
|
||||
}
|
||||
|
||||
$this->path = ! empty($config->file['storePath']) ? $config->file['storePath'] : WRITEPATH . 'cache';
|
||||
$this->path = rtrim($this->path, '/') . '/';
|
||||
|
||||
if (! is_really_writable($this->path)) {
|
||||
throw CacheException::forUnableToWrite($this->path);
|
||||
}
|
||||
|
||||
$this->mode = $config->file['mode'] ?? 0640;
|
||||
$this->prefix = $config->prefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function initialize()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function get(string $key)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
$data = $this->getItem($key);
|
||||
|
||||
return is_array($data) ? $data['data'] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function save(string $key, $value, int $ttl = 60)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
$contents = [
|
||||
'time' => time(),
|
||||
'ttl' => $ttl,
|
||||
'data' => $value,
|
||||
];
|
||||
|
||||
if ($this->writeFile($this->path . $key, serialize($contents))) {
|
||||
try {
|
||||
chmod($this->path . $key, $this->mode);
|
||||
|
||||
// @codeCoverageIgnoreStart
|
||||
} catch (Throwable $e) {
|
||||
log_message('debug', 'Failed to set mode on cache file: ' . $e->getMessage());
|
||||
// @codeCoverageIgnoreEnd
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function delete(string $key)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
return is_file($this->path . $key) && unlink($this->path . $key);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function deleteMatching(string $pattern)
|
||||
{
|
||||
$deleted = 0;
|
||||
|
||||
foreach (glob($this->path . $pattern, GLOB_NOSORT) as $filename) {
|
||||
if (is_file($filename) && @unlink($filename)) {
|
||||
$deleted++;
|
||||
}
|
||||
}
|
||||
|
||||
return $deleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function increment(string $key, int $offset = 1)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
$data = $this->getItem($key);
|
||||
|
||||
if ($data === false) {
|
||||
$data = [
|
||||
'data' => 0,
|
||||
'ttl' => 60,
|
||||
];
|
||||
} elseif (! is_int($data['data'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$newValue = $data['data'] + $offset;
|
||||
|
||||
return $this->save($key, $newValue, $data['ttl']) ? $newValue : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function decrement(string $key, int $offset = 1)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
$data = $this->getItem($key);
|
||||
|
||||
if ($data === false) {
|
||||
$data = [
|
||||
'data' => 0,
|
||||
'ttl' => 60,
|
||||
];
|
||||
} elseif (! is_int($data['data'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$newValue = $data['data'] - $offset;
|
||||
|
||||
return $this->save($key, $newValue, $data['ttl']) ? $newValue : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function clean()
|
||||
{
|
||||
return $this->deleteFiles($this->path, false, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getCacheInfo()
|
||||
{
|
||||
return $this->getDirFileInfo($this->path);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getMetaData(string $key)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
if (false === $data = $this->getItem($key)) {
|
||||
return false; // @TODO This will return null in a future release
|
||||
}
|
||||
|
||||
return [
|
||||
'expire' => $data['ttl'] > 0 ? $data['time'] + $data['ttl'] : null,
|
||||
'mtime' => filemtime($this->path . $key),
|
||||
'data' => $data['data'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function isSupported(): bool
|
||||
{
|
||||
return is_writable($this->path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Does the heavy lifting of actually retrieving the file and
|
||||
* verifying it's age.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
protected function getItem(string $filename)
|
||||
{
|
||||
if (! is_file($this->path . $filename)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$data = @unserialize(file_get_contents($this->path . $filename));
|
||||
if (! is_array($data) || ! isset($data['ttl'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($data['ttl'] > 0 && time() > $data['time'] + $data['ttl']) {
|
||||
// If the file is still there then try to remove it
|
||||
if (is_file($this->path . $filename)) {
|
||||
@unlink($this->path . $filename);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a file to disk, or returns false if not successful.
|
||||
*
|
||||
* @param string $path
|
||||
* @param string $data
|
||||
* @param string $mode
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function writeFile($path, $data, $mode = 'wb')
|
||||
{
|
||||
if (($fp = @fopen($path, $mode)) === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
flock($fp, LOCK_EX);
|
||||
|
||||
for ($result = $written = 0, $length = strlen($data); $written < $length; $written += $result) {
|
||||
if (($result = fwrite($fp, substr($data, $written))) === false) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
flock($fp, LOCK_UN);
|
||||
fclose($fp);
|
||||
|
||||
return is_int($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all files contained in the supplied directory path.
|
||||
* Files must be writable or owned by the system in order to be deleted.
|
||||
* If the second parameter is set to TRUE, any directories contained
|
||||
* within the supplied base directory will be nuked as well.
|
||||
*
|
||||
* @param string $path File path
|
||||
* @param bool $delDir Whether to delete any directories found in the path
|
||||
* @param bool $htdocs Whether to skip deleting .htaccess and index page files
|
||||
* @param int $_level Current directory depth level (default: 0; internal use only)
|
||||
*/
|
||||
protected function deleteFiles(string $path, bool $delDir = false, bool $htdocs = false, int $_level = 0): bool
|
||||
{
|
||||
// Trim the trailing slash
|
||||
$path = rtrim($path, '/\\');
|
||||
|
||||
if (! $currentDir = @opendir($path)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
while (false !== ($filename = @readdir($currentDir))) {
|
||||
if ($filename !== '.' && $filename !== '..') {
|
||||
if (is_dir($path . DIRECTORY_SEPARATOR . $filename) && $filename[0] !== '.') {
|
||||
$this->deleteFiles($path . DIRECTORY_SEPARATOR . $filename, $delDir, $htdocs, $_level + 1);
|
||||
} elseif ($htdocs !== true || ! preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename)) {
|
||||
@unlink($path . DIRECTORY_SEPARATOR . $filename);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
closedir($currentDir);
|
||||
|
||||
return ($delDir === true && $_level > 0) ? @rmdir($path) : true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the specified directory and builds an array containing the filenames,
|
||||
* filesize, dates, and permissions
|
||||
*
|
||||
* Any sub-folders contained within the specified path are read as well.
|
||||
*
|
||||
* @param string $sourceDir Path to source
|
||||
* @param bool $topLevelOnly Look only at the top level directory specified?
|
||||
* @param bool $_recursion Internal variable to determine recursion status - do not use in calls
|
||||
*
|
||||
* @return array|false
|
||||
*/
|
||||
protected function getDirFileInfo(string $sourceDir, bool $topLevelOnly = true, bool $_recursion = false)
|
||||
{
|
||||
static $_filedata = [];
|
||||
$relativePath = $sourceDir;
|
||||
|
||||
if ($fp = @opendir($sourceDir)) {
|
||||
// reset the array and make sure $source_dir has a trailing slash on the initial call
|
||||
if ($_recursion === false) {
|
||||
$_filedata = [];
|
||||
$sourceDir = rtrim(realpath($sourceDir) ?: $sourceDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
|
||||
}
|
||||
|
||||
// Used to be foreach (scandir($source_dir, 1) as $file), but scandir() is simply not as fast
|
||||
while (false !== ($file = readdir($fp))) {
|
||||
if (is_dir($sourceDir . $file) && $file[0] !== '.' && $topLevelOnly === false) {
|
||||
$this->getDirFileInfo($sourceDir . $file . DIRECTORY_SEPARATOR, $topLevelOnly, true);
|
||||
} elseif ($file[0] !== '.') {
|
||||
$_filedata[$file] = $this->getFileInfo($sourceDir . $file);
|
||||
$_filedata[$file]['relative_path'] = $relativePath;
|
||||
}
|
||||
}
|
||||
|
||||
closedir($fp);
|
||||
|
||||
return $_filedata;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a file and path, returns the name, path, size, date modified
|
||||
* Second parameter allows you to explicitly declare what information you want returned
|
||||
* Options are: name, server_path, size, date, readable, writable, executable, fileperms
|
||||
* Returns FALSE if the file cannot be found.
|
||||
*
|
||||
* @param string $file Path to file
|
||||
* @param mixed $returnedValues Array or comma separated string of information returned
|
||||
*
|
||||
* @return array|false
|
||||
*/
|
||||
protected function getFileInfo(string $file, $returnedValues = ['name', 'server_path', 'size', 'date'])
|
||||
{
|
||||
if (! is_file($file)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (is_string($returnedValues)) {
|
||||
$returnedValues = explode(',', $returnedValues);
|
||||
}
|
||||
|
||||
$fileInfo = [];
|
||||
|
||||
foreach ($returnedValues as $key) {
|
||||
switch ($key) {
|
||||
case 'name':
|
||||
$fileInfo['name'] = basename($file);
|
||||
break;
|
||||
|
||||
case 'server_path':
|
||||
$fileInfo['server_path'] = $file;
|
||||
break;
|
||||
|
||||
case 'size':
|
||||
$fileInfo['size'] = filesize($file);
|
||||
break;
|
||||
|
||||
case 'date':
|
||||
$fileInfo['date'] = filemtime($file);
|
||||
break;
|
||||
|
||||
case 'readable':
|
||||
$fileInfo['readable'] = is_readable($file);
|
||||
break;
|
||||
|
||||
case 'writable':
|
||||
$fileInfo['writable'] = is_writable($file);
|
||||
break;
|
||||
|
||||
case 'executable':
|
||||
$fileInfo['executable'] = is_executable($file);
|
||||
break;
|
||||
|
||||
case 'fileperms':
|
||||
$fileInfo['fileperms'] = fileperms($file);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $fileInfo;
|
||||
}
|
||||
}
|
||||
271
system/Cache/Handlers/MemcachedHandler.php
Normal file
271
system/Cache/Handlers/MemcachedHandler.php
Normal file
@@ -0,0 +1,271 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Cache\Handlers;
|
||||
|
||||
use CodeIgniter\Exceptions\CriticalError;
|
||||
use Config\Cache;
|
||||
use Exception;
|
||||
use Memcache;
|
||||
use Memcached;
|
||||
|
||||
/**
|
||||
* Mamcached cache handler
|
||||
*/
|
||||
class MemcachedHandler extends BaseHandler
|
||||
{
|
||||
/**
|
||||
* The memcached object
|
||||
*
|
||||
* @var Memcache|Memcached
|
||||
*/
|
||||
protected $memcached;
|
||||
|
||||
/**
|
||||
* Memcached Configuration
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $config = [
|
||||
'host' => '127.0.0.1',
|
||||
'port' => 11211,
|
||||
'weight' => 1,
|
||||
'raw' => false,
|
||||
];
|
||||
|
||||
public function __construct(Cache $config)
|
||||
{
|
||||
$this->prefix = $config->prefix;
|
||||
|
||||
if (! empty($config)) {
|
||||
$this->config = array_merge($this->config, $config->memcached);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the connection to Memcache(d) if present.
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
if ($this->memcached instanceof Memcached) {
|
||||
$this->memcached->quit();
|
||||
} elseif ($this->memcached instanceof Memcache) {
|
||||
$this->memcached->close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function initialize()
|
||||
{
|
||||
try {
|
||||
if (class_exists(Memcached::class)) {
|
||||
// Create new instance of Memcached
|
||||
$this->memcached = new Memcached();
|
||||
if ($this->config['raw']) {
|
||||
$this->memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
|
||||
}
|
||||
|
||||
// Add server
|
||||
$this->memcached->addServer(
|
||||
$this->config['host'],
|
||||
$this->config['port'],
|
||||
$this->config['weight']
|
||||
);
|
||||
|
||||
// attempt to get status of servers
|
||||
$stats = $this->memcached->getStats();
|
||||
|
||||
// $stats should be an associate array with a key in the format of host:port.
|
||||
// If it doesn't have the key, we know the server is not working as expected.
|
||||
if (! isset($stats[$this->config['host'] . ':' . $this->config['port']])) {
|
||||
throw new CriticalError('Cache: Memcached connection failed.');
|
||||
}
|
||||
} elseif (class_exists(Memcache::class)) {
|
||||
// Create new instance of Memcache
|
||||
$this->memcached = new Memcache();
|
||||
|
||||
// Check if we can connect to the server
|
||||
$canConnect = $this->memcached->connect(
|
||||
$this->config['host'],
|
||||
$this->config['port']
|
||||
);
|
||||
|
||||
// If we can't connect, throw a CriticalError exception
|
||||
if ($canConnect === false) {
|
||||
throw new CriticalError('Cache: Memcache connection failed.');
|
||||
}
|
||||
|
||||
// Add server, third parameter is persistence and defaults to TRUE.
|
||||
$this->memcached->addServer(
|
||||
$this->config['host'],
|
||||
$this->config['port'],
|
||||
true,
|
||||
$this->config['weight']
|
||||
);
|
||||
} else {
|
||||
throw new CriticalError('Cache: Not support Memcache(d) extension.');
|
||||
}
|
||||
} catch (CriticalError $e) {
|
||||
throw $e;
|
||||
} catch (Exception $e) {
|
||||
throw new CriticalError('Cache: Memcache(d) connection refused (' . $e->getMessage() . ').');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function get(string $key)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
if ($this->memcached instanceof Memcached) {
|
||||
$data = $this->memcached->get($key);
|
||||
|
||||
// check for unmatched key
|
||||
if ($this->memcached->getResultCode() === Memcached::RES_NOTFOUND) {
|
||||
return null;
|
||||
}
|
||||
} elseif ($this->memcached instanceof Memcache) {
|
||||
$flags = false;
|
||||
$data = $this->memcached->get($key, $flags);
|
||||
|
||||
// check for unmatched key (i.e. $flags is untouched)
|
||||
if ($flags === false) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return is_array($data) ? $data[0] : $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function save(string $key, $value, int $ttl = 60)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
if (! $this->config['raw']) {
|
||||
$value = [
|
||||
$value,
|
||||
time(),
|
||||
$ttl,
|
||||
];
|
||||
}
|
||||
|
||||
if ($this->memcached instanceof Memcached) {
|
||||
return $this->memcached->set($key, $value, $ttl);
|
||||
}
|
||||
|
||||
if ($this->memcached instanceof Memcache) {
|
||||
return $this->memcached->set($key, $value, 0, $ttl);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function delete(string $key)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
return $this->memcached->delete($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function deleteMatching(string $pattern)
|
||||
{
|
||||
throw new Exception('The deleteMatching method is not implemented for Memcached. You must select File, Redis or Predis handlers to use it.');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function increment(string $key, int $offset = 1)
|
||||
{
|
||||
if (! $this->config['raw']) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
return $this->memcached->increment($key, $offset, $offset, 60);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function decrement(string $key, int $offset = 1)
|
||||
{
|
||||
if (! $this->config['raw']) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
// FIXME: third parameter isn't other handler actions.
|
||||
|
||||
return $this->memcached->decrement($key, $offset, $offset, 60);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function clean()
|
||||
{
|
||||
return $this->memcached->flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getCacheInfo()
|
||||
{
|
||||
return $this->memcached->getStats();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getMetaData(string $key)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
$stored = $this->memcached->get($key);
|
||||
|
||||
// if not an array, don't try to count for PHP7.2
|
||||
if (! is_array($stored) || count($stored) !== 3) {
|
||||
return false; // @TODO This will return null in a future release
|
||||
}
|
||||
|
||||
[$data, $time, $limit] = $stored;
|
||||
|
||||
return [
|
||||
'expire' => $limit > 0 ? $time + $limit : null,
|
||||
'mtime' => $time,
|
||||
'data' => $data,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function isSupported(): bool
|
||||
{
|
||||
return extension_loaded('memcached') || extension_loaded('memcache');
|
||||
}
|
||||
}
|
||||
227
system/Cache/Handlers/PredisHandler.php
Normal file
227
system/Cache/Handlers/PredisHandler.php
Normal file
@@ -0,0 +1,227 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Cache\Handlers;
|
||||
|
||||
use CodeIgniter\Exceptions\CriticalError;
|
||||
use Config\Cache;
|
||||
use Exception;
|
||||
use Predis\Client;
|
||||
use Predis\Collection\Iterator\Keyspace;
|
||||
|
||||
/**
|
||||
* Predis cache handler
|
||||
*/
|
||||
class PredisHandler extends BaseHandler
|
||||
{
|
||||
/**
|
||||
* Default config
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $config = [
|
||||
'scheme' => 'tcp',
|
||||
'host' => '127.0.0.1',
|
||||
'password' => null,
|
||||
'port' => 6379,
|
||||
'timeout' => 0,
|
||||
];
|
||||
|
||||
/**
|
||||
* Predis connection
|
||||
*
|
||||
* @var Client
|
||||
*/
|
||||
protected $redis;
|
||||
|
||||
public function __construct(Cache $config)
|
||||
{
|
||||
$this->prefix = $config->prefix;
|
||||
|
||||
if (isset($config->redis)) {
|
||||
$this->config = array_merge($this->config, $config->redis);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function initialize()
|
||||
{
|
||||
try {
|
||||
$this->redis = new Client($this->config, ['prefix' => $this->prefix]);
|
||||
$this->redis->time();
|
||||
} catch (Exception $e) {
|
||||
throw new CriticalError('Cache: Predis connection refused (' . $e->getMessage() . ').');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function get(string $key)
|
||||
{
|
||||
$key = static::validateKey($key);
|
||||
|
||||
$data = array_combine(
|
||||
['__ci_type', '__ci_value'],
|
||||
$this->redis->hmget($key, ['__ci_type', '__ci_value'])
|
||||
);
|
||||
|
||||
if (! isset($data['__ci_type'], $data['__ci_value']) || $data['__ci_value'] === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
switch ($data['__ci_type']) {
|
||||
case 'array':
|
||||
case 'object':
|
||||
return unserialize($data['__ci_value']);
|
||||
|
||||
case 'boolean':
|
||||
case 'integer':
|
||||
case 'double': // Yes, 'double' is returned and NOT 'float'
|
||||
case 'string':
|
||||
case 'NULL':
|
||||
return settype($data['__ci_value'], $data['__ci_type']) ? $data['__ci_value'] : null;
|
||||
|
||||
case 'resource':
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function save(string $key, $value, int $ttl = 60)
|
||||
{
|
||||
$key = static::validateKey($key);
|
||||
|
||||
switch ($dataType = gettype($value)) {
|
||||
case 'array':
|
||||
case 'object':
|
||||
$value = serialize($value);
|
||||
break;
|
||||
|
||||
case 'boolean':
|
||||
case 'integer':
|
||||
case 'double': // Yes, 'double' is returned and NOT 'float'
|
||||
case 'string':
|
||||
case 'NULL':
|
||||
break;
|
||||
|
||||
case 'resource':
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
if (! $this->redis->hmset($key, ['__ci_type' => $dataType, '__ci_value' => $value])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($ttl) {
|
||||
$this->redis->expireat($key, time() + $ttl);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function delete(string $key)
|
||||
{
|
||||
$key = static::validateKey($key);
|
||||
|
||||
return $this->redis->del($key) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function deleteMatching(string $pattern)
|
||||
{
|
||||
$matchedKeys = [];
|
||||
|
||||
foreach (new Keyspace($this->redis, $pattern) as $key) {
|
||||
$matchedKeys[] = $key;
|
||||
}
|
||||
|
||||
return $this->redis->del($matchedKeys);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function increment(string $key, int $offset = 1)
|
||||
{
|
||||
$key = static::validateKey($key);
|
||||
|
||||
return $this->redis->hincrby($key, 'data', $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function decrement(string $key, int $offset = 1)
|
||||
{
|
||||
$key = static::validateKey($key);
|
||||
|
||||
return $this->redis->hincrby($key, 'data', -$offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function clean()
|
||||
{
|
||||
return $this->redis->flushdb()->getPayload() === 'OK';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getCacheInfo()
|
||||
{
|
||||
return $this->redis->info();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getMetaData(string $key)
|
||||
{
|
||||
$key = static::validateKey($key);
|
||||
|
||||
$data = array_combine(['__ci_value'], $this->redis->hmget($key, ['__ci_value']));
|
||||
|
||||
if (isset($data['__ci_value']) && $data['__ci_value'] !== false) {
|
||||
$time = time();
|
||||
$ttl = $this->redis->ttl($key);
|
||||
|
||||
return [
|
||||
'expire' => $ttl > 0 ? time() + $ttl : null,
|
||||
'mtime' => $time,
|
||||
'data' => $data['__ci_value'],
|
||||
];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function isSupported(): bool
|
||||
{
|
||||
return class_exists('Predis\Client');
|
||||
}
|
||||
}
|
||||
263
system/Cache/Handlers/RedisHandler.php
Normal file
263
system/Cache/Handlers/RedisHandler.php
Normal file
@@ -0,0 +1,263 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Cache\Handlers;
|
||||
|
||||
use CodeIgniter\Exceptions\CriticalError;
|
||||
use Config\Cache;
|
||||
use Redis;
|
||||
use RedisException;
|
||||
|
||||
/**
|
||||
* Redis cache handler
|
||||
*/
|
||||
class RedisHandler extends BaseHandler
|
||||
{
|
||||
/**
|
||||
* Default config
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $config = [
|
||||
'host' => '127.0.0.1',
|
||||
'password' => null,
|
||||
'port' => 6379,
|
||||
'timeout' => 0,
|
||||
'database' => 0,
|
||||
];
|
||||
|
||||
/**
|
||||
* Redis connection
|
||||
*
|
||||
* @var Redis
|
||||
*/
|
||||
protected $redis;
|
||||
|
||||
public function __construct(Cache $config)
|
||||
{
|
||||
$this->prefix = $config->prefix;
|
||||
|
||||
if (! empty($config)) {
|
||||
$this->config = array_merge($this->config, $config->redis);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the connection to Redis if present.
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
if (isset($this->redis)) {
|
||||
$this->redis->close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function initialize()
|
||||
{
|
||||
$config = $this->config;
|
||||
|
||||
$this->redis = new Redis();
|
||||
|
||||
try {
|
||||
// Note:: If Redis is your primary cache choice, and it is "offline", every page load will end up been delayed by the timeout duration.
|
||||
// I feel like some sort of temporary flag should be set, to indicate that we think Redis is "offline", allowing us to bypass the timeout for a set period of time.
|
||||
|
||||
if (! $this->redis->connect($config['host'], ($config['host'][0] === '/' ? 0 : $config['port']), $config['timeout'])) {
|
||||
// Note:: I'm unsure if log_message() is necessary, however I'm not 100% comfortable removing it.
|
||||
log_message('error', 'Cache: Redis connection failed. Check your configuration.');
|
||||
|
||||
throw new CriticalError('Cache: Redis connection failed. Check your configuration.');
|
||||
}
|
||||
|
||||
if (isset($config['password']) && ! $this->redis->auth($config['password'])) {
|
||||
log_message('error', 'Cache: Redis authentication failed.');
|
||||
|
||||
throw new CriticalError('Cache: Redis authentication failed.');
|
||||
}
|
||||
|
||||
if (isset($config['database']) && ! $this->redis->select($config['database'])) {
|
||||
log_message('error', 'Cache: Redis select database failed.');
|
||||
|
||||
throw new CriticalError('Cache: Redis select database failed.');
|
||||
}
|
||||
} catch (RedisException $e) {
|
||||
throw new CriticalError('Cache: RedisException occurred with message (' . $e->getMessage() . ').');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function get(string $key)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
$data = $this->redis->hMGet($key, ['__ci_type', '__ci_value']);
|
||||
|
||||
if (! isset($data['__ci_type'], $data['__ci_value']) || $data['__ci_value'] === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
switch ($data['__ci_type']) {
|
||||
case 'array':
|
||||
case 'object':
|
||||
return unserialize($data['__ci_value']);
|
||||
|
||||
case 'boolean':
|
||||
case 'integer':
|
||||
case 'double': // Yes, 'double' is returned and NOT 'float'
|
||||
case 'string':
|
||||
case 'NULL':
|
||||
return settype($data['__ci_value'], $data['__ci_type']) ? $data['__ci_value'] : null;
|
||||
|
||||
case 'resource':
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function save(string $key, $value, int $ttl = 60)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
switch ($dataType = gettype($value)) {
|
||||
case 'array':
|
||||
case 'object':
|
||||
$value = serialize($value);
|
||||
break;
|
||||
|
||||
case 'boolean':
|
||||
case 'integer':
|
||||
case 'double': // Yes, 'double' is returned and NOT 'float'
|
||||
case 'string':
|
||||
case 'NULL':
|
||||
break;
|
||||
|
||||
case 'resource':
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
if (! $this->redis->hMSet($key, ['__ci_type' => $dataType, '__ci_value' => $value])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($ttl) {
|
||||
$this->redis->expireAt($key, time() + $ttl);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function delete(string $key)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
return $this->redis->del($key) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function deleteMatching(string $pattern)
|
||||
{
|
||||
$matchedKeys = [];
|
||||
$iterator = null;
|
||||
|
||||
do {
|
||||
// Scan for some keys
|
||||
$keys = $this->redis->scan($iterator, $pattern);
|
||||
|
||||
// Redis may return empty results, so protect against that
|
||||
if ($keys !== false) {
|
||||
foreach ($keys as $key) {
|
||||
$matchedKeys[] = $key;
|
||||
}
|
||||
}
|
||||
} while ($iterator > 0);
|
||||
|
||||
return $this->redis->del($matchedKeys);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function increment(string $key, int $offset = 1)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
return $this->redis->hIncrBy($key, 'data', $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function decrement(string $key, int $offset = 1)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
return $this->redis->hIncrBy($key, 'data', -$offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function clean()
|
||||
{
|
||||
return $this->redis->flushDB();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getCacheInfo()
|
||||
{
|
||||
return $this->redis->info();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getMetaData(string $key)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
$value = $this->get($key);
|
||||
|
||||
if ($value !== null) {
|
||||
$time = time();
|
||||
$ttl = $this->redis->ttl($key);
|
||||
|
||||
return [
|
||||
'expire' => $ttl > 0 ? time() + $ttl : null,
|
||||
'mtime' => $time,
|
||||
'data' => $value,
|
||||
];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function isSupported(): bool
|
||||
{
|
||||
return extension_loaded('redis');
|
||||
}
|
||||
}
|
||||
144
system/Cache/Handlers/WincacheHandler.php
Normal file
144
system/Cache/Handlers/WincacheHandler.php
Normal file
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Cache\Handlers;
|
||||
|
||||
use Config\Cache;
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Cache handler for WinCache from Microsoft & IIS.
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
class WincacheHandler extends BaseHandler
|
||||
{
|
||||
public function __construct(Cache $config)
|
||||
{
|
||||
$this->prefix = $config->prefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function initialize()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function get(string $key)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
$success = false;
|
||||
|
||||
$data = wincache_ucache_get($key, $success);
|
||||
|
||||
// Success returned by reference from wincache_ucache_get()
|
||||
return $success ? $data : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function save(string $key, $value, int $ttl = 60)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
return wincache_ucache_set($key, $value, $ttl);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function delete(string $key)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
return wincache_ucache_delete($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function deleteMatching(string $pattern)
|
||||
{
|
||||
throw new Exception('The deleteMatching method is not implemented for Wincache. You must select File, Redis or Predis handlers to use it.');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function increment(string $key, int $offset = 1)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
return wincache_ucache_inc($key, $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function decrement(string $key, int $offset = 1)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
return wincache_ucache_dec($key, $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function clean()
|
||||
{
|
||||
return wincache_ucache_clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getCacheInfo()
|
||||
{
|
||||
return wincache_ucache_info(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getMetaData(string $key)
|
||||
{
|
||||
$key = static::validateKey($key, $this->prefix);
|
||||
|
||||
if ($stored = wincache_ucache_info(false, $key)) {
|
||||
$age = $stored['ucache_entries'][1]['age_seconds'];
|
||||
$ttl = $stored['ucache_entries'][1]['ttl_seconds'];
|
||||
$hitcount = $stored['ucache_entries'][1]['hitcount'];
|
||||
|
||||
return [
|
||||
'expire' => $ttl > 0 ? time() + $ttl : null,
|
||||
'hitcount' => $hitcount,
|
||||
'age' => $age,
|
||||
'ttl' => $ttl,
|
||||
];
|
||||
}
|
||||
|
||||
return false; // @TODO This will return null in a future release
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function isSupported(): bool
|
||||
{
|
||||
return extension_loaded('wincache') && ini_get('wincache.ucenabled');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user