Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

@@ -0,0 +1,29 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Files\Core\Util;
// TODO: implement logging levels
class Logger {
public static function log($context, $msg) {
if (PLUGIN_FILESBROWSER_LOGLEVEL === "DEBUG" || PLUGIN_FILESBROWSER_LOGLEVEL === "NORMAL") {
error_log("[INFO][{$context}] " . (string) print_r($msg, true));
}
}
public static function error($context, $msg) {
if (PLUGIN_FILESBROWSER_LOGLEVEL === "ERROR" || PLUGIN_FILESBROWSER_LOGLEVEL === "DEBUG" || PLUGIN_FILESBROWSER_LOGLEVEL === "NORMAL") {
error_log("[ERROR][{$context}] " . (string) print_r($msg, true));
}
}
public static function debug($context, $msg) {
if (PLUGIN_FILESBROWSER_LOGLEVEL === "DEBUG") {
error_log("[DBG][{$context}] " . (string) print_r($msg, true));
}
}
}
@@ -0,0 +1,93 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Created by PhpStorm.
* User: zdev
* Date: 10.01.15
* Time: 11:54.
*/
namespace Files\Core\Util;
class StringUtil {
/**
* Return size to human readable filesize.
*
* @static
*
* @param int $decimals digits
* @param mixed $bytes
*
* @return string human readable filesize
*/
public static function human_filesize($bytes, $decimals = 2) {
$sz = ' KMGTP';
$factor = (int) floor((strlen((string) $bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / 1024 ** $factor) . " " . @$sz[$factor] . "B";
}
/**
* check if a string starts with a specific char.
*
* @static
*
* @param string $haystack
* @param string $needle
*
* @return bool true if $needle is found in $haystack
*/
public static function startsWith($haystack, $needle) {
return !strncmp($haystack, $needle, strlen($needle));
}
/**
* Creates a random string.
*
* @static
*
* @param int $length the length of the random string
*
* @return string a random string
*/
public static function randomstring($length = 6) {
// $chars - all allowed characters
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
mt_srand((int) ((float) microtime() * 1000000));
$i = 0;
$pass = "";
while ($i < $length) {
$num = random_int(0, mt_getrandmax()) % strlen($chars);
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
++$i;
}
return $pass;
}
/**
* check if a string ends with a specific char.
*
* @static
*
* @param string $haystack
* @param string $needle
*
* @return bool true if $haystack ends with $needle
*/
public static function endsWith($haystack, $needle) {
$length = strlen($needle);
if ($length == 0) {
return true;
}
return substr($haystack, -$length) === $needle;
}
}
@@ -0,0 +1,196 @@
## 9.2.4
##### 30 april 2025
- __Core__
- PHP 8.4 compatibility (@khoaofgod, @CHANCENY)
- __Drivers__
- Redis: Refactor Redis driver to read all keys efficiently (@mapcentia)
## 9.2.3
##### 11 january 2024
- __Drivers__
- **Added support of `Ravendb` as an extension with its own [sub-repository](https://github.com/PHPSocialNetwork/ravendb-extension).**
- Deprecated `\Phpfastcache\Entities\DriverStatistic::getData()`. Will be removed as of v10.
- Deprecated `\Phpfastcache\Entities\DriverStatistic::setData()`. Will be removed as of v10.
- Added `\Phpfastcache\Entities\DriverStatistic::getCount(): int|null`. If applicable will return the count of cache objects stored in driver database/collection. Null otherwise.
- Added `\Phpfastcache\Entities\DriverStatistic::setCount()`
## 9.2.2
##### 11 january 2024
- __Core__
- Added optional prefix to `\Phpfastcache\Core\Pool\CacheItemPoolTrait::getKeys()`
## 9.2.1
##### 07 january 2024
- __Misc__
- Added additional check in cache manager for extensions
## 9.2.0
##### 07 january 2024
- __API__
- Upgraded Phpfastcache API to `4.3.0` ([see changes](CHANGELOG_API.md))
- __Extensions__ (💡 New in 9.2)
- Created an extension mechanism to allow some drivers to be loaded independently, see [README.md](README.md)
- Added support of `Couchbasev4` as an extension with its own [sub-repository](https://github.com/PHPSocialNetwork/couchbasev4-extension).
- **IMPORTANT**: *AS OF v9.2* the following drivers has been **MOVED** to their own sub-repositories as a standalone extension: `Arangodb`, `Couchdb`, `Dynamodb`, `Firestore`, `Mongodb`, `Solr`. However `Couchbasev3` will stay in the core for compatibility reasons but will be deprecated.
- **IMPORTANT**: *AS OF v10* extensions will have their namespaces permanently moved from `Phpfastcache\Drivers\EXT_NAME\{Config, Driver, Event, Item}` to `Phpfastcache\Extensions\Drivers\EXT_NAME\{Config, Driver, Event, Item}`. For now an alias is ensuring compatibility.
- __Events__
- EventManager is now scoped to its own poll if retrieved through `ExtendedCacheItemPoolTrait::->getEventManager()`. Global EventManager `EventManager::getInstance()` remains unchanged, see [EVENTS.md](./docs/EVENTS.md).
- `EventManagerInterface::on()` now also accepts a single `string $events`.
- Alias `\Phpfastcache\PhpfastcacheEventManager` of `\Phpfastcache\EventManager` has been added to improve your code import readability.
- Deprecated `\Phpfastcache\Event\EventManagerDispatcherInterface::hasEventManager` to be removed for v10.
- __Drivers__
- Implemented #906 // **Added `RedisCluster` driver support**
- Driver `Memstatic` has changed its name to `Memory` for more consistency.
- Driver `Wincache` is now deprecated and will be removed as of v10 due to the lack of updates to PHP 8 [as officially stated by PHP](https://www.php.net/manual/en/install.windows.recommended.php).
- __Pool__
- Added `ExtendedCacheItemPoolTrait::getAllItems` to allow you to retrieve all items in the cache. This method have some limitations, ([see more in the Wiki](https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV5%CB%96%5D-Fetching-all-keys)).
- __Core__
- Configuration methods`ConfigurationOption::isPreventCacheSlams()`, `ConfigurationOption::setPreventCacheSlams()`, `ConfigurationOption::getCacheSlamsTimeout()`, `ConfigurationOption::setCacheSlamsTimeout()` are deprecated. ([See changes](CHANGELOG_API.md)).
- Fixed #907 // Internal "driver decode()" method will now throw an if the string data looks corrupted.
- Internal: Implemented multiple keys fetch (*if supported by the backend*) to improve the performances behind all `getItems()` calls. Currently only supported in some backends, but it may evolve in the future.
- Internal: Implemented multiple keys delete (*if supported by the backend*) to improve the performances behind all `deleteItems()` calls. Currently only supported in some backends, but it may evolve in the future.
- `\Phpfastcache\CacheContract::get()` now accepts a `\Stringable $cacheKey` argument.
- __Tags__
- Added `\Phpfastcache\Core\Item\TaggableCacheItemInterface::isTagged(): bool`
- __Misc__
- Fixed multiple code typo & updated README.md
## 9.1.3
##### 12 february 2023
- __Core__
- Fixed #893 // getItemsByTag() - empty after one item has expired
- __Misc__
- Fixed multiple code typo & updated README.md
## 9.1.2
##### 09 june 2022
- __API__
- Upgraded Phpfastcache API to `4.2.0` ([see changes](CHANGELOG_API.md))
- __Core__
- Rewrote some core code to improve code maintainability & readability following Scrutinizer and Phpstan recommendations
- Fixed an issue with tags not properly reinitialized when a backend driver returns an expired cache item
- __Drivers__
- Fixed #866 // Deprecated Method Cassandra\ExecutionOptions starting of Cassandra 1.3
- __Misc__
- Increased PHPSTAN level to 6
- Fixed multiple fails of Travis CI
- Migrated Github issue templates from Markdown to YAML configurations
## 9.1.1
##### 15 april 2022
- __Core__
- Fixed #860 // Cache item throw an error on reading with DateTimeImmutable date objects
- Fixed an issue with tags not properly reinitialized when a backend driver returns an expired cache item
- __Drivers__
- Fixed #862 // Multiple driver errors caused by invalid return type of `driverRead()` (reported by @ShockedPlot7560 and @aemla)
## 9.1.0
##### 04 april 2022
- __API__
- Upgraded Phpfastcache API to `4.1.0` ([see changes](CHANGELOG_API.md))
- __Core__
- Added `\Phpfastcache\Helper\UninstanciableObjectTrait` trait which will contains base locked constructor for any classes that are nor meant to be instanciated.
- Deprecated `\Phpfastcache\Config\Config::class`
- Removed/reworked/improved dead/unreachable/redundant/obsolete code, thanks to `Phpstan`
- __Drivers__
- **Added `Solr` driver support**
- __Events__
- Added `\Phpfastcache\Event\EventInterface` for `\Phpfastcache\Event\Event` and subclasses below
- Added `\Phpfastcache\Drivers\Arangodb\Event` for Arangodb events
- Added `\Phpfastcache\Drivers\Dynamodb\Event` for Dynamodb events
- Added `\Phpfastcache\Drivers\Solr\Event` for Solr events
- Moved the following constant from `\Phpfastcache\Event\Event` to their respective drivers: `ARANGODB_CONNECTION`, `ARANGODB_COLLECTION_PARAMS`, `DYNAMODB_CREATE_TABLE`
- __Cluster__
- Fixed #855 // ClusterReplication drivers are saving erroneous expiration date in low-level backends
- __Misc__
- Full PSR-12 compliance is now enforced by PHPCS
- Multiple typo fixes (@mbiebl)
- Updated composer suggestions and CI builder dependencies
## 9.0.2
##### 04 march 2022
- __Core__
- Updated CacheContract::__invoke() signature
- Added new option to allow EventManager override + improved EventManager tests (EventManager::setInstance())
- __Drivers__
- Fixed #853 // Configuration validation issue with Memcached socket (path)
- __Misc__
- Fixed typo and some types hint
## 9.0.1
##### 14 november 2021
- __Core__
- Added `\Phpfastcache\Event\Event` class for centralizing event name with reusable constants.
- __Item__
- `\Psr\Cache\CacheItemInterface::set` will also no longer accepts resource object anymore as method unique parameter
- __Misc__
- Fixed typos in [README.md](./README.md)
## 9.0.0
##### 31 october 2021
- __Migration guide__
- Read the [migration guide](./docs/migration/MigratingFromV8ToV9.md) to upgrade from V8 to V9
- __PSR-6__
- Upgraded `psr/cache` dependency to `^2.0||^3.0` (for PHP-8 types)
- `\Psr\Cache\CacheItemInterface::get()` slightly changed to fully comply with missing PSR-6 specification: If the cache item is **NOT** hit, this method will return `NULL`.
- __PSR-16__
- Upgraded `psr/simple-cache` dependency to `^2.0||^3.0` (for PHP-8 types)
- __API__
- Upgraded Phpfastcache API to `4.0.0` ([see changes](CHANGELOG_API.md))
- Renamed `Api::getPhpFastCacheVersion()` to `Api::getPhpfastcacheVersion()`
- Renamed `Api::getPhpFastCacheChangelog()` to `Api::getPhpfastcacheChangelog()`
- Renamed `Api::getPhpFastCacheGitHeadHash()` to `Api::getPhpfastcacheGitHeadHash()`
- __Cluster__
- Renamed `\Phpfastcache\Cluster\AggregatorInterface::aggregateNewDriver()` to `\Phpfastcache\Cluster\AggregatorInterface::aggregateDriverByName()`
- __Exceptions__
- Added `PhpfastcacheEventManagerException` for EventManager-related exceptions
- __Global__
- Removed magics methods from CacheManager `CacheManager::DriverName()`, use `CacheManager::getInstance('DriverName')` instead
- `\Phpfastcache\Proxy\PhpfastcacheAbstractProxy` now implements `\Phpfastcache\Proxy\PhpfastcacheAbstractProxyInterface`
- Slightly increased performances on some critical points of the library
- Removed "BadPracticeOMeter" notice in CacheManager
- Removed many code duplicate (like in `\Phpfastcache\Driver\[DRIVER_NAME]\Item` classes)
- Reworked traits inter-dependencies for better logic and less polymorphic calls in pool/item traits
- Upgrading library to use benefits of PHP 8 new features (see below)
- Typed every class properties of the library
- Migrated many Closure to arrow functions
- Updated parameters & return type hint to use benefit of covariance and contravariance
- Removed embedded Autoload, Phpfastcache is now only Composer-compatible.
- Removed embedded dependencies (`psr/cache`, `psr/simple-cache`)
- __Helpers__
- Deprecated `\Phpfastcache\Helper\CacheConditionalHelper`, use `\Phpfastcache\CacheContract` instead
- The `\Phpfastcache\CacheContract` class is now also callable directly without calling `get()` method
- __Config/Options__
- Configuration object will now be locked once the cache pool instance is running.
- Updated `ConfigurationOption` which is no longer an `ArrayObject` class, therefore array-syntax is no longer available.
- Removed configuration entry `htaccess` for files-based drivers.
- Removed `IOConfigurationOptionTrait::getHtaccess()`
- Removed `IOConfigurationOptionTrait::setHtaccess()`
- __Tests__
- Added PHPMD, PHPCS and PHPSTAN coverages to increase quality of the project
- Updated tests to work with new core/drivers changes
- Removed Autoload test since its support has been removed and now only managed by Composer
- Increased tests reliability and code coverage for better catching any eventual regression
- __Item__
- `\Psr\Cache\CacheItemInterface::set` will not accept `\Closure` object anymore as method unique parameter
- __Drivers__
- Added `Arangodb` driver support
- Added `Dynamodb` (AWS) driver support
- Added `Firestore` (GCP) driver support
- Removed `Cookie` driver because of its potential dangerosity
- Removed `Couchbase` (SDK 2 support dropped) driver which is now replaced by `Couchbasev3` (SDK 3)
- Removed `Devtrue` and `Devfalse` drivers
- Added `Devrandom` with configurable factor chance and data length
- Renamed classes `\Phpfastcache\Cluster\Drivers\[STATEGY]\[CLUSTER_NAME]Cluster` to `\Phpfastcache\Cluster\Drivers\[STATEGY]\Driver` for better driver naming across the project
- __Events__
- Added `\Phpfastcache\Event\EventReferenceParameter` class and more events such as driver-specific events, see [EVENTS.md](./docs/EVENTS.md) file for more information
- Event callbacks will now receive the `eventName` as an extra _last_ callback parameter (except for `onEveryEvents` callbacks)
- Added `EventManagerInterface::on(array $eventNames, $callback)` method, to subscribe to multiple events in once with the same callback
- Added method named `unbindAllEventCallbacks(): bool` to `EventManagerInterface` to allow you to unbind/clear all event from an event instance
- Updated argument type #2 (`$items`) of `onCacheSaveMultipleItems()` event from `ExtendedCacheItemInterface[]` to `EventReferenceParameter($items)`
- Updated argument type #2 (`$items`) of `onCacheCommitItem()` event from `ExtendedCacheItemInterface[]` to `EventReferenceParameter($items)`
- Updated argument type #2 (`$value`) of `onCacheItemSet()` event from `mixed` to `EventReferenceParameter(mixed $value)`
- __Misc__
- Increased minimum PHP compatibility in composer to `^8.0`
- Updated copyright headers on every file to include the many project contributors
- Globally renamed every occurrence of `PhpFastCache` to `Phpcastcache`
@@ -0,0 +1,144 @@
## 4.3.0
- Created method `ExtendedCacheItemPoolTrait::getAllItems(string $pattern = ''): iterable` which will return all the items stored in the cache. This method have some limitations, ([see more in the Wiki](https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV5%CB%96%5D-Fetching-all-keys)).
- Deprecated `ConfigurationOption::isPreventCacheSlams()` for future removal, use `IOConfigurationOption::isPreventCacheSlams()` instead.
- Deprecated `ConfigurationOption::setPreventCacheSlams()` for future removal, use `IOConfigurationOption::setPreventCacheSlams()` instead.
- Deprecated `ConfigurationOption::getCacheSlamsTimeout()` for future removal, use `IOConfigurationOption::getCacheSlamsTimeout()` instead.
- Deprecated `ConfigurationOption::setCacheSlamsTimeout()` for future removal, use `IOConfigurationOption::setCacheSlamsTimeout()` instead.
- Deprecated `\Phpfastcache\Event\EventManagerDispatcherInterface::hasEventManager` to be removed for v10.
- Created `IOConfigurationOption::isPreventCacheSlams()`. This method will **only be available** for `Files, Sqlite, Leveldb` drivers.
- Created `IOConfigurationOption::setPreventCacheSlams()`. This method will **only be available** for `Files, Sqlite, Leveldb` drivers.
- Created `IOConfigurationOption::getCacheSlamsTimeout()`. This method will **only be available** for `Files, Sqlite, Leveldb` drivers.
- Created `IOConfigurationOption::setCacheSlamsTimeout()`. This method will **only be available** for `Files, Sqlite, Leveldb` drivers.
- Method `EventManagerInterface::on(array|string $events, callable $callback)` now also accepts a single `string $events`.
- Added `\Phpfastcache\Core\Item\TaggableCacheItemInterface::isTagged`.
## 4.2.0
- Created method `\Phpfastcache\Cluster\AggregatablePoolInterface::isAggregatedBy(): ?ClusterPoolInterface` which will return the aggregator object for Cluster aggregators
- Created method `\Phpfastcache\Cluster\AggregatablePoolInterface::setAggregatedBy(ClusterPoolInterface $clusterPool): static` which will allow to set the aggregator object
## 4.1.0
- Created `\Phpfastcache\Event\EventInterface` which will be used for `Phpfastcache\Event\Event` and any `Phpfastcache\Drivers\xxxxxxx\Event` classes
- Extended `CacheItemPoolInterface::save()` with `ExtendedCacheItemPoolInterface::save()` for re-typing
- Method `ExtendedCacheItemPoolInterface::getConfig()` now returns `ConfigurationOptionInterface` instead of `ConfigurationOption`
- Method `ExtendedCacheItemPoolInterface::getDefaultConfig()` now returns `ConfigurationOptionInterface` instead of `ConfigurationOption`
- Method `EventManagerInterface::getInstance()` now returns `EventManagerInterface` instead of `static`
## 4.0.0
- **[BC Break]** Upgraded `psr/cache` dependency to `^3.0` which required `ExtendedCacheItemPoolInterface` and `ExtendedCacheItemInterface` updates
- **[BC Break]** Increased minimum PHP compatibility to `^8.0` which also required `TaggableCacheItemPoolInterface` and `TaggableCacheItemInterface` updates
- **[BC Break]** Updated `ExtendedCacheItemPoolInterface::saveMultiple(ExtendedCacheItemInterface...$items)` which no longer accept argument #0 to be itself an array of `ExtendedCacheItemInterface` objects
- **[BC Break]** Updated `ExtendedCacheItemPoolInterface::getConfigClass()` signature: it is now a **static** method
- Added `ExtendedCacheItemPoolInterface::getItemClass()`
- Added `ExtendedCacheItemInterface::hasTag(string $tag)` to test if a cache item is tagged with the provided tag
- Added `ExtendedCacheItemInterface::hasTag(string $tag)` to test if a cache item is tagged with the provided tag
- Added `ExtendedCacheItemInterface::cloneInto(ExtendedCacheItemInterface $itemTarget, ?ExtendedCacheItemPoolInterface $itemPoolTarget = null)` to clone a cache item into another with an optional pool object
- Referenced `TaggableCacheItemPoolInterface::TAG_STRATEGY_*` constants to `TaggableCacheItemInterface::TAG_STRATEGY_*` for more code usability
## 3.0.0
- **[BC Break]** Removed `ExtendedCacheItemPoolInterface::appendItemsByTagsAll()` (replaced by strategy `TaggableCacheItemPoolInterface::TAG_STRATEGY_ALL`)
- **[BC Break]** Removed `ExtendedCacheItemPoolInterface::decrementItemsByTagsAll()` (replaced by strategy `TaggableCacheItemPoolInterface::TAG_STRATEGY_ALL`)
- **[BC Break]** Removed `ExtendedCacheItemPoolInterface::deleteItemsByTagsAll()` (replaced by strategy `TaggableCacheItemPoolInterface::TAG_STRATEGY_ALL`)
- **[BC Break]** Removed `ExtendedCacheItemPoolInterface::getItemsByTagsAll()` (replaced by strategy `TaggableCacheItemPoolInterface::TAG_STRATEGY_ALL`)
- **[BC Break]** Removed `ExtendedCacheItemPoolInterface::incrementItemsByTagsAll()` (replaced by strategy `TaggableCacheItemPoolInterface::TAG_STRATEGY_ALL`)
- **[BC Break]** Removed `ExtendedCacheItemPoolInterface::prependItemsByTagsAll()` (replaced by strategy `TaggableCacheItemPoolInterface::TAG_STRATEGY_ALL`)
- **[BC Break]** Removed deprecated method `ExtendedCacheItemPoolInterface::getConfigOption()` (Use getConfig()->getOptionName() instead)
- **[BC Break]** Removed deprecated method `ExtendedCacheItemPoolInterface::isUsableInAutoContext()` (Since "Auto" driver has been removed)
- Added strategy`TaggableCacheItemPoolInterface::TAG_STRATEGY_ONE` usable in every `**byTags**` methods.
- Added strategy`TaggableCacheItemPoolInterface::TAG_STRATEGY_ALL` usable in every `**byTags**` methods.
- Added strategy`TaggableCacheItemPoolInterface::TAG_STRATEGY_ONLY` usable in every `**byTags**` methods.
## 3.0.0-rc
- **[BC Break]** Moved `\Phpfastcache\Event\EventInterface` to`\Phpfastcache\Event\EventManagerInterface`
- Moved (by extends) ExtendedCacheItemPoolInterface::setEventManager() in `\Phpfastcache\Event\EventManagerDispatcherInterface:setEventManager()`
- Moved (by extends) ExtendedCacheItemInterface::doesItemBelongToThatDriverBackend() in `\Phpfastcache\Event\EventManagerDispatcherInterface::setEventManager()`
- Added `\Phpfastcache\Event\EventManagerDispatcherInterface`
- Added `ExtendedCacheItemInterface::doesItemBelongToThatDriverBackend()`
- Added `\Phpfastcache\Event\EventManagerInterface:onEveryEvents()`
## 2.0.4
- Added ExtendedCacheItemPoolInterface::getConfigClass() that returns the config class name
## 2.0.3
- Updated ExtendedCacheItemPoolInterface::setEventManager() first argument that now MUST implement `\Phpfastcache\Event\EventInterface`
- Updated ExtendedCacheItemInterface::setEventManager() first argument that now MUST implement `\Phpfastcache\Event\EventInterface`
## 2.0.2
- Added ExtendedCacheItemPoolInterface::isUsableInAutoContext() to check if the driver is allowed to be used in 'Auto' context.
## 2.0.1
- Implemented additional atomic methods:
- Added ExtendedCacheItemInterface::isNull() to test if the data is null or not despite the hit/miss status.
- Added ExtendedCacheItemInterface::isEmpty() to test if the data is empty or not despite the hit/miss status.
- Added ExtendedCacheItemInterface::getLength() get the data length if the data is a string, array, or objects that implement \Countable interface.
## 2.0.0
- Introduced BC breaks:
- Updated ExtendedCacheItemPoolInterface to be compliant with the new \$config object introduced in V7.
- ExtendedCacheItemPoolInterface::getConfig() no longer returns an array but a ConfigurationOption object
- ExtendedCacheItemPoolInterface::getDefaultConfig() no longer returns an array but a ConfigurationOption object
- Removed ExtendedCacheItemInterface::getUncommittedData() that is no longer used in the V7
## 1.3.0
- Implemented full PHP7 type hint support for ExtendedCacheItemPoolInterface and ExtendedCacheItemInterface
- Added instance ID getter (introduced in V7):
- ExtendedCacheItemPoolInterface::getInstanceId()
- The method ExtendedCacheItemPoolInterface::getDefaultConfig() will now returns a \phpFastCache\Util\ArrayObject
## 1.2.5
- Implemented additional simple helper method to direct access to a config option:
- ExtendedCacheItemPoolInterface::getConfigOption()
## 1.2.4
- Implemented additional simple helper method to provide basic information about the driver:
- ExtendedCacheItemPoolInterface::getHelp()
## 1.2.3
- Implemented additional saving method form multiple items:
ExtendedCacheItemPoolInterface::saveMultiple()
## 1.2.2
- Implemented additional tags methods such as:
- ExtendedCacheItemPoolInterface::getItemsByTagsAll()
- ExtendedCacheItemPoolInterface::incrementItemsByTagsAll()
- ExtendedCacheItemPoolInterface::decrementItemsByTagsAll()
- ExtendedCacheItemPoolInterface::deleteItemsByTagsAll()
- ExtendedCacheItemPoolInterface::appendItemsByTagsAll()
- ExtendedCacheItemPoolInterface::prependItemsByTagsAll()
## 1.2.1
- Implemented Event manager methods such as:
- ExtendedCacheItemInterface::setEventManager()
- ExtendedCacheItemPoolInterface::setEventManager()
## 1.2.0
- Implemented Item advanced time methods such as:
- ExtendedCacheItemInterface::setExpirationDate() (Alias of CacheItemInterface::ExpireAt() for more code logic)
- ExtendedCacheItemInterface::getCreationDate() *
- ExtendedCacheItemInterface::getModificationDate() *
- ExtendedCacheItemInterface::setCreationDate(\DateTimeInterface) *
- ExtendedCacheItemInterface::setModificationDate() *
- \* Require configuration directive "itemDetailedDate" to be enabled
## 1.1.3
- Added an additional CacheItemInterface method:
- ExtendedCacheItemInterface::getEncodedKey()
## 1.1.2
- Implemented [de|a]ttaching methods to improve memory management
- ExtendedCacheItemPoolInterface::detachItem()
- ExtendedCacheItemPoolInterface::detachAllItems()
- ExtendedCacheItemPoolInterface::attachItem()
- ExtendedCacheItemPoolInterface::isAttached()
## 1.1.1
- Implemented JsonSerializable interface to ExtendedCacheItemInterface
## 1.1.0
- Implemented JSON methods such as:
- ExtendedCacheItemPoolInterface::getItemsAsJsonString()
- ExtendedCacheItemPoolInterface::getItemsByTagsAsJsonString()
- ExtendedCacheItemInterface::getDataAsJsonString()
## 1.0.0
- First initial version
@@ -0,0 +1,20 @@
## As of the 9.2 an extension concept has been introduced.
It's pretty new but allow Phpfastcache to split up its drivers into sub-repository with a simple additional call to make.
The 9.2 make the beginning of a new external extensions:
- `Arangodb`
- `Couchbasev4`
- `Couchdb`
- `Dynamodb`
- `Firestore`
- `Mongodb`
- `Solr`
There's only 2 steps:
1) Add it to your composer: `composer install phpfastcache/couchbasev4-extension`
2) Call the CacheManager: `CacheManager::getInstance('Couchbasev4')`
However `Couchbasev3` will stay in the core for compatibility reason but will be **deprecated**.
@@ -0,0 +1,20 @@
Copyright (c) 2023 Phpfastcache & its Extensions
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
Software), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,26 @@
# Security Policy
If you discover any vulnerability please be aware of the following table of supported versions below.
Then feel free to contact me at the email address provided in the bottom of that page.
## Supported Versions
| Version | End of support | End of life |
|---------|------------------|------------------|
| 10.0 | *In development* | *In development* |
| 9.2 | December 2025 | December 2026 |
| 9.1 | December 2024 | December 2025 |
| 9.0 | December 2023 | December 2024 |
| 8.x | July 2023 | July 2024 |
| 7.1 | July 2021 | July 2022 |
| 7.0 | July 2019 | July 2020 |
| 6.0 | July 2020 | July 2021 |
| 5.0 | July 2018 | July 2019 |
| 4.0 | July 2017 | January 2018 |
| < 4.0 | N/A | N/A |
More details on the [Wiki](https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV4%CB%96%5D-Global-support-timeline)
## Reporting a Vulnerability
If you discover any security vulnerability contact me at contact#at#geolim4.com with a subject formatted like that:\
`[PHPFASTCACHE][VULNERABILITY] Your mail subject goes here`
Thanks in advance for taking the time to report me that in private.
@@ -0,0 +1,93 @@
{
"name": "phpfastcache/phpfastcache",
"type" : "library",
"description": "PHP Abstract Cache Class - Reduce your database call using cache system. Phpfastcache handles a lot of drivers such as Apc(u), Cassandra, CouchBase, Couchdb, Dynamodb, Firestore, Mongodb, Files, (P)redis, Leveldb, Memcache(d), Ravendb, Ssdb, Sqlite, Wincache, Xcache, Zend Data Cache.",
"keywords": ["abstract", "cache","caching","php cache","mysql cache","apc","apcu","arangodb","dynamodb","firestore","memcache","memcached","wincache","files cache","pdo cache","cache class","redis","redis cluster","predis","cookie", "mongodb", "cassandra", "couchdb", "couchbase", "LevelDb", "ravendb", "Solr", "Ssdb", "Wincache", "xcache","zend","zend disk cache","zend memory cache","zend data cache","zend server"],
"homepage": "https://www.phpfastcache.com",
"license": "MIT",
"readme": "README.md",
"minimum-stability": "stable",
"authors": [
{
"name": "Georges.L",
"email": "contact@geolim4.com",
"homepage": "https://github.com/Geolim4",
"role": "Actual Project Manager/Developer"
},
{
"name": "Contributors",
"homepage": "https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors"
}
],
"provide": {
"psr/cache-implementation": "2.0|3.0",
"psr/simple-cache-implementation": "2.0|3.0"
},
"require": {
"php": ">=8.0",
"psr/cache": "^2.0||^3.0",
"psr/simple-cache": "^2.0||^3.0",
"ext-mbstring": "*",
"ext-json": "*"
},
"require-dev": {
"league/climate": "^3.8",
"ext-gettext": "*",
"phpmd/phpmd": "@stable",
"squizlabs/php_codesniffer": "@stable",
"phpstan/phpstan": "@stable",
"jetbrains/phpstorm-stubs": "dev-master",
"phpfastcache/phpfastcache-devtools": "dev-master"
},
"suggest": {
"ext-apcu": "*",
"ext-curl": "*",
"ext-intl": "*",
"ext-memcached": "*",
"ext-cassandra": "*",
"ext-memcache": "*",
"ext-redis": "*",
"ext-sqlite": "*",
"ext-wincache": "*",
"ext-leveldb": "*",
"ext-couchbase": "^3.0",
"predis/predis": "^2.0",
"phpfastcache/phpssdb": "~1.1.0",
"phpfastcache/arangodb-extension": "^9.2",
"phpfastcache/couchbasev4-extension": "^9.2",
"phpfastcache/couchdb-extension": "^9.2",
"phpfastcache/dynamodb-extension": "^9.2",
"phpfastcache/firestore-extension": "^9.2",
"phpfastcache/mongodb-extension": "^9.2",
"phpfastcache/ravendb-extension": "^9.2",
"phpfastcache/solr-extension": "^9.2"
},
"autoload": {
"psr-4": {
"Phpfastcache\\": "lib/Phpfastcache/"
}
},
"scripts": {
"phpcs": "vendor/bin/phpcs lib/ --report=summary",
"phpcbf": "vendor/bin/phpcbf lib/ --report=summary",
"phpmd": "vendor/bin/phpmd lib/ ansi phpmd.xml",
"phpstan": "vendor/bin/phpstan analyse lib/ -l 6 -c phpstan.neon",
"quality": ["@phpcs", "@phpmd", "@phpstan"],
"tests": [
"php tests/RunTests.php"
]
},
"support": {
"issues": "https://github.com/PHPSocialNetwork/phpfastcache/issues",
"wiki": "https://github.com/PHPSocialNetwork/phpfastcache/wiki",
"docs": "https://github.com/PHPSocialNetwork/phpfastcache/wiki",
"source": "https://github.com/PHPSocialNetwork/phpfastcache",
"security": "https://github.com/PHPSocialNetwork/phpfastcache/blob/master/SECURITY.md"
},
"funding": [
{
"type": "patreon",
"url": "https://www.patreon.com/geolim4"
}
]
}
@@ -0,0 +1,48 @@
## Phpfastcache Copyright (c) 2016
https://www.phpfastcache.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
__Phpfastcache Current Project Manager:__ Georges.L (Geolim4) / (v5, v6, v7, v8, v9)
__Phpfastcache Former Project Founder:__ Khoa Bui (khoaofgod) / (> v4)
__Phpfastcache Contributors:__ https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
#### Hall of fame (Special thanks):
- __Jetbrains__ * for providing us a free Phpstorm IDE licence for years
- __Scrutinizer-CI__ * for providing us a free Security Analysis
- __VersionEye__ * For being an awesome tool that helped us to watch version dependencies. You will be missed, thank you very much Robert.
- __Sabine van Lommen__ * from __Zend.com__ for providing us a free developer licence of Zend Server
- __Lucas (_hammermaps_)__ for the "Zend Data Cache" driver implementation
- __Anton (_git-webmaster_)__ for kindly providing us a Couchbase server for deep tests purposes.
\* Thanks to the companies that provided us free access to their products to help us to build a better quality software every day.
But above all, many thanks to these companies to support indisputably Open Source Projects.
Thanks to all the contributors that added their stone to the building. Each contribution made this project a bit better, every commit, every pull request you made contributed to make this project greater and better.
#### Software licenses:
- PHP License, version 3.0:
- Pear (c) 2001-2004 PHP Group, http://pear.php.net
- MIT licenced:
- Predis (c) 2009-2015 Daniele Alessandri, https://clorophilla.net
@@ -0,0 +1,80 @@
### Drivers descriptions
* Apc **(REMOVED in v8)**
* The Alternative Php Cache (APC) driver. A memory cache for regular performances.
* Apcu
* The Alternative Php User Cache (APCU) driver. A memory cache for regular performances.
* Arangodb **(Added in v9)**
* A very high-performance NoSQL driver using a key-value pair system.
* :new: Is now a composer extension separated from the Phpfastcache core as of v9.2: `phpfastcache/arangodb-extension`
* Cassandra
* A very high-performance NoSQL driver using a key-value pair system. Please note that the Driver rely on php's Datastax extension: https://github.com/datastax/php-driver
* As of PHP an unofficial fork has been launched due to Datastax lack of maintenance: https://github.com/he4rt/scylladb-php-driver
* Cookie **(REMOVED in v9)**
* A cookie driver to store non-sensitive scalar (only) data. Limited storage up to 4Ko.
* Couchbase **(REMOVED in v9)**
* A very high-performance NoSQL driver using a key-value pair system, replaced by Couchbasev3 as of v8.0.8.
* Couchbasev3 **(Added in v8.0.8)**
* Same as Couchbase but for Couchbase PHP-SDK 3.0 support.
* Will be deprecated as of v10
* Couchbasev4 **(Added in v9.2.0)**
* Couchbase PHP-SDK 4.x support.
* :new: It is now a [separated extension](https://github.com/PHPSocialNetwork/couchbasev4-extension) which is no longer part of the Phpfastcache's core.
* Couchdb
* A very high-performance NoSQL driver using a key-value pair system.
* :new: Is now a composer extension separated from the Phpfastcache core as of v9.2: `phpfastcache/couchdb-extension`
* Devfalse **(REMOVED in v9)**
* A development driver that return false for everything except driverCheck().
* Devnull
* A development driver that return null for driverRead() and driverIsHit() (get actions) and true for other action such as driverDelete, DriverClear() etc.
* Devtrue **(REMOVED in v9)**
* A development driver that return true for everything including driverCheck().
* Devrandom **(Added in v8.0.8)**
* A development driver with configurable factor chance and data length.
* Dynamodb **(Added in v9)**
* An AWS cloud NoSQL driver using a key-value pair system. Be careful when flushing the table as it will delete and recreate the table due to a Dynamodb limitation.
* :new: Is now a composer extension separated from the Phpfastcache core as of v9.2: `phpfastcache/dynamodb-extension`
* Files
* A file driver that use serialization for storing data for regular performances. A _$path_ config must be specified, else the system temporary directory will be used.
* Firestore **(Added in v9)**
* A GCP cloud NoSQL driver using a key-value pair system. Collections are created automatically on-the-fly.
* :new: Is now a composer extension separated from the Phpfastcache core as of v9.2: `phpfastcache/firestore-extension`
* Leveldb
* A NoSQL driver using a key-value pair system. A _$path_ config must be specified, else the system temporary directory will be used.
* Memcache
* The Memcache driver. A memory cache for regular performances. Do not cross this driver with Memcached driver.
* Memcached
* The Memcached driver. A memory cache for regular performances. Do not cross this driver with Memcache driver.
* Memstatic
* The Memstatic driver is a memory static driver that expires when the script execution ends.
* Mongodb
* A very high-performance NoSQL driver using a key-value pair system.
* :new: Is now a composer extension separated from the Phpfastcache core as of v9.2: `phpfastcache/mongodb-extension`
* Predis
* A high-performance memory driver using a in-memory data structure storage. Less efficient than Redis driver as it is an embedded library.
* Ravendb **(Added in v9.2)**
* A Ravendb driver that use the `ravendb/ravendb-php-client` client for good performances.
* :new: It is a composer extension separated from the Phpfastcache core as of v9.2: `phpfastcache/ravendb-extension`
* Redis/Rediscluster
* A very high-performance memory driver using a in-memory data structure storage. More efficient than Predis driver as it is an compiled library.
* RedisCluster use the RedisCluster class with a different driver name but behave slightly differently than Redis driver.
* Relay **(Planned for v9.3.0)**
* A very high-performance memory driver based on a Redis backend
* Relay.so aims to be faster than Redis/Predis using a new php extension. Will be available by the end of 2024.
* Riak **(REMOVED in v8.0.6)**
* A very high-performance NoSQL driver using a key-value pair system.
* Solr **(Added in v9.1)**
* A Solr driver that use Solarium as PHP client for good performances.
* :new: It is now a composer extension separated from the Phpfastcache core as of v9.2: `phpfastcache/solr-extension`
* Sqlite
* A Sqlite driver that use serialization for storing data for regular performances. A _$path_ config must be specified, else the system temporary directory will be used.
* Ssdb
* A very high-performance NoSQL driver using a key-value pair system.
* Wincache
* The Wincache driver. A memory cache for regular performances on Windows platforms.
* **Will be removed in v10** due to the lack of updates to PHP8 [as officially stated by PHP](https://www.php.net/manual/en/install.windows.recommended.php).
* Xcache **(REMOVED in v8)**
* The Xcache driver. A memory cache for regular performances.
* Zend Disk Cache ( * Requires ZendServer Version 4 or higher * )
* The Zend Data Cache is a by ZendServer supported file cache. The cache is for regular performance.
* Zend Memory Cache ( * Requires ZendServer Version 4 or higher * )
* The Zend Memory Cache is a by ZendServer supported memory cache. The cache is for high-performance applications.
@@ -0,0 +1,323 @@
:mega: As of the V6, Phpfastcache provides an event mechanism.
You can subscribe to an event by passing a Closure to an active event:
```php
use Phpfastcache\EventManager;
/**
* Bind the event callback
*/
EventManager::getInstance()->onCacheGetItem(function(ExtendedCacheItemPoolInterface $itemPool, ExtendedCacheItemInterface $item){
$item->set('[HACKED BY EVENT] ' . $item->get());
});
```
An event callback can get unbind but you MUST provide a name to the callback previously:
```php
use Phpfastcache\EventManager;
/**
* Bind the event callback
*/
EventManager::getInstance()->onCacheGetItem(function(ExtendedCacheItemPoolInterface $itemPool, ExtendedCacheItemInterface $item){
$item->set('[HACKED BY EVENT] ' . $item->get());
}, 'myCallbackName');
/**
* Unbind the event callback
*/
EventManager::getInstance()->unbindEventCallback('onCacheGetItem', 'myCallbackName');
```
:new: in V8
You can simply subscribe to **every** events at once of Phpfastcache.
```php
<?php
use Phpfastcache\EventManager;
EventManager::getInstance()->onEveryEvents(static function (string $eventName, ...$args) {
echo sprintf("Triggered event '{$eventName}' with %d arguments provided", count($args));
}, 'debugCallback');
```
This is an exhaustive list, and it will be updated as soon as new events will be added to the Core.
:new: In V9
- Some callback parameter, that are __NOT__ objects, are passed by reference via the new `\Phpfastcache\Event\EventReferenceParameter` class.\
This class is instantiated and passed to the callback with the original value passed **by reference** allowing you to either read or re-write its value.\
If it's allowed by the event dispatcher the type can be changed or not.\
If you try to while it's not allowed, you will get a `PhpfastcacheInvalidArgumentException` when trying to call `\Phpfastcache\Event\EventReferenceParameter::setParameterValue()`\
Finally the class `\Phpfastcache\Event\EventReferenceParameter` is `invokable` and trying to do so will return you the parameter value.\
- A method named `unbindAllEventCallbacks(): bool` has been added to `EventManagerInterface` to allow you to unbind/clear all event from an event instance.
- Event callbacks will now receive the `eventName` as an extra _last_ callback parameter (except for `onEveryEvents` callbacks)
- Added `EventManagerInterface::on(array $eventNames, $callback)` method, to subscribe to multiple events in once with the same callback
:warning: Changed in V9.2
As of the V9.2 there is a slight change with the EventManager:
EventManager is now scoped to its own poll if retrieved through `ExtendedCacheItemPoolTrait::->getEventManager()`.
This means, that the behavior is not more consistent:\
An EventManager retrieved through `ExtendedCacheItemPoolTrait::->getEventManager()` will now **ONLY** fire events related to this pool instance.\
However, the global EventManager `EventManager::getInstance()` remains unchanged and will fire any events no matter what pool emitted it.
The order of execution of the events is always the following:
1. Scoped named Event through `ExtendedCacheItemPoolTrait::->getEventManager()->onXxxxxXxxxx(...)`
2. Scoped `onEveryEvent` Event through `ExtendedCacheItemPoolTrait::->getEventManager()->onEveryEvent(...)`
3. Unscoped named event through `EventManager::getInstance()->onXxxxxXxxxx(...)`
4. Unscoped `onEveryEvent` event through `EventManager::getInstance()->onEveryEvent(...)`
## List of active events:
### ItemPool Events
- onCacheGetItem(*Callable* **$callback**)
- **Callback arguments**
- *ExtendedCacheItemPoolInterface* **$itemPool**
- *ExtendedCacheItemInterface* **$item**
- **Scope**
- ItemPool
- **Description**
- Allow you to manipulate an item just before it gets returned by the getItem() method.
- **Risky Circular Methods**
- *ExtendedCacheItemPoolInterface::getItem()*
- *ExtendedCacheItemPoolInterface::getItems()*
- *ExtendedCacheItemPoolInterface::getItemsByTag()*
- *ExtendedCacheItemPoolInterface::getItemsAsJsonString()*
- onCacheGetItems(*Callable* **$callback**)
- **Callback arguments**
- *ExtendedCacheItemPoolInterface* **$itemPool**
- *ExtendedCacheItemInterface[]* **$items**
- **Scope**
- ItemPool
- **Description**
- Allow you to manipulate a set of items just before it gets returned by the getItems() method.
- **Risky Circular Methods**
- *ExtendedCacheItemPoolInterface::getItem()*
- *ExtendedCacheItemPoolInterface::getItems()*
- *ExtendedCacheItemPoolInterface::getItemsByTag()*
- *ExtendedCacheItemPoolInterface::getItemsAsJsonString()*
- onCacheDeleteItem(*Callable* **$callback**)
- **Callback arguments**
- *ExtendedCacheItemPoolInterface* **$itemPool**
- *ExtendedCacheItemInterface* **$item**
- **Scope**
- ItemPool
- **Description**
- Allow you to manipulate an item after being deleted (this event is not fired if `deleteItems()` is called). :exclamation: **Caution** The provided item is in pool detached-state.
- **Risky Circular Methods**
- *ExtendedCacheItemPoolInterface::deleteItem()*
- *ExtendedCacheItemPoolInterface::deleteItems()*
- *ExtendedCacheItemPoolInterface::getItem()*
- *ExtendedCacheItemPoolInterface::getItems()*
- *ExtendedCacheItemPoolInterface::getItemsByTag()*
- *ExtendedCacheItemPoolInterface::getItemsAsJsonString()*
- onCacheDeleteItems(*Callable* **$callback**)
- **Callback arguments**
- *ExtendedCacheItemPoolInterface* **$itemPool**
- *ExtendedCacheItemInterface[]* **$items**
- **Scope**
- ItemPool
- **Description**
- Allow you to manipulate multiple items after being deleted. :exclamation: **Caution** The provided item is in pool detached-state.
- **Risky Circular Methods**
- *ExtendedCacheItemPoolInterface::deleteItem()*
- *ExtendedCacheItemPoolInterface::deleteItems()*
- *ExtendedCacheItemPoolInterface::getItem()*
- *ExtendedCacheItemPoolInterface::getItems()*
- *ExtendedCacheItemPoolInterface::getItemsByTag()*
- *ExtendedCacheItemPoolInterface::getItemsAsJsonString()*
- onCacheSaveItem(*Callable* **$callback**)
- **Callback arguments**
- *ExtendedCacheItemPoolInterface* **$itemPool**
- *ExtendedCacheItemInterface* **$item**
- **Scope**
- ItemPool
- **Description**
- Allow you to manipulate an item just before it gets saved by the driver.
- **Risky Circular Methods**
- *ExtendedCacheItemPoolInterface::commit()*
- *ExtendedCacheItemPoolInterface::save()*
- onCacheSaveMultipleItems(*Callable* **$callback**)
- **Callback arguments**
- *ExtendedCacheItemPoolInterface* **$itemPool**
- *EventReferenceParameter($items)* **$items** _via EventReferenceParameter object_ **(type modification forbidden)**
- **Scope**
- ItemPool
- **Description**
- Allow you to manipulate an array of items before they get saved by the driver.
- **Risky Circular Methods**
- *ExtendedCacheItemPoolInterface::commit()*
- *ExtendedCacheItemPoolInterface::save()*
- *ExtendedCacheItemPoolInterface::saveMultiple()*
- onCacheSaveDeferredItem(*Callable* **$callback**)
- **Callback arguments**
- *ExtendedCacheItemPoolInterface* **$itemPool**
- *ExtendedCacheItemInterface* **$item**
- **Scope**
- ItemPool
- **Description**
- Allow you to manipulate an item just before it gets pre-saved by the driver.
- **Risky Circular Methods**
- *ExtendedCacheItemPoolInterface::saveDeferred()*
- onCacheCommitItem(*Callable* **$callback**)
- **Callback arguments**
- *ExtendedCacheItemPoolInterface* **$itemPool**
- *EventReferenceParameter($items)* **$items** _via EventReferenceParameter object_ **(type modification forbidden)**
- **Scope**
- ItemPool
- **Description**
- Allow you to manipulate and/or alter a set of items just before they gets pre-saved by the driver.
- **Risky Circular Methods**
- *ExtendedCacheItemPoolInterface::commit()*
- onCacheClearItem(*Callable* **$callback**)
- **Callback arguments**
- *ExtendedCacheItemPoolInterface* **$itemPool**
- *ExtendedCacheItemInterface[]* **$items**
- **Scope**
- ItemPool
- **Description**
- Allow you to manipulate a set of item just before they gets cleared by the driver.
- **Risky Circular Methods**
- *ExtendedCacheItemPoolInterface::clear()*
- *ExtendedCacheItemPoolInterface::clean()*
- onCacheWriteFileOnDisk(*Callable* **$callback**)
- **Callback arguments**
- *ExtendedCacheItemPoolInterface* **$itemPool**
- *string* **$file**
- *bool* **$secureFileManipulation**
- **Scope**
- ItemPool
- **Description**
- Allow you to get notified when a file is written on disk.
- **Risky Circular Methods**
- *ExtendedCacheItemPoolInterface::writefile()*
- onCacheGetItemInSlamBatch(*Callable* **$callback**)
- **Callback arguments**
- *ExtendedCacheItemPoolInterface* **$itemPool**
- *ItemBatch* **$driverData**
- *int* **$cacheSlamsSpendSeconds**
- **Scope**
- ItemPool
- **Description**
- Allow you to get notified each time a batch loop is looping
- **Risky Circular Methods**
- *ExtendedCacheItemPoolInterface::deleteItem()*
- *ExtendedCacheItemPoolInterface::getItem()*
- *ExtendedCacheItemPoolInterface::getItems()*
- *ExtendedCacheItemPoolInterface::getItemsByTag()*
- *ExtendedCacheItemPoolInterface::getItemsAsJsonString()*
- onCacheDriverChecked(*Callable* **$callback**)
- **Callback arguments**
- *ExtendedCacheItemPoolInterface* **$itemPool**
- **Scope**
- ItemPool
- **Description**
- Allow you to bind an event when the driver prerequisites has passed but before it the `driverConnect()` is called.
- **Risky Circular Methods**
- *(none)*
- onCacheDriverConnected(*Callable* **$callback**)
- **Callback arguments**
- *ExtendedCacheItemPoolInterface* **$itemPool**
- *object* **$instance** Internal instance of the backend connect
- **Scope**
- ItemPool
- **Description**
- Allow you to bind an event when the driver backend has been successfully instantiated and connected/authenticated (where applicable).
- **Risky Circular Methods**
- *(none)*
### ItemPool Events (Cluster)
- onCacheReplicationSlaveFallback(*Callable* **$callback**)
- **Callback arguments**
- *ClusterPoolInterface* **$self**
- *string* **$caller**
- **Scope**
- Cluster pool
- **Description**
- Allow you to get notified when a Master/Slave cluster switches on slave
- **Risky Circular Methods**
- N/A
- onCacheReplicationRandomPoolChosen(*Callable* **$callback**)
- **Callback arguments**
- *ClusterPoolInterface* **$self**
- *ExtendedCacheItemPoolInterface* **$randomPool**
- **Scope**
- Cluster pool
- **Description**
- Allow you to get notified when a Random Replication cluster choose a cluster
- **Risky Circular Methods**
- N/A
- onCacheClusterBuilt(*Callable* **$callback**)
- **Callback arguments**
- *AggregatorInterface* **$clusterAggregator**
- *ClusterPoolInterface* **$cluster**
- **Scope**
- Cluster aggregator
- **Description**
- Allow you to get notified when a cluster is being built
- **Risky Circular Methods**
- *$clusterAggregator::getCluster()*
### Item Events
- onCacheItemSet(*Callable* **$callback**)
- **Callback arguments**
- *ExtendedCacheItemInterface* **$item**
- *EventReferenceParameter($value)* **$value** _via EventReferenceParameter object_ **(type modification allowed)**
- **Scope**
- Item
- **Description**
- Allow you to read (and rewrite) the value set to an item.
- **Risky Circular Methods**
- *ExtendedCacheItemInterface::get()*
- onCacheItemExpireAt(*Callable* **$callback**)
- **Callback arguments**
- *ExtendedCacheItemInterface* **$item**
- *\DateTimeInterface* **$expiration**
- **Scope**
- Item
- **Description**
- Allow you to get/set the expiration date of an item.
- **Risky Circular Methods**
- *ExtendedCacheItemInterface::expiresAt()*
- onCacheItemExpireAfter(*Callable* **$callback**)
- **Callback arguments**
- *ExtendedCacheItemInterface* **$item**
- *int | \DateInterval* **$time**
- **Scope**
- Item
- **Description**
- Allow you to get the "expire after" time of an item. If `$time` is a DateInterval you also set it.
- **Risky Circular Methods**
- *ExtendedCacheItemInterface::expiresAt()*
### Driver-specific Events (as of V9)
#### Arangodb
See [Arangodb extension event documentation](https://github.com/PHPSocialNetwork/arangodb-extension#events).
#### Couchdb (v9.2)
See [Couchdb extension event documentation](https://github.com/PHPSocialNetwork/couchdb-extension#events).
#### Dynamodb
See [Dynamodb extension event documentation](https://github.com/PHPSocialNetwork/dynamodb-extension#events).
#### Solr
See [Solr extension event documentation](https://github.com/PHPSocialNetwork/solr-extension#events).
@@ -0,0 +1,8 @@
Phpfastcache has some options that you may want to know before using them.
### Global options
The global options are defined in `\Phpfastcache\Config\ConfigurationOption` ([ConfigurationOption.php](../lib/Phpfastcache/Config/ConfigurationOption.php))
### Driver-specific options *
The driver-specific options are defined in `Config.php` file located in each driver [directory](../lib/Phpfastcache/Drivers).
Each driver-specific `Config` class file extends `\Phpfastcache\Config\ConfigurationOption`
@@ -0,0 +1,137 @@
Because the V5 is not backward compatible with the V4 we will help you to migrate your code:
### Extending phpFastCache:
#### :clock1: Then:
```php
namespace My\Custom\Project;
use phpFastCache\Core\phpFastCache;
/**
* Class Cache
*/
class Cache extends phpFastCache
{
}
```
#### :alarm_clock: Now:
```php
namespace My\Custom\Project;
use phpFastCache\Proxy\phpFastCacheAbstractProxy;
/**
* Class Cache
*/
class Cache extends phpFastCacheAbstractProxy
{
}
```
See examples/extendedPhpFastCache.php for more information
### Get/Set uses:
#### :clock1: Then:
```php
namespace My\Custom\Project;
use phpFastCache\Core\phpFastCache;
$cache = phpFastCache();
// or
$cache = __c();
$myCacheItem = $cache->get("myKey");
if($myCacheItem === null){
$myCacheItem = database_operation();
$cache->set("myKey", $myCacheItem, 600);
}
$template['myCacheItemData'] = $myCacheItem;
```
#### :alarm_clock: Now:
```php
namespace My\Custom\Project;
$config = [
'path' => 'An\absolute\path',
];
$cache = CacheManager::getInstance('Files', $config);
// or
$cache = CacheManager::Files($config);
$myCacheItem = $cache->getItem("myKey");
if(!$myCacheItem->isHit()){
$myCacheItem->set(database_operation());
$cache->save($myCacheItem);
}
$template['myCacheItemData'] = $myCacheItem->get();
```
### Cache clearing:
#### :clock1: Then:
```php
namespace My\Custom\Project;
use phpFastCache\Core\phpFastCache;
$cache = phpFastCache();
// or
$cache = __c();
$cache->clean();
```
#### :alarm_clock: Now:
```php
namespace My\Custom\Project;
$config = [
'path' => 'An\absolute\path',
];
$cache = CacheManager::getInstance('Files', $config);
// or
$cache = CacheManager::Files($config);
$myCacheItem = $cache->clear();
```
### Search system:
The search system has been removed in favor of Tags features. Remember that the cache must NOT be considered as a search engine like Solr, Sphynx etc.
See examples/tagsMethods.php for more information
@@ -0,0 +1,244 @@
Because the V6 is not backward compatible with the V5, here's a guide to help you to migrate your code:
### Existing data in cache during migration
:anger: :exclamation: If you update PhpFastCache from v5 to v6 you need to clear up the whole cache otherwise you may get this kind of error:
```
Notice: Undefined index: e in /phpfastcache/src/phpFastCache/Core/Pool/DriverBaseTrait.php on line ...
Fatal error: Uncaught phpFastCache\Exceptions\phpFastCacheInvalidArgumentException: $expiration must be an object implementing the DateTimeInterface in ...
```
### Setting up a default config
#### :clock1: Then:
PhpFastCache used to set a default global config using the `CacheManager::setup()` method
```php
namespace My\Custom\Project;
$instance = CacheManager::setup([
'path' => 'somewhere'
]);
$instance = CacheManager::getInstance('Files');
```
#### :alarm_clock: Now:
This method has been changed is now replaced by the `CacheManager::setDefaultConfig()` method.
Using the old `CacheManager::setup()` method will trigger a `phpFastCacheInvalidConfigurationException`
```php
namespace My\Custom\Project;
$instance = CacheManager::setDefaultConfig([
'path' => 'somewhere'
]);
$instance = CacheManager::getInstance('Files');
```
### Type hint of Driver instances
#### :clock1: Then:
Driver instances used to implements a `phpFastCache\Cache\ExtendedCacheItemPoolInterface` interface.
```php
namespace My\Custom\Project;
$instance = CacheManager::getInstance('Files');
if($instance instanceof \phpFastCache\Cache\ExtendedCacheItemPoolInterface)
{
// Some code
}
```
#### :alarm_clock: Now:
This has been changed and they now implements a `phpFastCache\Core\Pool\ExtendedCacheItemPoolInterface` interface
```php
namespace My\Custom\Project;
$instance = CacheManager::getInstance('Files');
if($instance instanceof \phpFastCache\Core\Pool\ExtendedCacheItemPoolInterface)
{
// Some code
}
```
### Type hint of Item instances
#### :clock1: Then:
Item instances used to implements a ``phpFastCache\Cache\ExtendedCacheItemInterface`` interface.
```php
namespace My\Custom\Project;
$instance = CacheManager::getInstance('Files');
$item = $instance->getItem('key');
if($item instanceof \phpFastCache\Cache\ExtendedCacheItemInterface)
{
// Some code
}
```
#### :alarm_clock: Now:
This has been changed and it now returns a `phpFastCache\Core\Item\ExtendedCacheItemInterface` interface
```php
namespace My\Custom\Project;
$instance = CacheManager::getInstance('Files');
$item = $instance->getItem('key');
if($item instanceof \phpFastCache\Core\Item\ExtendedCacheItemInterface)
{
// Some code
}
```
### Catching \InvalidArgumentException
#### :clock1: Then:
Code used to catch a `\InvalidArgumentException` interface.
```php
namespace My\Custom\Project;
$instance = CacheManager::getInstance('Files');
try{
$item = $instance->getItem(array());
}catch(\InvalidArgumentException $e){
//Caught exception code
}
```
#### :alarm_clock: Now:
This has been changed you now MUST catch `\phpFastCache\Exceptions\phpFastCacheInvalidArgumentException` class
```php
namespace My\Custom\Project;
$instance = CacheManager::getInstance('Files');
try{
$item = $instance->getItem(array());
}catch(\phpFastCache\Exceptions\phpFastCacheInvalidArgumentException $e){
//Caught exception code
}
```
:warning: Please note that `\phpFastCache\Exceptions\phpFastCacheInvalidArgumentException` implements `\Psr\Cache\InvalidArgumentException` as per PSR-6.
### Catching \LogicException
#### :clock1: Then:
Code used to catch a `\LogicException`.
```php
namespace My\Custom\Project;
$instance = CacheManager::getInstance('Files');
try{
$item = $instance->getItem(array());
}catch(\LogicException $e){
//Caught exception code
}
```
#### :alarm_clock: Now:
This has been changed you now MUST catch `\phpFastCache\Exceptions\phpFastCacheLogicException` interface
```php
namespace My\Custom\Project;
$instance = CacheManager::getInstance('Files');
try{
$item = $instance->getItem(array());
}catch(\phpFastCache\Exceptions\phpFastCacheLogicException $e){
//Caught exception code
}
```
### Allowed characters in key identifier
:warning: As of the V6, the following characters can not longer being a part of the key identifier: `{}()/\@:`
If you try to do so, an `\phpFastCache\Exceptions\phpFastCacheInvalidArgumentException` will be raised.
You must replace them with a safe delimiter such as `.|-_`
### Cache clear method
The deprecated method `phpFastCache\Cache\ExtendedCacheItemPoolInterface::clear()` is now definitely removed.
#### :clock1: Then:
In the V5 the method `phpFastCache\Cache\ExtendedCacheItemPoolInterface::clear()` was deprecated.
```php
namespace My\Custom\Project;
$instance = CacheManager::getInstance('Files');
if($instance instanceof \phpFastCache\Cache\ExtendedCacheItemPoolInterface)
{
$instance->clear();
}
```
#### :alarm_clock: Now:
In the V6 we removed it. Use `phpFastCache\Cache\ExtendedCacheItemPoolInterface::clean()` instead.
```php
namespace My\Custom\Project;
$instance = CacheManager::getInstance('Files');
if($instance instanceof \phpFastCache\Core\Pool\ExtendedCacheItemPoolInterface)
{
$instance->clean();
}
```
### Mongodb driver has changed
:warning: As of the V6, the Mongodb driver has been updated
#### :clock1: Then:
In the V5 the driver was making use of of the [deprecated class Mongo](http://php.net/manual/fr/class.mongo.php).
#### :alarm_clock: Now:
In the V6 we made an important change: We now make use of [Mongodb Driver](http://php.net/manual/fr/set.mongodb.php)
Only your code configuration will have to be updated, PhpFastCache manages all the abstract part by itself.
### DriverStatistic class name has changed
:warning: As of the V6, DriverStatistic class name has changed for a better classes name normalization
#### :clock1: Then:
In the V5 the class was named `phpFastCache\Entities\driverStatistic`
#### :alarm_clock: Now:
In the V6 it has changed and is now `phpFastCache\Entities\DriverStatistic` (with a **D** uppercase), you may need to re-fetch your
git repository completely on some operating systems (especially Windows, meh).
@@ -0,0 +1,169 @@
Because the V7 is **absolutely** not backward compatible with the V6, here's a guide to help you to migrate your code:
### :warning: Phpfastcache global namespace :warning:
As of the V7 and to comply with modern standards the Phpfastcache namespace has changed :warning:
#### :clock1: Then:
We used to declare this namespace: `namespace phpFastCache;` or `use phpFastCache\...;`
#### :alarm_clock: Now:
The time has changed, you now have to use: `namespace Phpfastcache;` or `use Phpfastcache\...;`
For any useful purpose, the `src/` directory has been moved along to `lib/`.
### :warning: Phpfastcache "phpFastCache*" classes :warning:
As of the V7 and to comply with modern standards the "phpFastCache*" classes have been **C**apitalized :warning:
#### :clock1: Then:
We used to declare this kind of class: `class phpFastCacheAbstractProxy`
#### :alarm_clock: Now:
The time has changed, you now have to use: `class PhpfastcacheAbstractProxy`
For any useful purpose, all the PhpFastCache exceptions has been **C**apitalized.
Class `Phpfastcache\Exceptions\phpFastCache[...]Exception` have been renamed to `Phpfastcache\Exceptions\Phpfastcache[...]Exception`
### Deprecations
- `Phpfastcache\CacheManager::getStaticAllDrivers()` replaced by `Phpfastcache\CacheManager::getDriverList()`
- `Phpfastcache\CacheManager::getStaticSystemDrivers()` replaced by `Phpfastcache\CacheManager::getDriverList()`
- Configuration option `ignoreSymfonyNotice` will not be replaced since that the related Symfony notice in `Phpfastcache\CacheManager::getInstance()` has been removed
### Configuration
- Added configuration option `fallbackConfig` for a better fallback configuration
### Return type & Scalar type declarations
:anger: :exclamation: The V7 will make use of new php's return type & scalars type declarations features.
This means that you will now have to be very careful about the data types that you are sending to the phpFastCache API.
Also PhpFastCache will make use of **strict types** provided by php7 by declaring `declare(strict_types=1);` in the top of each source file.
This ensure you a full compatibility and respect of php types.
### ActOnAll Helper
#### :clock1: Then:
The ActOnAll helper used to return an array of returns only for getters and a strict boolean of CRUD operations:
(
Files::DeleteItem(): false +
Memcache::DeleteItem(): true +
Redis::DeleteItem(): true
) => Returning a strict FALSE
#### :alarm_clock: Now:
Whatever you call will now result in an array of returns giving you the possibility to know which driver is returning an unexpected response via the ActOnAll helper.
Also the ActOnAll helper does no longer implements `ExtendedCacheItemPoolInterface` due to the type hint implementation.
### Cache Manager: Instance ID
:new: As of the V7 you can now (optionally) specify an instance ID using the CacheManager:
```php
CacheManager::getInstance($defaultDriver, $options, $instanceId);
```
Please note that `$instanceId` must be a valid __STRING__.
There's also a variant that throw a `phpFastCacheInstanceNotFoundException` if the instance is not found.
```php
CacheManager::getInstanceById($instanceId);
```
### Configuration option names
#### :clock1: Then:
Some configuration names were still using "snake case" format:
- default_chmod
- compress_data
- sasl_user
- ...
#### :alarm_clock: Now:
These configuration names are now "Camelized":
- defaultChmod
- compressData
- saslUser
- ...
As of the V7 there's no "snake case" names left.
### Configuration option type
#### :clock1: Then:
The configuration data used to be a primitive array passed through a `CacheManager` method.
#### :alarm_clock: Now:
The will now accept only a `\Phpfastcache\Config\ConfigurationOption` object.
There's a short alias available for less verbose configuration: `\Phpfastcache\Config\Config`
This object will contain fluent setters allowing you to make use of chained setters.
Despite the fact that this is a bad practice, this object which implements ArrayAccess interface
will allow you to treat the object as an array for primitive variable accesses:
```php
use Phpfastcache\Config\Config;
$configArray = [];
$config = new Config();
$config['path'] = '/an/absolute/path';
// The line above is doing exact same job as the line below:
$config->setPath('/an/absolute/path');
$cacheInstace = CacheManager::getInstance('Files', $config);
// This also works well:
$cacheInstace = CacheManager::getInstance('Files', new Config([
'path' => '/an/absolute/path']
));
```
#### For non-global option you MUST use the specific Config object provided for each drivers
```php
// The recommended way is to use an alias to not confuse yourself
use Phpfastcache\Drivers\Files\Config as FilesConfig;
$config = new FilesConfig();
$config->setPath('/an/absolute/path');
$config->setSecureFileManipulation(true);
$cacheInstace = CacheManager::getInstance('Files', $config);
// This also works well:
$cacheInstace = CacheManager::getInstance('Files', new FilesConfig([
'path' => '/an/absolute/path']
));
```
However the ArrayAccess interface has been implemented to make the migration easier,
so we might reconsider it's usefulness in the future.
Then, we recommend you to use the standard object syntax to ensure you a better compatibility.
Please note that the `CacheManager` will still accepts a primitive array but will raise a
E_USER_DEPRECATED error if you do so.
### Cache manager default configuration
#### :clock1: Then:
The previous deprecated `CacheManager::setup()` method was kept until V6.
It has been definitely removed as of the V7.
#### :alarm_clock: Now:
Use the recommended `CacheManager::setDefaultConfig()` method instead
### Invalid configuration keys/values
#### :clock1: Then:
PhpFastCache ignored invalid configuration Key/value.
#### :alarm_clock: Now:
PhpFastCache will now throws a `phpFastCacheInvalidConfigurationException` if you
attempt to make use of an invalid configuration Key/value.
### API changelog
#### :clock1: Then:
The API changelog used to be hardcoded as a HEREDOC in the `Api::getChangelog()` method.
#### :alarm_clock: Now:
The API changelog format has been moved to a MarDown file (.md)
If you were using `Api::getChangelog()` you may need to check that your code is still working as expected.
The method still returns a valid string but its format has changed slightly.
### Couchbase PHP SDK
The Couchbase driver has been updated to works with PHP SDK 2.4+ (Couchbase Server 5+).
Therefore it way requires a Couchbase Server updated combined with an SDK update.
### Constants autoload-related
As of the V7, all the constant starting by _PFC\_*_ were moved in to the `Phpfastcache\Autoload` namespace\
to not pollute php's root namespace.
### Autoload mechanism
Although we highly recommend you to make use of composer benefits, it's however still possible\
to use our own standalone autoloader. It is now located in `lib/autoload`
@@ -0,0 +1,88 @@
Because the V8 is **relatively** not backward compatible with the V7, here's a guide to help you to migrate your code:
### :warning: Minimum php version increased to 7.3+
As of the V8 the mandatory minimum php version has been increased to 7.3+.
Once released, the php version 8.0 will be unit-tested
### :warning: "Auto" driver removed
As of the V8 the "Auto" driver in `CacheManager::getInstance()` has been removed.\
You will now be mandatory to specify the driver to use.
#### :clock1: Then:
`CacheManager::getInstance('Auto')` or `CacheManager::getInstance()` expecting automatic driver chosen
#### :alarm_clock: Now:
Use `CacheManager::getInstance('Files')` or `CacheManager::getInstance('Redis')` or something else.
### Removal of "APC" driver
As of the V8 the "APC" has been removed. Use "APCu" instead.
#### :clock1: Then:
`CacheManager::getInstance('Apc')`
#### :alarm_clock: Now:
`CacheManager::getInstance('Apcu')`
### Removal of "Xcache" driver
As of the V8 the "Xcache" has been removed, no replacement have been made.\
It is [completely abandoned](https://xcache.lighttpd.net/) (latest update: 2014)
Use alternative memory cache such as Redis, Memcache, Ssdb, etc.
#### :clock1: Then:
`CacheManager::getInstance('Xcache')`
#### :alarm_clock: Now:
Find an alternative :)
### Phpfastcache API has been upgraded to 3.0.0
Check the [CHANGELOG_API.md](./../../CHANGELOG_API.md) to see the changes.
### Removal of static counters
As of the V8 the static I/O counter have been removed
#### :clock1: Then:
Calling `CacheManager::$ReadHits`, `CacheManager::$WriteHits`
#### :alarm_clock: Now:
Replaced by`\Phpfastcache\Entities\DriverIO` callable in`\Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface::getIO`
### Removal of deprecated method `CacheManager::setNamespacePath()`
As of the V8 the deprecated method `CacheManager::setNamespacePath()` have been removed.
#### :clock1: Then:
Calling `CacheManager::setNamespacePath('some\custom\path')`
#### :alarm_clock: Now:
Replaced by cache manager "override" or "custom driver" features introduced in V7
### Removal of deprecated method `CacheManager::getStaticSystemDrivers()`
As of the V8 the deprecated method `CacheManager::getStaticSystemDrivers()` have been removed.
#### :clock1: Then:
Calling `CacheManager::getStaticSystemDrivers()`
#### :alarm_clock: Now:
Replaced by `CacheManager::getDriverList()`
### Removal of `ActOnAll` helper
#### :clock1: Then:
The helper `ActOnAll` used to be useful to act on all instance
#### :alarm_clock: Now:
The "ActOnAll Helper" have been removed in profit of aggregated cluster support
### Removal of `fallback` feature
#### :clock1: Then:
The `fallback` features used to be useful when a backend failed to initialize
#### :alarm_clock: Now:
Use aggregated cluster Master/Slave instead
------
More infos in our comprehensive [changelog](./../../CHANGELOG.md).
@@ -0,0 +1,61 @@
Because the V9 is **relatively** not backward compatible with the V8, here's a guide to help you to migrate your code:
### :warning: Minimum php version increased to 8.0+
As of the V9 the mandatory php version has been increased to 8.0+.
Once released, the php versions 8.1, 8.2 will be unit-tested
### Embedded autoload has been removed (and therefore, embedded dependencies too)
Use [Composer](https://getcomposer.org/doc/03-cli.md#require) to include Phpfastcache in your project
### Removed magics methods from CacheManager `CacheManager::DriverName()`
Use `CacheManager::getInstance('DriverName')` instead.\
This decision was made to make the cache manager more consistent by removing the "old legacy code".
### Updated `ConfigurationOption` which is no longer an `ArrayObject` class
You can no longer use the following array-compatible syntax: `$config['yourKey'] = 'value'`\
Use the object-notation syntax instead: `$config->setYourKey('value')`
However, this syntax is STILL valid through the configuration constructor\
For the default config object: `new ConfigurationOption(['yourKey' => 'yourValue'])`\
Or for specific config objects: `new \Phpfastcache\Drivers\Files\Config(['yourKey' => 'yourValue'])`\
Finally, the config name you try to set MUST be recognized or an exception will be thrown.
### Deprecated `\Phpfastcache\Helper\CacheConditionalHelper`
Use `\Phpfastcache\CacheContract` instead. See [Wiki](https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV9%CB%96%5D-Cache-contract).
### Removed `Couchbase` driver (SDK 2 support dropped)
It is now replaced by `Couchbasev3` driver (SDK 3), the configuration options remains the same plus `scopeName` and `collectionName` that are now configurable.
### Updated EventManager callback parameters
- Updated argument type #2 (`$items`) of `onCacheSaveMultipleItems()` event from `ExtendedCacheItemInterface[]` to `EventReferenceParameter($items)`
- Updated argument type #2 (`$items`) of `onCacheCommitItem()` event from `ExtendedCacheItemInterface[]` to `EventReferenceParameter($items)`
- Updated argument type #2 (`$value`) of `onCacheItemSet()` event from `mixed` to `EventReferenceParameter(mixed $value)`
See [EVENTS.md](./../EVENTS.md) file for more information
### Upgraded Phpfastcache API
- The Phpfastcache API has been upgraded to `4.0.0` introducing BC breaks. [See full changes](./../../CHANGELOG_API.md)
- Renamed `Api::getPhpFastCacheVersion()` to `Api::getPhpfastcacheVersion()`
- Renamed `Api::getPhpFastCacheChangelog()` to `Api::getPhpfastcacheChangelog()`
- Renamed `Api::getPhpFastCacheGitHeadHash()` to `Api::getPhpfastcacheGitHeadHash()`
### Removed `Devtrue` and `Devfalse` drivers
They have not been replaced.
However, the `Devrandom` driver with configurable factor chance and data length has been added
### Removed configuration entry `htaccess` for files-based drivers.
- We consider that it's no longer the task of Phpfastcache to handle server configuration
- Removed `IOConfigurationOptionTrait::getHtaccess()`
- Removed `IOConfigurationOptionTrait::setHtaccess()`
### Configuration object will now be locked once the cache pool instance is running
If you try to set a configuration value after the cache pool instance is being built, an exception will be thrown.
### Removed `Cookie` driver because of its potential dangerousness
However, you can always implement it by yourself if you want to by putting it back from previous versions using `\Phpfastcache\CacheManager::addCustomDriver()` method
------
More information in our comprehensive [changelog](./../../CHANGELOG.md).
@@ -0,0 +1,31 @@
Because the V9.2 is **completely** backward compatible with the V9.1, there's a small guide to help you to migrate your code:
### :warning: Phpfastcache core drivers has been moved to their own extensions
If you were using one of those drivers:
`Arangodb`
`Couchdb`
`Dynamodb`
`Firestore`
`Mongodb`
`Solr`
Your **CODE IS SAFE AND FINE**, you just need to add a new composer dependency, ex:
```bash
composer install phpfastcache/arangodb-extension
```
### :new: Couchbasev4 has been as an extension:
```bash
composer install phpfastcache/couchbasev4-extension
```
However `Couchbasev3` **will stay in the core** for compatibility reasons but will be deprecated.
That's it :)
------
More information in our comprehensive [changelog](./../../CHANGELOG.md).
@@ -0,0 +1,162 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache;
use Phpfastcache\Exceptions\PhpfastcacheIOException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Phpfastcache\Helper\UninstanciableObjectTrait;
/**
* Class Api
* @package Phpfastcache
*/
class Api
{
use UninstanciableObjectTrait;
protected static string $version = '4.3.0';
/**
* This method will return the current
* API version, the API version will be
* updated by following the semantic versioning
* based on changes of:
* - ExtendedCacheItemPoolInterface
* - ExtendedCacheItemInterface
* - AggregatablePoolInterface
* - AggregatorInterface
* - ClusterPoolInterface
* - EventManagerInterface
*
* @see https://semver.org/
* @return string
*/
public static function getVersion(): string
{
return self::$version;
}
/**
* @param bool $fallbackOnChangelog
* @param bool $cacheable
* @return string
* @throws PhpfastcacheLogicException
* @throws PhpfastcacheIOException
*/
public static function getPhpfastcacheVersion(bool $fallbackOnChangelog = true, bool $cacheable = true): string
{
/**
* Cache the version statically to improve
* performances on multiple calls
*/
static $version;
if ($version && $cacheable) {
return $version;
}
if (\function_exists('shell_exec')) {
$command = 'git -C "' . __DIR__ . '" describe --abbrev=0 --tags ' . (DIRECTORY_SEPARATOR === '\\' ? '2>nul' : '2>/dev/null');
$stdout = \shell_exec($command);
if (\is_string($stdout)) {
return trim($stdout);
}
if (!$fallbackOnChangelog) {
throw new PhpfastcacheLogicException('The git command used to retrieve the Phpfastcache version has failed.');
}
}
if (!$fallbackOnChangelog) {
throw new PhpfastcacheLogicException('shell_exec is disabled therefore the Phpfastcache version cannot be retrieved.');
}
$changelogFilename = __DIR__ . '/../../CHANGELOG.md';
if (\file_exists($changelogFilename)) {
$semverRegexp = '/^([\d]+)\.([\d]+)\.([\d]+)(?:-([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?(?:\+[\dA-Za-z-]+)?$/';
$changelog = \explode("\n", self::getPhpfastcacheChangelog());
foreach ($changelog as $line) {
$trimmedLine = \trim($line, " \t\n\r\0\x0B#");
if (\str_starts_with($line, '#') && \preg_match($semverRegexp, $trimmedLine)) {
return $trimmedLine;
}
}
throw new PhpfastcacheLogicException('Unable to retrieve the Phpfastcache version through the CHANGELOG.md as no valid string were found in it.');
}
throw new PhpfastcacheLogicException(
'shell_exec being disabled we attempted to retrieve the Phpfastcache version through the CHANGELOG.md file but it is not readable or has been removed.'
);
}
/**
* Return the Phpfastcache changelog, as a string.
* @return string
* @throws PhpfastcacheLogicException
* @throws PhpfastcacheIOException
*/
public static function getPhpfastcacheChangelog(): string
{
$changelogFilename = __DIR__ . '/../../CHANGELOG.md';
if (\file_exists($changelogFilename)) {
$string = \str_replace(["\r\n", "\r"], "\n", \trim(\file_get_contents($changelogFilename)));
if ($string) {
return $string;
}
throw new PhpfastcacheLogicException('Unable to retrieve the Phpfastcache changelog as it seems to be empty.');
}
throw new PhpfastcacheIOException('The CHANGELOG.md file is not readable or has been removed.');
}
/**
* @param bool $cacheable
* @return string
*/
public static function getPhpfastcacheGitHeadHash(bool $cacheable = true): string
{
static $hash;
if ($hash && $cacheable) {
return $hash;
}
if (\function_exists('shell_exec')) {
$stdout = \shell_exec('git rev-parse --short HEAD ' . (DIRECTORY_SEPARATOR === '\\' ? '2>nul' : '2>/dev/null'));
if (\is_string($stdout)) {
return '#' . \trim($stdout);
}
}
return '';
}
/**
* Return the API changelog, as a string.
* @return string
* @throws PhpfastcacheLogicException
* @throws PhpfastcacheIOException
*/
public static function getChangelog(): string
{
$changelogFilename = __DIR__ . '/../../CHANGELOG_API.md';
if (\file_exists($changelogFilename)) {
$string = \str_replace(["\r\n", "\r"], "\n", \trim(\file_get_contents($changelogFilename)));
if ($string) {
return $string;
}
throw new PhpfastcacheLogicException('Unable to retrieve the Phpfastcache API changelog as it seems to be empty.');
}
throw new PhpfastcacheIOException('The CHANGELOG_API.md file is not readable or has been removed.');
}
}
@@ -0,0 +1,61 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache;
use DateInterval;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException;
class CacheContract
{
protected CacheItemPoolInterface $cacheInstance;
public function __construct(CacheItemPoolInterface $cacheInstance)
{
$this->cacheInstance = $cacheInstance;
}
/**
* @throws InvalidArgumentException
*/
public function get(string|\Stringable $cacheKey, callable $callback, DateInterval|int|null $expiresAfter = null): mixed
{
$cacheItem = $this->cacheInstance->getItem((string) $cacheKey);
if (!$cacheItem->isHit()) {
/*
* Parameter $cacheItem will be available as of 8.0.6
*/
$cacheItem->set($callback($cacheItem));
if ($expiresAfter) {
$cacheItem->expiresAfter($expiresAfter);
}
$this->cacheInstance->save($cacheItem);
}
return $cacheItem->get();
}
/**
* @throws InvalidArgumentException
*/
public function __invoke(string $cacheKey, callable $callback, DateInterval|int|null $expiresAfter = null): mixed
{
return $this->get($cacheKey, $callback, $expiresAfter);
}
}
@@ -0,0 +1,445 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Config\ConfigurationOptionInterface;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException;
use Phpfastcache\Exceptions\PhpfastcacheDriverException;
use Phpfastcache\Exceptions\PhpfastcacheDriverNotFoundException;
use Phpfastcache\Exceptions\PhpfastcacheExtensionNotFoundException;
use Phpfastcache\Exceptions\PhpfastcacheExtensionNotInstalledException;
use Phpfastcache\Exceptions\PhpfastcacheInstanceNotFoundException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Phpfastcache\Exceptions\PhpfastcacheUnsupportedOperationException;
use Phpfastcache\Helper\UninstanciableObjectTrait;
use Phpfastcache\Util\ClassNamespaceResolverTrait;
/**
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
*/
class CacheManager
{
use ClassNamespaceResolverTrait;
use UninstanciableObjectTrait;
public const CORE_DRIVER_NAMESPACE = 'Phpfastcache\Drivers\\';
protected static ConfigurationOptionInterface $config;
protected static string $namespacePath;
/**
* @var ExtendedCacheItemPoolInterface[]
*/
protected static array $instances = [];
/**
* @var string[]
*/
protected static array $driverOverrides = [];
/**
* @var string[]
*/
protected static array $driverCustoms = [];
/**
* @var string[]
*/
protected static array $driverExtensions = [];
/**
* @param string $instanceId
* @return ExtendedCacheItemPoolInterface
* @throws PhpfastcacheInstanceNotFoundException
*/
public static function getInstanceById(string $instanceId): ExtendedCacheItemPoolInterface
{
if (isset(self::$instances[$instanceId])) {
return self::$instances[$instanceId];
}
throw new PhpfastcacheInstanceNotFoundException(sprintf('Instance ID %s not found', $instanceId));
}
/**
* Return the list of instances
*
* @return ExtendedCacheItemPoolInterface[]
*/
public static function getInstances(): array
{
return self::$instances;
}
/**
* @param string $driver
* @param ConfigurationOptionInterface|null $config
* @param string|null $instanceId
* @return ExtendedCacheItemPoolInterface
* @throws PhpfastcacheDriverCheckException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheDriverNotFoundException
* @throws PhpfastcacheExtensionNotInstalledException
* @throws PhpfastcacheLogicException
*/
public static function getInstance(string $driver, ?ConfigurationOptionInterface $config = null, ?string $instanceId = null): ExtendedCacheItemPoolInterface
{
if (\class_exists($driver) && \str_starts_with($driver, 'Phpfastcache')) {
$driverClass = $driver;
} else {
$driver = self::normalizeDriverName($driver);
$driverClass = self::getDriverClass($driver);
}
$config = self::validateConfig($config);
$instanceId = $instanceId ?: self::getInstanceHash($driverClass, $config);
if (!isset(self::$instances[$instanceId])) {
if (\is_a($driverClass, ExtendedCacheItemPoolInterface::class, true)) {
if (($configClass = $driverClass::getConfigClass()) !== $config::class) {
$config = new $configClass($config->toArray());
}
self::$instances[$instanceId] = new $driverClass(
$config,
$instanceId,
EventManager::getInstance()
);
} else {
try {
self::$driverExtensions[$driver] = ExtensionManager::getExtension($driver);
return CacheManager::getInstance($driver, $config, $instanceId);
} catch (PhpfastcacheExtensionNotFoundException) {
if (in_array($driver, ExtensionManager::KNOWN_EXTENSION_NAMES, true)) {
throw new PhpfastcacheExtensionNotInstalledException(sprintf(
'You requested a driver which is now an extension. Run the following command to solve this issue: %s',
sprintf('composer install phpfastcache/%s-extension', strtolower($driver))
));
}
throw new PhpfastcacheDriverNotFoundException(sprintf(
'The driver "%s" does not exist or does not implement %s.',
$driver,
ExtendedCacheItemPoolInterface::class,
));
}
}
}
return self::$instances[$instanceId];
}
/**
* @param string $driverClass
* @param ConfigurationOptionInterface $config
* @return string
*/
protected static function getInstanceHash(string $driverClass, ConfigurationOptionInterface $config): string
{
return \md5($driverClass . \serialize(
\array_filter(
$config->toArray(),
static fn ($val) => $config->isValueSerializable($val)
)
));
}
/**
* @param ConfigurationOptionInterface|null $config
* @return ConfigurationOptionInterface
* @throws PhpfastcacheLogicException
*/
protected static function validateConfig(?ConfigurationOptionInterface $config): ConfigurationOptionInterface
{
if ($config instanceof ConfigurationOptionInterface && $config->isLocked()) {
throw new PhpfastcacheLogicException('You provided an already locked configuration, cannot continue.');
}
return $config ?? self::getDefaultConfig();
}
/**
* @return ConfigurationOptionInterface
*/
public static function getDefaultConfig(): ConfigurationOptionInterface
{
return self::$config ?? self::$config = new ConfigurationOption();
}
/**
* @param string $driverName
* @return string
*/
public static function normalizeDriverName(string $driverName): string
{
return \ucfirst(\strtolower(\trim($driverName)));
}
/**
* @param string $driverName
* @return string
*/
public static function getDriverClass(string $driverName): string
{
if (!empty(self::$driverExtensions[$driverName])) {
$driverClass = self::$driverExtensions[$driverName];
} elseif (!empty(self::$driverCustoms[$driverName])) {
$driverClass = self::$driverCustoms[$driverName];
} elseif (!empty(self::$driverOverrides[$driverName])) {
$driverClass = self::$driverOverrides[$driverName];
} else {
$driverClass = self::getNamespacePath() . $driverName . '\Driver';
}
return $driverClass;
}
/**
* @return string
*/
public static function getNamespacePath(): string
{
return self::$namespacePath ?? self::getDefaultNamespacePath();
}
/**
* @return string
*/
public static function getDefaultNamespacePath(): string
{
return self::CORE_DRIVER_NAMESPACE;
}
/**
* @return bool
*/
public static function clearInstances(): bool
{
self::$instances = [];
\gc_collect_cycles();
return true;
}
/**
* @param ExtendedCacheItemPoolInterface $cachePoolInstance
* @return bool
* @since 7.0.4
*/
public static function clearInstance(ExtendedCacheItemPoolInterface $cachePoolInstance): bool
{
$found = false;
self::$instances = \array_filter(
\array_map(
static function (ExtendedCacheItemPoolInterface $cachePool) use ($cachePoolInstance, &$found) {
if (\spl_object_hash($cachePool) === \spl_object_hash($cachePoolInstance)) {
$found = true;
return null;
}
return $cachePool;
},
self::$instances
)
);
return $found;
}
/**
* @param ConfigurationOptionInterface $config
* @throws PhpfastcacheInvalidArgumentException
*/
public static function setDefaultConfig(ConfigurationOptionInterface $config): void
{
if (\is_subclass_of($config, ConfigurationOption::class)) {
throw new PhpfastcacheInvalidArgumentException('Default configuration cannot be a child class of ConfigurationOption::class');
}
self::$config = $config;
}
/**
* @param string $driverName
* @param string $className
* @return void
* @throws PhpfastcacheLogicException
* @throws PhpfastcacheUnsupportedOperationException
* @throws PhpfastcacheInvalidArgumentException
*/
public static function addCustomDriver(string $driverName, string $className): void
{
$driverName = self::normalizeDriverName($driverName);
if (empty($driverName)) {
throw new PhpfastcacheInvalidArgumentException("Can't add a custom driver because its name is empty");
}
if (!\class_exists($className)) {
throw new PhpfastcacheInvalidArgumentException(
\sprintf("Can't add '%s' because the class '%s' does not exist", $driverName, $className)
);
}
if (!empty(self::$driverCustoms[$driverName])) {
throw new PhpfastcacheLogicException(\sprintf("Driver '%s' has been already added", $driverName));
}
if (\in_array($driverName, self::getDriverList(), true)) {
throw new PhpfastcacheLogicException(\sprintf("Driver '%s' is already a part of the Phpfastcache core", $driverName));
}
self::$driverCustoms[$driverName] = $className;
}
/**
* @param string $driverName
* @return bool
*/
public static function customDriverExists(string $driverName): bool
{
return isset(self::$driverCustoms[$driverName]);
}
/**
* Return the list of available drivers Capitalized
* with optional FQCN as key
*
* @param bool $fqcnAsKey Describe keys with Full Qualified Class Name
* @return string[]
* @throws PhpfastcacheUnsupportedOperationException
*/
public static function getDriverList(bool $fqcnAsKey = false): array
{
static $driverList;
if (self::getDefaultNamespacePath() === self::getNamespacePath()) {
if ($driverList === null) {
$prefix = self::CORE_DRIVER_NAMESPACE;
$classMap = self::createClassMap(__DIR__ . '/Drivers');
$driverList = [];
foreach (\array_keys($classMap) as $class) {
$driverList[] = \str_replace($prefix, '', \substr($class, 0, \strrpos($class, '\\')));
}
$driverList = \array_values(\array_unique($driverList));
}
$driverList = \array_merge($driverList, \array_keys(self::$driverCustoms));
if ($fqcnAsKey) {
$realDriverList = [];
foreach ($driverList as $driverName) {
$realDriverList[self::getDriverClass($driverName)] = $driverName;
}
$driverList = $realDriverList;
}
\asort($driverList);
return $driverList;
}
throw new PhpfastcacheUnsupportedOperationException('Cannot get the driver list if the default namespace path has changed.');
}
/**
* @param string $driverName
* @return void
* @throws PhpfastcacheLogicException
* @throws PhpfastcacheInvalidArgumentException
*/
public static function removeCustomDriver(string $driverName): void
{
$driverName = self::normalizeDriverName($driverName);
if (empty($driverName)) {
throw new PhpfastcacheInvalidArgumentException("Can't remove a custom driver because its name is empty");
}
if (!isset(self::$driverCustoms[$driverName])) {
throw new PhpfastcacheLogicException(\sprintf("Driver '%s' does not exist", $driverName));
}
unset(self::$driverCustoms[$driverName]);
}
/**
* @param string $driverName
* @param string $className
* @return void
* @throws PhpfastcacheLogicException
* @throws PhpfastcacheUnsupportedOperationException
* @throws PhpfastcacheInvalidArgumentException
*/
public static function addCoreDriverOverride(string $driverName, string $className): void
{
$driverName = self::normalizeDriverName($driverName);
if (empty($driverName)) {
throw new PhpfastcacheInvalidArgumentException("Can't add a core driver override because its name is empty");
}
if (!\class_exists($className)) {
throw new PhpfastcacheInvalidArgumentException(
\sprintf("Can't override '%s' because the class '%s' does not exist", $driverName, $className)
);
}
if (!empty(self::$driverOverrides[$driverName])) {
throw new PhpfastcacheLogicException(\sprintf("Driver '%s' has been already overridden", $driverName));
}
if (!\in_array($driverName, self::getDriverList(), true)) {
throw new PhpfastcacheLogicException(\sprintf("Driver '%s' can't be overridden since its not a part of the Phpfastcache core", $driverName));
}
if (!\is_subclass_of($className, self::CORE_DRIVER_NAMESPACE . $driverName . '\\Driver', true)) {
throw new PhpfastcacheLogicException(
\sprintf(
"Can't override '%s' because the class '%s' MUST extend '%s'",
$driverName,
$className,
self::CORE_DRIVER_NAMESPACE . $driverName . '\\Driver'
)
);
}
self::$driverOverrides[$driverName] = $className;
}
/**
* @param string $driverName
* @return void
* @throws PhpfastcacheLogicException
* @throws PhpfastcacheInvalidArgumentException
*/
public static function removeCoreDriverOverride(string $driverName): void
{
$driverName = self::normalizeDriverName($driverName);
if (empty($driverName)) {
throw new PhpfastcacheInvalidArgumentException("Can't remove a core driver override because its name is empty");
}
if (!isset(self::$driverOverrides[$driverName])) {
throw new PhpfastcacheLogicException(\sprintf("Driver '%s' were not overridden", $driverName));
}
unset(self::$driverOverrides[$driverName]);
}
}
@@ -0,0 +1,26 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt file.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
declare(strict_types=1);
namespace Phpfastcache\Cluster;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
interface AggregatablePoolInterface extends ExtendedCacheItemPoolInterface
{
public function isAggregatedBy(): ?ClusterPoolInterface;
public function setAggregatedBy(ClusterPoolInterface $clusterPool): static;
}
@@ -0,0 +1,100 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt file.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
declare(strict_types=1);
namespace Phpfastcache\Cluster;
use Phpfastcache\Config\ConfigurationOption;
interface AggregatorInterface
{
/**
* Full replication mechanism
*
* Read on first working (and synchronize if needed, no failure allowed),
* Write on all (no failure allowed),
* Delete on all (no failure allowed)
*
* Conflict on multiple reads: Keep first found item (but sync the others)
* Cluster size: 2 minimum, unlimited
*/
public const STRATEGY_FULL_REPLICATION = 1;
/**
* Semi replication mechanism
*
* Read first working (but do not synchronize, with partial failure allowed),
* Write on all (with partial failure allowed)
* Delete on all (with partial failure allowed)
*
* Conflict on multiple reads: Keep first found item
* Cluster size: 2 minimum, unlimited
*/
public const STRATEGY_SEMI_REPLICATION = 2;
/**
* First pool is master, second is slave
*
* Read from master (but do not synchronize, with master failure only allowed)
* Write on all (with master failure only allowed)
* Delete on all (with master failure only allowed)
*
* Conflict on multiple reads: No, master is exclusive source except if it fails
* Cluster size: 2 exactly: Master & Slave (Exception if more or less)
*/
public const STRATEGY_MASTER_SLAVE = 4;
/**
* Mostly used for development testing
*
* CRUD operations are made on a random-chosen backend from a given cluster.
* This means you have 1 chance out of (n count of pools) to find an existing cache item
* but also to write/delete a non-existing item.
*/
public const STRATEGY_RANDOM_REPLICATION = 8;
/**
* AggregatorInterface constructor.
*
* @param string $clusterAggregatorName
* @param AggregatablePoolInterface ...$driverPools
*/
public function __construct(string $clusterAggregatorName, AggregatablePoolInterface ...$driverPools);
/**
* @param int $strategy
*
* @return ClusterPoolInterface
*/
public function getCluster(int $strategy): ClusterPoolInterface;
/**
* @param string $driverName
* @param ConfigurationOption|NULL $driverConfig
*
* @return void
*/
public function aggregateDriverByName(string $driverName, ?ConfigurationOption $driverConfig = null): void;
/**
* @param AggregatablePoolInterface $driverPool
*/
public function aggregateDriver(AggregatablePoolInterface $driverPool): void;
/**
* @param AggregatablePoolInterface $driverPool
*/
public function disaggregateDriver(AggregatablePoolInterface $driverPool): void;
}
@@ -0,0 +1,170 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt file.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
declare(strict_types=1);
namespace Phpfastcache\Cluster;
use Exception;
use Phpfastcache\CacheManager;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Event\Event;
use Phpfastcache\EventManager;
use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException;
use Phpfastcache\Exceptions\PhpfastcacheDriverException;
use Phpfastcache\Exceptions\PhpfastcacheDriverNotFoundException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use stdClass;
class ClusterAggregator implements AggregatorInterface
{
/**
* @var array<string, AggregatablePoolInterface>
*/
protected array $driverPools;
protected ClusterPoolInterface $cluster;
protected string $clusterAggregatorName;
/**
* ClusterAggregator constructor.
* @param string $clusterAggregatorName
* @param array<AggregatablePoolInterface> $driverPools
* @throws PhpfastcacheLogicException
*/
public function __construct(string $clusterAggregatorName = '', AggregatablePoolInterface ...$driverPools)
{
$clusterAggregatorName = trim($clusterAggregatorName);
if (empty($clusterAggregatorName)) {
try {
$clusterAggregatorName = 'cluster_' . \bin2hex(\random_bytes(15));
} catch (Exception) {
$clusterAggregatorName = 'cluster_' . \str_shuffle(\spl_object_hash(new stdClass()));
}
}
$this->clusterAggregatorName = $clusterAggregatorName;
foreach ($driverPools as $driverPool) {
$this->aggregateDriver($driverPool);
}
}
/**
* @param AggregatablePoolInterface $driverPool
*
* @throws PhpfastcacheLogicException
*/
public function aggregateDriver(AggregatablePoolInterface $driverPool): void
{
if (isset($this->cluster)) {
throw new PhpfastcacheLogicException('The cluster has been already build, cannot aggregate more pools.');
}
$splHash = \spl_object_hash($driverPool);
if (!isset($this->driverPools[$splHash])) {
if ($driverPool instanceof ClusterPoolInterface) {
throw new PhpfastcacheLogicException('Recursive cluster aggregation is not allowed !');
}
$this->driverPools[$splHash] = $driverPool;
} else {
throw new PhpfastcacheLogicException('This pool has been already aggregated !');
}
}
/**
* @param string $driverName
* @param ConfigurationOption|null $driverConfig
* @throws PhpfastcacheDriverCheckException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheDriverNotFoundException
* @throws PhpfastcacheLogicException
*/
public function aggregateDriverByName(string $driverName, ?ConfigurationOption $driverConfig = null): void
{
if (isset($this->cluster)) {
throw new PhpfastcacheLogicException('The cluster has been already build, cannot aggregate more pools.');
}
$driverInstance = CacheManager::getInstance($driverName, $driverConfig);
if ($driverInstance instanceof AggregatablePoolInterface) {
$this->aggregateDriver($driverInstance);
}
throw new PhpfastcacheDriverException(
\sprintf(
'Driver "%s" does not implements "%s"',
$driverInstance::class,
AggregatablePoolInterface::class
)
);
}
/**
* @param AggregatablePoolInterface $driverPool
*
* @throws PhpfastcacheLogicException
*/
public function disaggregateDriver(AggregatablePoolInterface $driverPool): void
{
if (isset($this->cluster)) {
throw new PhpfastcacheLogicException('The cluster has been already build, cannot disaggregate pools.');
}
$splHash = \spl_object_hash($driverPool);
if (isset($this->driverPools[$splHash])) {
unset($this->driverPools[$splHash]);
} else {
throw new PhpfastcacheLogicException('This pool was not aggregated !');
}
}
/**
* @param int $strategy
*
* @return ClusterPoolInterface
* @throws PhpfastcacheInvalidArgumentException
*/
public function getCluster(int $strategy = AggregatorInterface::STRATEGY_FULL_REPLICATION): ClusterPoolInterface
{
if (isset(ClusterPoolAbstract::STRATEGY[$strategy])) {
if (!isset($this->cluster)) {
$clusterClass = ClusterPoolAbstract::STRATEGY[$strategy];
$this->cluster = new $clusterClass(
$this->getClusterAggregatorName(),
EventManager::getInstance(),
...\array_values($this->driverPools)
);
$this->cluster->getEventManager()->dispatch(Event::CACHE_CLUSTER_BUILT, $this, $this->cluster);
}
} else {
throw new PhpfastcacheInvalidArgumentException('Unknown cluster strategy');
}
return $this->cluster;
}
/**
* @return string
*/
public function getClusterAggregatorName(): string
{
return $this->clusterAggregatorName;
}
}
@@ -0,0 +1,250 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt file.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
declare(strict_types=1);
namespace Phpfastcache\Cluster;
use Phpfastcache\Cluster\Drivers\FullReplication\Driver as FullReplicationCluster;
use Phpfastcache\Cluster\Drivers\MasterSlaveReplication\Driver as MasterSlaveReplicationCluster;
use Phpfastcache\Cluster\Drivers\RandomReplication\Driver as RandomReplicationCluster;
use Phpfastcache\Cluster\Drivers\SemiReplication\Driver as SemiReplicationCluster;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait;
use Phpfastcache\Entities\DriverIO;
use Phpfastcache\Entities\DriverStatistic;
use Phpfastcache\Event\EventManagerInterface;
use Phpfastcache\EventManager;
use Phpfastcache\Exceptions\PhpfastcacheCoreException;
use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException;
use Phpfastcache\Exceptions\PhpfastcacheDriverConnectException;
use Phpfastcache\Exceptions\PhpfastcacheDriverException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheIOException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\InvalidArgumentException;
abstract class ClusterPoolAbstract implements ClusterPoolInterface
{
use TaggableCacheItemPoolTrait;
use ClusterPoolTrait {
TaggableCacheItemPoolTrait::__construct as private __parentConstruct;
}
public const STRATEGY = [
AggregatorInterface::STRATEGY_FULL_REPLICATION => FullReplicationCluster::class,
AggregatorInterface::STRATEGY_SEMI_REPLICATION => SemiReplicationCluster::class,
AggregatorInterface::STRATEGY_MASTER_SLAVE => MasterSlaveReplicationCluster::class,
AggregatorInterface::STRATEGY_RANDOM_REPLICATION => RandomReplicationCluster::class,
];
/**
* @var AggregatablePoolInterface[]
*/
protected array $clusterPools;
/**
* ClusterPoolAbstract constructor.
* @param string $clusterName
* @param EventManagerInterface $em
* @param ExtendedCacheItemPoolInterface ...$driverPools
* @throws PhpfastcacheDriverCheckException
* @throws PhpfastcacheDriverConnectException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheIOException
*/
public function __construct(string $clusterName, EventManagerInterface $em, AggregatablePoolInterface ...$driverPools)
{
if (count($driverPools) < 2) {
throw new PhpfastcacheInvalidArgumentException('A cluster requires at least two pools to be working.');
}
$this->clusterPools = $driverPools;
$this->__parentConstruct(new ConfigurationOption(), $clusterName, $em);
$this->setEventManager(EventManager::getInstance());
$this->setClusterPoolsAggregator();
}
protected function setClusterPoolsAggregator(): void
{
foreach ($this->clusterPools as $clusterPool) {
$clusterPool->setAggregatedBy($this);
}
}
/**
* @inheritDoc
*/
public function getIO(): DriverIO
{
$io = new DriverIO();
foreach ($this->clusterPools as $clusterPool) {
$io->setReadHit($io->getReadHit() + $clusterPool->getIO()->getReadHit())
->setReadMiss($io->getReadMiss() + $clusterPool->getIO()->getReadMiss())
->setWriteHit($io->getWriteHit() + $clusterPool->getIO()->getWriteHit());
}
return $io;
}
/**
* @inheritDoc
*/
public function getClusterPools(): array
{
return $this->clusterPools;
}
/**
* @inheritDoc
*/
public function getConfigs(): array
{
$configs = [];
foreach ($this->getClusterPools() as $clusterPool) {
$configs[$clusterPool->getDriverName()] = $clusterPool->getConfig();
}
return $configs;
}
/**
* @inheritDoc
*/
public function getItems(array $keys = []): iterable
{
$items = [];
foreach ($keys as $key) {
$items[$key] = $this->getItem($key);
}
return $items;
}
/**
* Shared method used by All Clusters
*/
/**
* @inheritDoc
*/
public function deleteItems(array $keys): bool
{
$hasDeletedOnce = false;
foreach ($this->clusterPools as $driverPool) {
if ($result = $driverPool->deleteItems($keys)) {
$hasDeletedOnce = $result;
}
}
// Return true only if at least one backend confirmed the "clear" operation
return $hasDeletedOnce;
}
/**
* @param CacheItemInterface $item
* @return bool
* @throws InvalidArgumentException
* @throws PhpfastcacheLogicException
*/
public function saveDeferred(CacheItemInterface $item): bool
{
/** @var ExtendedCacheItemInterface $item */
$hasSavedOnce = false;
foreach ($this->clusterPools as $driverPool) {
$poolItem = $this->getStandardizedItem($item, $driverPool);
if ($result = $driverPool->saveDeferred($poolItem)) {
$hasSavedOnce = $result;
}
}
// Return true only if at least one backend confirmed the "commit" operation
return $hasSavedOnce;
}
/**
* @param ExtendedCacheItemInterface $item
* @param ExtendedCacheItemPoolInterface $driverPool
* @return ExtendedCacheItemInterface
* @throws InvalidArgumentException
* @throws PhpfastcacheLogicException
*/
protected function getStandardizedItem(ExtendedCacheItemInterface $item, ExtendedCacheItemPoolInterface $driverPool): ExtendedCacheItemInterface
{
if (!$item->doesItemBelongToThatDriverBackend($driverPool)) {
/**
* Avoid infinite loop
*/
if ($driverPool === $this) {
/** @var ExtendedCacheItemInterface $itemPool */
$itemClass = $driverPool::getItemClass();
$itemPool = new $itemClass($this, $item->getKey(), $this->getEventManager());
$item->cloneInto($itemPool, $driverPool);
return $itemPool;
}
$itemPool = $driverPool->getItem($item->getKey());
$item->cloneInto($itemPool, $driverPool);
return $itemPool;
}
return $item->setEventManager($this->getEventManager());
}
/**
* @return DriverStatistic
*/
public function getStats(): DriverStatistic
{
$stats = new DriverStatistic();
$stats->setInfo(
sprintf(
'Using %d pool(s): %s',
\count($this->clusterPools),
\implode(
', ',
\array_map(
static fn (ExtendedCacheItemPoolInterface $pool) => \get_class($pool),
$this->clusterPools
)
)
)
);
$stats->setSize(
(int)\array_sum(
\array_map(
static fn (ExtendedCacheItemPoolInterface $pool) => $pool->getStats()->getSize(),
$this->clusterPools
)
)
);
$stats->setData(
\implode(
', ',
\array_map(
static fn (ExtendedCacheItemPoolInterface $pool) => $pool->getStats()->getData(),
$this->clusterPools
)
)
);
return $stats;
}
}
@@ -0,0 +1,33 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt file.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
declare(strict_types=1);
namespace Phpfastcache\Cluster;
use Phpfastcache\Config\ConfigurationOptionInterface;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
interface ClusterPoolInterface extends ExtendedCacheItemPoolInterface
{
/**
* @return AggregatablePoolInterface[]
*/
public function getClusterPools(): array;
/**
* @return ConfigurationOptionInterface[]
*/
public function getConfigs(): array;
}
@@ -0,0 +1,69 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt file.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
declare(strict_types=1);
namespace Phpfastcache\Cluster;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Psr\Cache\CacheItemInterface;
trait ClusterPoolTrait
{
protected function driverCheck(): bool
{
return true;
}
protected function driverConnect(): bool
{
return true;
}
/**
* @param ExtendedCacheItemInterface $item
* @return ?array<string, mixed>
*/
protected function driverRead(ExtendedCacheItemInterface $item): ?array
{
return null;
}
/**
* @param ExtendedCacheItemInterface $item
* @return bool
*/
protected function driverWrite(ExtendedCacheItemInterface $item): bool
{
return true;
}
/**
* @param string $key
* @param string $encodedKey
* @return bool
*/
protected function driverDelete(string $key, string $encodedKey): bool
{
return true;
}
/**
* @return bool
*/
protected function driverClear(): bool
{
return true;
}
}
@@ -0,0 +1,188 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt file.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
declare(strict_types=1);
namespace Phpfastcache\Cluster\Drivers\FullReplication;
use Phpfastcache\Cluster\ClusterPoolAbstract;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Psr\Cache\CacheItemInterface;
class Driver extends ClusterPoolAbstract
{
/**
* @inheritDoc
*/
public function getItem(string $key): ExtendedCacheItemInterface
{
/** @var ExtendedCacheItemPoolInterface[] $poolsToResync */
$poolsToResync = [];
/** @var ?ExtendedCacheItemInterface $item */
$item = null;
foreach ($this->clusterPools as $driverPool) {
$poolItem = $driverPool->getItem($key);
if ($poolItem->isHit()) {
if (!$item) {
$item = $poolItem;
continue;
}
$itemData = $item->get();
$poolItemData = $poolItem->get();
if (\is_object($itemData)) {
if ($item->get() != $poolItemData) {
$poolsToResync[] = $driverPool;
}
} else {
if ($item->get() !== $poolItemData) {
$poolsToResync[] = $driverPool;
}
}
} else {
$poolsToResync[] = $driverPool;
}
}
$this->resynchronizePool($poolsToResync, $key, $item);
if ($item === null) {
$item = new Item($this, $key, $this->getEventManager());
$item->expiresAfter((int) abs($this->getConfig()->getDefaultTtl()));
}
return $this->getStandardizedItem($item, $this);
}
/**
* @inheritDoc
*/
public function hasItem(string $key): bool
{
foreach ($this->clusterPools as $driverPool) {
$poolItem = $driverPool->getItem($key);
if ($poolItem->isHit()) {
return true;
}
}
return false;
}
/**
* @inheritDoc
*/
public function clear(): bool
{
$hasClearedOnce = false;
foreach ($this->clusterPools as $driverPool) {
if ($result = $driverPool->clear()) {
$hasClearedOnce = $result;
}
}
// Return true only if at least one backend confirmed the "clear" operation
return $hasClearedOnce;
}
/**
* @inheritDoc
*/
public function deleteItem(string $key): bool
{
$hasDeletedOnce = false;
foreach ($this->clusterPools as $driverPool) {
if ($result = $driverPool->deleteItem($key)) {
$hasDeletedOnce = $result;
}
}
// Return true only if at least one backend confirmed the "clear" operation
return $hasDeletedOnce;
}
/**
* @inheritDoc
*/
public function save(CacheItemInterface $item): bool
{
/** @var ExtendedCacheItemInterface $item */
$hasSavedOnce = false;
foreach ($this->clusterPools as $driverPool) {
$poolItem = $this->getStandardizedItem($item, $driverPool);
if ($result = $driverPool->save($poolItem)) {
$hasSavedOnce = $result;
}
}
// Return true only if at least one backend confirmed the "commit" operation
return $hasSavedOnce;
}
/**
* @inheritDoc
*/
public function saveDeferred(CacheItemInterface $item): bool
{
/** @var ExtendedCacheItemInterface $item */
$hasSavedOnce = false;
foreach ($this->clusterPools as $driverPool) {
$poolItem = $this->getStandardizedItem($item, $driverPool);
if ($result = $driverPool->saveDeferred($poolItem)) {
$hasSavedOnce = $result;
}
}
// Return true only if at least one backend confirmed the "commit" operation
return $hasSavedOnce;
}
/**
* @inheritDoc
*/
public function commit(): bool
{
$hasCommitOnce = false;
foreach ($this->clusterPools as $driverPool) {
if ($result = $driverPool->commit()) {
$hasCommitOnce = $result;
}
}
// Return true only if at least one backend confirmed the "commit" operation
return $hasCommitOnce;
}
/**
* @param ExtendedCacheItemPoolInterface[] $poolsToResynchronize
* @param string $key
* @param ?ExtendedCacheItemInterface $item
* @return void
* @throws \Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException
*/
protected function resynchronizePool(array $poolsToResynchronize, string $key, ?ExtendedCacheItemInterface $item): void
{
if ($item && $item->isHit() && \count($poolsToResynchronize) < \count($this->clusterPools)) {
foreach ($poolsToResynchronize as $poolToResynchronize) {
$poolItem = $poolToResynchronize->getItem($key);
$poolItem->setEventManager($this->getEventManager())
->set($item->get())
->setHit($item->isHit())
->setTags($item->getTags())
->expiresAt($item->getExpirationDate())
->setDriver($poolToResynchronize);
$poolToResynchronize->save($poolItem);
}
}
}
}
@@ -0,0 +1,27 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Cluster\Drivers\FullReplication;
use Phpfastcache\Cluster\ItemAbstract;
class Item extends ItemAbstract
{
protected function getDriverClass(): string
{
return Driver::class;
}
}
@@ -0,0 +1,164 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt file.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
declare(strict_types=1);
namespace Phpfastcache\Cluster\Drivers\MasterSlaveReplication;
use Phpfastcache\Cluster\AggregatablePoolInterface;
use Phpfastcache\Cluster\ClusterPoolAbstract;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Event\Event;
use Phpfastcache\Event\EventManagerInterface;
use Phpfastcache\Exceptions\PhpfastcacheCoreException;
use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException;
use Phpfastcache\Exceptions\PhpfastcacheDriverConnectException;
use Phpfastcache\Exceptions\PhpfastcacheDriverException;
use Phpfastcache\Exceptions\PhpfastcacheExceptionInterface;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheIOException;
use Phpfastcache\Exceptions\PhpfastcacheReplicationException;
use Psr\Cache\CacheItemInterface;
class Driver extends ClusterPoolAbstract
{
/**
* MasterSlaveReplicationCluster constructor.
* @param string $clusterName
* @param EventManagerInterface $em
* @param AggregatablePoolInterface ...$driverPools
* @throws PhpfastcacheDriverCheckException
* @throws PhpfastcacheDriverConnectException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheIOException
*/
public function __construct(string $clusterName, EventManagerInterface $em, AggregatablePoolInterface ...$driverPools)
{
if (\count($driverPools) !== 2) {
throw new PhpfastcacheInvalidArgumentException('A "master/slave" cluster requires exactly two pools to be working.');
}
parent::__construct($clusterName, $em, ...$driverPools);
}
/**
* @inheritDoc
*/
public function getItem(string $key): ExtendedCacheItemInterface
{
return $this->getStandardizedItem(
$this->makeOperation(static function (ExtendedCacheItemPoolInterface $pool) use ($key) {
return $pool->getItem($key);
}) ?? (new Item($this, $key, $this->getEventManager()))->expiresAfter((int) abs($this->getConfig()->getDefaultTtl())),
$this
);
}
/**
* @param callable $operation
* @return mixed
* @throws PhpfastcacheReplicationException
*/
protected function makeOperation(callable $operation)
{
try {
return $operation($this->getMasterPool());
} catch (PhpfastcacheExceptionInterface $e) {
try {
$this->eventManager->dispatch(
Event::CACHE_REPLICATION_SLAVE_FALLBACK,
$this,
\debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function']
);
return $operation($this->getSlavePool());
} catch (PhpfastcacheExceptionInterface $e) {
throw new PhpfastcacheReplicationException('Master and Slave thrown an exception !');
}
}
}
/**
* @return AggregatablePoolInterface
*/
protected function getMasterPool(): AggregatablePoolInterface
{
return $this->clusterPools[0];
}
/**
* @return AggregatablePoolInterface
*/
protected function getSlavePool(): AggregatablePoolInterface
{
return $this->clusterPools[1];
}
/**
* @inheritDoc
*/
public function hasItem(string $key): bool
{
return $this->makeOperation(
static fn (ExtendedCacheItemPoolInterface $pool) => $pool->hasItem($key)
);
}
/**
* @inheritDoc
*/
public function clear(): bool
{
return $this->makeOperation(
static fn (ExtendedCacheItemPoolInterface $pool) => $pool->clear()
);
}
/**
* @inheritDoc
*/
public function deleteItem(string $key): bool
{
return $this->makeOperation(
static fn (ExtendedCacheItemPoolInterface $pool) => $pool->deleteItem($key)
);
}
/**
* @inheritDoc
*/
public function save(CacheItemInterface $item): bool
{
return $this->makeOperation(
function (ExtendedCacheItemPoolInterface $pool) use ($item) {
/** @var ExtendedCacheItemInterface $item */
$item->setHit(true);
return $pool->save($this->getStandardizedItem($item, $pool));
}
);
}
/**
* @inheritDoc
*/
public function commit(): bool
{
return $this->makeOperation(
static fn (ExtendedCacheItemPoolInterface $pool) => $pool->commit()
);
}
}
@@ -0,0 +1,27 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Cluster\Drivers\MasterSlaveReplication;
use Phpfastcache\Cluster\ItemAbstract;
class Item extends ItemAbstract
{
protected function getDriverClass(): string
{
return Driver::class;
}
}
@@ -0,0 +1,65 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt file.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
declare(strict_types=1);
namespace Phpfastcache\Cluster\Drivers\RandomReplication;
use Phpfastcache\Cluster\AggregatablePoolInterface;
use Phpfastcache\Cluster\Drivers\MasterSlaveReplication\Driver as MasterSlaveReplicationDriver;
use Phpfastcache\Event\Event;
use Phpfastcache\Event\EventManagerInterface;
use ReflectionException;
use ReflectionMethod;
class Driver extends MasterSlaveReplicationDriver
{
/**
* RandomReplicationCluster constructor.
* @param string $clusterName
* @param EventManagerInterface $em
* @param AggregatablePoolInterface ...$driverPools
* @throws ReflectionException
*/
public function __construct(
string $clusterName,
EventManagerInterface $em,
AggregatablePoolInterface ...$driverPools
) {
/** Straight call to ClusterPoolAbstract constructor */
(new ReflectionMethod(
\get_parent_class(\get_parent_class($this)),
__FUNCTION__
))->invoke($this, $clusterName, $em, ...$driverPools);
$randomPool = $driverPools[\random_int(0, \count($driverPools) - 1)];
$this->eventManager->dispatch(
Event::CACHE_REPLICATION_RANDOM_POOL_CHOSEN,
$this,
$randomPool
);
$this->clusterPools = [$randomPool];
}
/**
* @param callable $operation
* @return mixed
*/
protected function makeOperation(callable $operation)
{
return $operation($this->getMasterPool());
}
}
@@ -0,0 +1,27 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Cluster\Drivers\RandomReplication;
use Phpfastcache\Cluster\ItemAbstract;
class Item extends ItemAbstract
{
protected function getDriverClass(): string
{
return Driver::class;
}
}
@@ -0,0 +1,197 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt file.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
declare(strict_types=1);
namespace Phpfastcache\Cluster\Drivers\SemiReplication;
use Phpfastcache\Cluster\ClusterPoolAbstract;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Exceptions\PhpfastcacheExceptionInterface;
use Phpfastcache\Exceptions\PhpfastcacheReplicationException;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\InvalidArgumentException;
class Driver extends ClusterPoolAbstract
{
/**
* @inheritDoc
* @throws InvalidArgumentException
* @throws PhpfastcacheReplicationException
*/
public function getItem(string $key): ExtendedCacheItemInterface
{
/** @var ?ExtendedCacheItemInterface $item */
$item = null;
$eCount = 0;
foreach ($this->clusterPools as $driverPool) {
try {
$poolItem = $driverPool->getItem($key);
if (!$item && $poolItem->isHit()) {
$item = $poolItem;
break;
}
} catch (PhpfastcacheExceptionInterface) {
$eCount++;
}
}
if (\count($this->clusterPools) <= $eCount) {
throw new PhpfastcacheReplicationException('Every pools thrown an exception');
}
if ($item === null) {
$item = new Item($this, $key, $this->getEventManager());
$item->expiresAfter((int) abs($this->getConfig()->getDefaultTtl()));
}
return $this->getStandardizedItem($item, $this);
}
/**
* @inheritDoc
* @throws PhpfastcacheReplicationException
*/
public function hasItem(string $key): bool
{
$eCount = 0;
foreach ($this->clusterPools as $driverPool) {
try {
$poolItem = $driverPool->getItem($key);
if ($poolItem->isHit()) {
return true;
}
} catch (PhpfastcacheExceptionInterface) {
$eCount++;
}
}
if (\count($this->clusterPools) <= $eCount) {
throw new PhpfastcacheReplicationException('Every pools thrown an exception');
}
return false;
}
/**
* @inheritDoc
* @throws PhpfastcacheReplicationException
*/
public function clear(): bool
{
$hasClearedOnce = false;
$eCount = 0;
foreach ($this->clusterPools as $driverPool) {
try {
if ($result = $driverPool->clear()) {
$hasClearedOnce = $result;
}
} catch (PhpfastcacheExceptionInterface) {
$eCount++;
}
}
if (\count($this->clusterPools) <= $eCount) {
throw new PhpfastcacheReplicationException('Every pools thrown an exception');
}
// Return true only if at least one backend confirmed the "clear" operation
return $hasClearedOnce;
}
/**
* @inheritDoc
* @throws PhpfastcacheReplicationException
* @throws InvalidArgumentException
*/
public function deleteItem(string $key): bool
{
$hasDeletedOnce = false;
$eCount = 0;
foreach ($this->clusterPools as $driverPool) {
try {
if ($result = $driverPool->deleteItem($key)) {
$hasDeletedOnce = $result;
}
} catch (PhpfastcacheExceptionInterface) {
$eCount++;
}
}
if (\count($this->clusterPools) <= $eCount) {
throw new PhpfastcacheReplicationException('Every pools thrown an exception');
}
// Return true only if at least one backend confirmed the "clear" operation
return $hasDeletedOnce;
}
/**
* @param CacheItemInterface $item
* @return bool
* @throws InvalidArgumentException
* @throws PhpfastcacheReplicationException
*/
public function save(CacheItemInterface $item): bool
{
/** @var ExtendedCacheItemInterface $item */
$hasSavedOnce = false;
$eCount = 0;
foreach ($this->clusterPools as $driverPool) {
try {
$poolItem = $this->getStandardizedItem($item, $driverPool);
if ($result = $driverPool->save($poolItem)) {
$hasSavedOnce = $result;
}
} catch (PhpfastcacheExceptionInterface) {
$eCount++;
}
}
if (\count($this->clusterPools) <= $eCount) {
throw new PhpfastcacheReplicationException('Every pools thrown an exception');
}
// Return true only if at least one backend confirmed the "commit" operation
return $hasSavedOnce;
}
/**
* @inheritDoc
* @throws PhpfastcacheReplicationException
*/
public function commit(): bool
{
$hasCommitOnce = false;
$eCount = 0;
foreach ($this->clusterPools as $driverPool) {
try {
if ($result = $driverPool->commit()) {
$hasCommitOnce = $result;
}
} catch (PhpfastcacheExceptionInterface) {
$eCount++;
}
}
if (\count($this->clusterPools) <= $eCount) {
throw new PhpfastcacheReplicationException('Every pools thrown an exception');
}
// Return true only if at least one backend confirmed the "commit" operation
return $hasCommitOnce;
}
}
@@ -0,0 +1,27 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Cluster\Drivers\SemiReplication;
use Phpfastcache\Cluster\ItemAbstract;
class Item extends ItemAbstract
{
protected function getDriverClass(): string
{
return Driver::class;
}
}
@@ -0,0 +1,25 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Cluster;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Item\TaggableCacheItemTrait;
abstract class ItemAbstract implements ExtendedCacheItemInterface
{
use TaggableCacheItemTrait;
}
@@ -0,0 +1,83 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Config;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
abstract class AbstractConfigurationOption implements LockableConfigurationInterface
{
private bool $lockedObject = false;
private ExtendedCacheItemPoolInterface $locker;
protected function getClassName(): string
{
return $this::class;
}
public function lock(ExtendedCacheItemPoolInterface $poolInstance): static
{
$this->lockedObject = true;
$this->locker = $poolInstance;
return $this;
}
public function lockedBy(): ExtendedCacheItemPoolInterface
{
return $this->locker;
}
public function isLocked(): bool
{
return $this->lockedObject;
}
/**
* @throws PhpfastcacheLogicException
* @throws PhpfastcacheInvalidArgumentException
*/
protected function setProperty(string $propertyName, mixed $propertyValue): static
{
$this->enforceLockedProperty($propertyName);
if (property_exists($this, $propertyName)) {
$this->$propertyName = $propertyValue;
return $this;
}
throw new PhpfastcacheInvalidArgumentException("Unknown property $propertyName in {$this->getClassName()} context.");
}
/**
* @throws PhpfastcacheLogicException
*/
protected function enforceLockedProperty(string $propertyName): void
{
if ($this->lockedObject === true) {
$dbt = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 3);
$cause = $dbt[\array_key_last($dbt)] ?? null;
if ($cause) {
$moreInfo = \sprintf('Caused line %d in %s', $cause['line'], $cause['file']);
}
throw new PhpfastcacheLogicException(\sprintf(
'You can no longer change the configuration "%s" as the cache pool instance is now running. %s',
$propertyName,
$moreInfo ?? ''
));
}
}
}
@@ -0,0 +1,36 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Config;
/**
* @deprecated This class is deprecated and will be removed in v10, use ConfigurationOption instead
*/
class Config extends ConfigurationOption
{
public function __construct(array $parameters = [])
{
\trigger_error(
\sprintf(
'%s class is deprecated and will be removed in v10, use %s instead.',
self::class,
ConfigurationOption::class
),
\E_USER_DEPRECATED
);
parent::__construct($parameters);
}
}
@@ -0,0 +1,369 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Config;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidConfigurationException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidTypeException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
class ConfigurationOption extends AbstractConfigurationOption implements ConfigurationOptionInterface
{
protected bool $itemDetailedDate = false;
protected bool $autoTmpFallback = false;
protected int $defaultTtl = 900;
/**
* @var string|callable
*/
protected mixed $defaultKeyHashFunction = 'md5';
/**
* @var string|callable
*/
protected mixed $defaultFileNameHashFunction = 'md5';
protected string $path = '';
protected bool $preventCacheSlams = false;
protected int $cacheSlamsTimeout = 15;
protected bool $useStaticItemCaching = true;
protected ?object $superGlobalAccessor = null;
/**
* @inheritDoc
* @throws PhpfastcacheInvalidConfigurationException
* @throws PhpfastcacheInvalidTypeException
*/
public function __construct(array $parameters = [])
{
foreach ($parameters as $configKey => $configVal) {
try {
if (\property_exists($this, $configKey)) {
$this->{'set' . \ucfirst($configKey)}($configVal);
} else {
throw new PhpfastcacheInvalidConfigurationException(
sprintf(
'Unknown configuration option name "%s" for the config class "%s". Allowed configurations options are "%s"',
$configKey,
$this::class,
\implode('", "', \array_keys($this->toArray())),
)
);
}
} catch (\TypeError $e) {
throw new PhpfastcacheInvalidTypeException(
\sprintf(
'TypeError exception thrown while trying to set your configuration: %s',
$e->getMessage()
)
);
}
}
}
public function toArray(): array
{
return \get_object_vars($this);
}
/**
* @throws \ReflectionException
*/
public function isValueSerializable(mixed $val): bool
{
return !\is_callable($val) && !(is_object($val) && (new \ReflectionClass($val))->isAnonymous());
}
/**
* @param string $optionName
* @return bool
*/
public function isValidOption(string $optionName): bool
{
return \property_exists($this, $optionName);
}
/**
* @return bool
*/
public function isItemDetailedDate(): bool
{
return $this->itemDetailedDate;
}
/**
* @param bool $itemDetailedDate
* @return ConfigurationOption
* @throws PhpfastcacheLogicException
*/
public function setItemDetailedDate(bool $itemDetailedDate): static
{
$this->enforceLockedProperty(__FUNCTION__);
$this->itemDetailedDate = $itemDetailedDate;
return $this;
}
/**
* @return bool
*/
public function isAutoTmpFallback(): bool
{
return $this->autoTmpFallback;
}
/**
* @param bool $autoTmpFallback
* @return ConfigurationOption
* @throws PhpfastcacheLogicException
*/
public function setAutoTmpFallback(bool $autoTmpFallback): static
{
$this->enforceLockedProperty(__FUNCTION__);
$this->autoTmpFallback = $autoTmpFallback;
return $this;
}
/**
* @return int
*/
public function getDefaultTtl(): int
{
return $this->defaultTtl;
}
/**
* @param int $defaultTtl
* @return ConfigurationOption
* @throws PhpfastcacheLogicException
*/
public function setDefaultTtl(int $defaultTtl): static
{
$this->enforceLockedProperty(__FUNCTION__);
$this->defaultTtl = $defaultTtl;
return $this;
}
/**
* @return callable|string
*/
public function getDefaultKeyHashFunction(): callable|string
{
return $this->defaultKeyHashFunction;
}
/**
* @param callable|string $defaultKeyHashFunction
* @return ConfigurationOption
* @throws PhpfastcacheInvalidConfigurationException
* @throws PhpfastcacheLogicException
*/
public function setDefaultKeyHashFunction(callable|string $defaultKeyHashFunction): static
{
$this->enforceLockedProperty(__FUNCTION__);
if ($defaultKeyHashFunction && !\is_callable($defaultKeyHashFunction) && (\is_string($defaultKeyHashFunction) && !\function_exists($defaultKeyHashFunction))) {
throw new PhpfastcacheInvalidConfigurationException('defaultKeyHashFunction must be a valid function name string');
}
$this->defaultKeyHashFunction = $defaultKeyHashFunction;
return $this;
}
/**
* @return callable|string
*/
public function getDefaultFileNameHashFunction(): callable|string
{
return $this->defaultFileNameHashFunction;
}
/**
* @param callable|string $defaultFileNameHashFunction
* @return ConfigurationOption
* @throws PhpfastcacheInvalidConfigurationException
* @throws PhpfastcacheLogicException
*/
public function setDefaultFileNameHashFunction(callable|string $defaultFileNameHashFunction): static
{
$this->enforceLockedProperty(__FUNCTION__);
if (!\is_callable($defaultFileNameHashFunction) && (\is_string($defaultFileNameHashFunction) && !\function_exists($defaultFileNameHashFunction))) {
throw new PhpfastcacheInvalidConfigurationException('defaultFileNameHashFunction must be a valid function name string');
}
$this->defaultFileNameHashFunction = $defaultFileNameHashFunction;
return $this;
}
/**
* @return string
*/
public function getPath(): string
{
return $this->path;
}
/**
* @param string $path
* @return ConfigurationOption
* @throws PhpfastcacheLogicException
*/
public function setPath(string $path): static
{
$this->enforceLockedProperty(__FUNCTION__);
$this->path = $path;
return $this;
}
/**
* @deprecated This method is deprecated and will be soon moved to IOConfigurationOption class, which means they will only be available for `IO` drivers.
* @return bool
*/
public function isPreventCacheSlams(): bool
{
return $this->preventCacheSlams;
}
/**
* @deprecated This method is deprecated and will be soon moved to IOConfigurationOption class, which means they will only be available for `IO` drivers.
* @param bool $preventCacheSlams
* @return ConfigurationOption
* @throws PhpfastcacheLogicException
*/
public function setPreventCacheSlams(bool $preventCacheSlams): static
{
if ($preventCacheSlams !== $this->preventCacheSlams) {
trigger_error(
'This method is deprecated and will be soon moved to IOConfigurationOption class, which means they will only be available for `IO` drivers.',
E_USER_DEPRECATED
);
}
$this->enforceLockedProperty(__FUNCTION__);
$this->preventCacheSlams = $preventCacheSlams;
return $this;
}
/**
* @deprecated This method is deprecated and will be soon moved to IOConfigurationOption class, which means they will only be available for `IO` drivers.
* @return int
*/
public function getCacheSlamsTimeout(): int
{
return $this->cacheSlamsTimeout;
}
/**
* @deprecated This method is deprecated and will be soon moved to IOConfigurationOption class, which means they will only be available for `IO` drivers.
* @param int $cacheSlamsTimeout
* @return ConfigurationOption
* @throws PhpfastcacheLogicException
*/
public function setCacheSlamsTimeout(int $cacheSlamsTimeout): static
{
if ($cacheSlamsTimeout !== $this->cacheSlamsTimeout) {
trigger_error(
'This method is deprecated and will be soon moved to IOConfigurationOption class, which means they will only be available for `IO` drivers.',
E_USER_DEPRECATED
);
}
$this->enforceLockedProperty(__FUNCTION__);
$this->cacheSlamsTimeout = $cacheSlamsTimeout;
return $this;
}
/**
* @return bool
*/
public function isUseStaticItemCaching(): bool
{
return $this->useStaticItemCaching;
}
/**
* @param bool $useStaticItemCaching
* @return ConfigurationOption
* @throws PhpfastcacheLogicException
*/
public function setUseStaticItemCaching(bool $useStaticItemCaching): static
{
$this->enforceLockedProperty(__FUNCTION__);
$this->useStaticItemCaching = $useStaticItemCaching;
return $this;
}
/**
* @return object
*/
public function getSuperGlobalAccessor(): object
{
if (!isset($this->superGlobalAccessor)) {
$this->superGlobalAccessor = $this->getDefaultSuperGlobalAccessor();
}
return $this->superGlobalAccessor;
}
/**
* @param ?object $superGlobalAccessor
* @return static
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
public function setSuperGlobalAccessor(?object $superGlobalAccessor): static
{
$this->enforceLockedProperty(__FUNCTION__);
/**
* Symfony's implementation for users that want a good control of their code:
*
* $config['superGlobalAccessor'] = \Closure::fromCallable(static function(string $superGlobalName, string $keyName) use ($request) {
* return match ($superGlobalName) {
* 'SERVER' => $request->server->get($keyName),
* 'REQUEST' => $request->request->get($keyName),
* };
* });
*/
if ($superGlobalAccessor === null) {
$this->superGlobalAccessor = $this->getDefaultSuperGlobalAccessor();
} elseif (!\is_callable($superGlobalAccessor)) {
throw new PhpfastcacheInvalidArgumentException('The "superGlobalAccessor" callback must be callable using "__invoke" or \Closure implementation');
} else {
$this->superGlobalAccessor = $superGlobalAccessor;
}
return $this;
}
/**
* @return \Closure
* @SuppressWarnings(PHPMD.Superglobals)
*/
protected function getDefaultSuperGlobalAccessor(): \Closure
{
return \Closure::fromCallable(static function (string $superGlobalName, ?string $keyName = null): string|int|float|array|bool|null {
return match ($superGlobalName) {
'SERVER' => $keyName !== null ? $_SERVER[$keyName] ?? null : $_SERVER,
'REQUEST' => $keyName !== null ? $_REQUEST[$keyName] ?? null : $_REQUEST,
'COOKIE' => $keyName !== null ? $_COOKIE[$keyName] ?? null : $_COOKIE,
default => null,
};
});
}
}
@@ -0,0 +1,134 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Config;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidConfigurationException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
interface ConfigurationOptionInterface extends LockableConfigurationInterface
{
/**
* @param array<string, mixed> $parameters
* ConfigurationOptionInterface constructor.
*/
public function __construct(array $parameters = []);
/**
* @return array<string, mixed>
*/
public function toArray(): array;
/**
* @param mixed $val
* @return bool
*/
public function isValueSerializable(mixed $val): bool;
/**
* @param string $optionName
* @return bool
*/
public function isValidOption(string $optionName): bool;
/**
* @return bool
*/
public function isItemDetailedDate(): bool;
/**
* @param bool $itemDetailedDate
* @return ConfigurationOption
*/
public function setItemDetailedDate(bool $itemDetailedDate): static;
/**
* @return bool
*/
public function isAutoTmpFallback(): bool;
/**
* @param bool $autoTmpFallback
* @return ConfigurationOption
*/
public function setAutoTmpFallback(bool $autoTmpFallback): static;
/**
* @return int
*/
public function getDefaultTtl(): int;
/**
* @param int $defaultTtl
* @return ConfigurationOption
*/
public function setDefaultTtl(int $defaultTtl): static;
/**
* @return callable|string
*/
public function getDefaultKeyHashFunction(): callable|string;
/**
* @param callable|string $defaultKeyHashFunction
* @return ConfigurationOption
* @throws PhpfastcacheInvalidConfigurationException
*/
public function setDefaultKeyHashFunction(callable|string $defaultKeyHashFunction): static;
/**
* @return callable|string
*/
public function getDefaultFileNameHashFunction(): callable|string;
/**
* @param callable|string $defaultFileNameHashFunction
* @return ConfigurationOption
* @throws PhpfastcacheInvalidConfigurationException
*/
public function setDefaultFileNameHashFunction(callable|string $defaultFileNameHashFunction): static;
/**
* @return string
*/
public function getPath(): string;
/**
* @param string $path
* @return ConfigurationOption
*/
public function setPath(string $path): static;
/**
* @return bool
*/
public function isUseStaticItemCaching(): bool;
/**
* @param bool $useStaticItemCaching
* @return ConfigurationOption
*/
public function setUseStaticItemCaching(bool $useStaticItemCaching): static;
/**
* @return object
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
public function getSuperGlobalAccessor(): object;
/**
* @param ?object $superGlobalAccessor
* @return static
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
public function setSuperGlobalAccessor(?object $superGlobalAccessor): static;
}
@@ -0,0 +1,156 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Config;
use Phpfastcache\Exceptions\PhpfastcacheInvalidConfigurationException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
/**
* @todo: As of V10, imports cache slams properties.
*/
class IOConfigurationOption extends ConfigurationOption
{
protected bool $secureFileManipulation = false;
protected string $securityKey = '';
protected string $cacheFileExtension = 'txt';
protected int $defaultChmod = 0777;
/**
* @return string
*/
public function getSecurityKey(): string
{
return $this->securityKey;
}
/**
* @param string $securityKey
* @return static
* @throws PhpfastcacheLogicException
*/
public function setSecurityKey(string $securityKey): static
{
return $this->setProperty('securityKey', $securityKey);
}
/**
* @return bool
*/
public function isSecureFileManipulation(): bool
{
return $this->secureFileManipulation;
}
/**
* @param bool $secureFileManipulation
* @return static
* @throws PhpfastcacheLogicException
*/
public function setSecureFileManipulation(bool $secureFileManipulation): static
{
return $this->setProperty('secureFileManipulation', $secureFileManipulation);
}
/**
* @return string
*/
public function getCacheFileExtension(): string
{
return $this->cacheFileExtension;
}
/**
* @param string $cacheFileExtension
* @return static
* @throws PhpfastcacheInvalidConfigurationException
* @throws PhpfastcacheLogicException
*/
public function setCacheFileExtension(string $cacheFileExtension): static
{
$safeFileExtensions = \explode('|', IOConfigurationOptionInterface::SAFE_FILE_EXTENSIONS);
if (\str_contains($cacheFileExtension, '.')) {
throw new PhpfastcacheInvalidConfigurationException('cacheFileExtension cannot contain a dot "."');
}
if (!\in_array($cacheFileExtension, $safeFileExtensions, true)) {
throw new PhpfastcacheInvalidConfigurationException(
"Extension \"$cacheFileExtension\" is unsafe, currently allowed extension names: " . \implode(', ', $safeFileExtensions)
);
}
return $this->setProperty('cacheFileExtension', $cacheFileExtension);
}
/**
* @return int
*/
public function getDefaultChmod(): int
{
return $this->defaultChmod;
}
/**
* @param int $defaultChmod
* @return static
* @throws PhpfastcacheLogicException
*/
public function setDefaultChmod(int $defaultChmod): static
{
return $this->setProperty('defaultChmod', $defaultChmod);
}
/**
* @return bool
*/
public function isPreventCacheSlams(): bool
{
return $this->preventCacheSlams;
}
/**
* @param bool $preventCacheSlams
* @return static
* @throws PhpfastcacheLogicException
*/
public function setPreventCacheSlams(bool $preventCacheSlams): static
{
return $this->setProperty('preventCacheSlams', $preventCacheSlams);
}
/**
* @return int
*/
public function getCacheSlamsTimeout(): int
{
return $this->cacheSlamsTimeout;
}
/**
* @param int $cacheSlamsTimeout
* @return static
* @throws PhpfastcacheLogicException
*/
public function setCacheSlamsTimeout(int $cacheSlamsTimeout): static
{
return $this->setProperty('cacheSlamsTimeout', $cacheSlamsTimeout);
}
}
@@ -0,0 +1,50 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Config;
interface IOConfigurationOptionInterface extends ConfigurationOptionInterface
{
/**
* Feel free to propose your own one
* by opening a pull request :)
*/
public const SAFE_FILE_EXTENSIONS = 'txt|cache|db|pfc';
public function getSecurityKey(): string;
public function setSecurityKey(string $securityKey): static;
public function isSecureFileManipulation(): bool;
public function setSecureFileManipulation(bool $secureFileManipulation): static;
public function getCacheFileExtension(): string;
public function setCacheFileExtension(string $cacheFileExtension): static;
public function getDefaultChmod(): int;
public function setDefaultChmod(int $defaultChmod): static;
public function isPreventCacheSlams(): bool;
public function setPreventCacheSlams(bool $preventCacheSlams): static;
public function getCacheSlamsTimeout(): int;
public function setCacheSlamsTimeout(int $cacheSlamsTimeout): static;
}
@@ -0,0 +1,31 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Config;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
interface LockableConfigurationInterface
{
/**
* @internal
*/
public function lock(ExtendedCacheItemPoolInterface $poolInstance): static;
public function lockedBy(): ExtendedCacheItemPoolInterface;
public function isLocked(): bool;
}
@@ -0,0 +1,149 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Core\Item;
use DateInterval;
use DateTime;
use DateTimeInterface;
use Phpfastcache\Event\Event;
use Phpfastcache\Event\EventManagerDispatcherTrait;
use Phpfastcache\Event\EventReferenceParameter;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Util\ClassNamespaceResolverTrait;
trait CacheItemTrait
{
use EventManagerDispatcherTrait;
use ClassNamespaceResolverTrait;
protected string $key;
protected mixed $data;
protected DateTimeInterface $expirationDate;
protected DateTimeInterface $creationDate;
protected DateTimeInterface $modificationDate;
protected bool $isHit = false;
public function getKey(): string
{
return $this->key;
}
public function get(): mixed
{
if (!$this->isHit()) {
return null;
}
return $this->data;
}
/**
* @throws PhpfastcacheInvalidArgumentException
*/
public function set(mixed $value): static
{
if ($value instanceof \Closure) {
throw new PhpfastcacheInvalidArgumentException('The value set cannot be an instance of \\Closure.');
}
if (\is_resource($value)) {
throw new PhpfastcacheInvalidArgumentException('The value set cannot be a resource');
}
$this->eventManager->dispatch(Event::CACHE_ITEM_SET, $this, new EventReferenceParameter($value, true));
$this->data = $value;
return $this;
}
/**
* @return bool
*/
public function isHit(): bool
{
return $this->isHit;
}
/**
* @param bool $isHit
* @return ExtendedCacheItemInterface
*/
public function setHit(bool $isHit): ExtendedCacheItemInterface
{
$this->isHit = $isHit;
return $this;
}
/**
* @throws PhpfastcacheInvalidArgumentException
*/
public function expiresAt(?\DateTimeInterface $expiration): static
{
if ($expiration instanceof DateTimeInterface) {
$this->eventManager->dispatch(Event::CACHE_ITEM_EXPIRE_AT, $this, $expiration);
$this->expirationDate = $this->demutateDatetime($expiration);
} else {
throw new PhpfastcacheInvalidArgumentException('$expiration must be an object implementing the DateTimeInterface got: ' . \gettype($expiration));
}
return $this;
}
/**
* @return $this
* @throws PhpfastcacheInvalidArgumentException
* @throws \Exception
*/
public function expiresAfter(int|\DateInterval|null $time): static
{
if (\is_numeric($time)) {
if ($time <= 0) {
/**
* 5 months, however memcached or memory cached will be gone when u restart it
* just recommended for sqlite. files
*/
$time = 30 * 24 * 3600 * 5;
}
$this->eventManager->dispatch(Event::CACHE_ITEM_EXPIRE_AFTER, $this, $time);
$this->expirationDate = (new DateTime())->add(new DateInterval(\sprintf('PT%dS', $time)));
} elseif ($time instanceof DateInterval) {
$this->eventManager->dispatch(Event::CACHE_ITEM_EXPIRE_AFTER, $this, $time);
$this->expirationDate = (new DateTime())->add($time);
} else {
throw new PhpfastcacheInvalidArgumentException(\sprintf('Invalid date format, got "%s"', \gettype($time)));
}
return $this;
}
protected function demutateDatetime(\DateTimeInterface $dateTime): \DateTimeInterface
{
return $dateTime instanceof \DateTimeImmutable
? \DateTime::createFromImmutable($dateTime)
: $dateTime;
}
}
@@ -0,0 +1,207 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Core\Item;
use DateTimeInterface;
use JsonSerializable;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Event\EventManagerDispatcherInterface;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidTypeException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Phpfastcache\Util\ClassNamespaceResolverInterface;
use Psr\Cache\CacheItemInterface;
interface ExtendedCacheItemInterface extends
CacheItemInterface,
EventManagerDispatcherInterface,
ClassNamespaceResolverInterface,
JsonSerializable,
TaggableCacheItemInterface
{
/**
* Returns the encoded key for the current cache item.
* Is a MD5 (default),SHA1,SHA256 hash if "defaultKeyHashFunction" config option is configured
* Else return the plain cache item key "defaultKeyHashFunction" config option is emptied
*
* @return string
* The encoded key string for this cache item.
*/
public function getEncodedKey(): string;
/**
* Returns the cache item value, regardless of hit status.
* This method can be called if the cache item is NOT YET
* persisted, and you need to access to its set value.
*
* Although not part of the CacheItemInterface, this method is used by
* the pool for extracting information for saving.
*
* @return mixed
*
* @internal This method is used internally by phpfastcache, so you should not use it in your application.
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
*/
public function _getData(): mixed; // @phpcs:ignore
/**
* @return DateTimeInterface
*/
public function getExpirationDate(): DateTimeInterface;
/**
* Alias of expireAt() with forced $expiration param
*
* @param DateTimeInterface $expiration
* The point in time after which the item MUST be considered expired.
* If null is passed explicitly, a default value MAY be used. If none is set,
* the value should be stored permanently or for as long as the
* implementation allows.
*
* @return ExtendedCacheItemInterface
* The called object.
*/
public function setExpirationDate(DateTimeInterface $expiration): ExtendedCacheItemInterface;
/**
* @return DateTimeInterface
* @throws PhpfastcacheLogicException
*/
public function getCreationDate(): DateTimeInterface;
/**
* @return DateTimeInterface
* @throws PhpfastcacheLogicException
*/
public function getModificationDate(): DateTimeInterface;
/**
* @param $date DateTimeInterface
*
* @return ExtendedCacheItemInterface
* @throws PhpfastcacheLogicException
*/
public function setCreationDate(DateTimeInterface $date): ExtendedCacheItemInterface;
/**
* @param $date DateTimeInterface
*
* @return ExtendedCacheItemInterface
* @throws PhpfastcacheLogicException
*/
public function setModificationDate(DateTimeInterface $date): ExtendedCacheItemInterface;
/**
* @return int
*/
public function getTtl(): int;
/**
* @return bool
*/
public function isExpired(): bool;
/**
* @return bool
*/
public function isNull(): bool;
/**
* @return bool
*/
public function isEmpty(): bool;
/**
* Return the data length:
* - Either the number of char if it's a string (binary mode)
* - or the number of element if it's an array
* - or the number returned by count() if it's an object implementing \Countable interface
* - or -1 for anything else
*
* @return int
*/
public function getLength(): int;
/**
* @param ExtendedCacheItemPoolInterface $driver
*
* @return ExtendedCacheItemInterface
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver): ExtendedCacheItemInterface;
/**
* @param bool $isHit
*
* @return ExtendedCacheItemInterface
*/
public function setHit(bool $isHit): ExtendedCacheItemInterface;
/**
* @param int $step
*
* @return ExtendedCacheItemInterface
* @throws PhpfastcacheInvalidTypeException
*/
public function increment(int $step = 1): ExtendedCacheItemInterface;
/**
* @param int $step
*
* @return ExtendedCacheItemInterface
* @throws PhpfastcacheInvalidTypeException
*/
public function decrement(int $step = 1): ExtendedCacheItemInterface;
/**
* @param mixed[]|string $data
*
* @return ExtendedCacheItemInterface
* @throws PhpfastcacheInvalidTypeException
*/
public function append(array|string $data): ExtendedCacheItemInterface;
/**
* @param mixed[]|string $data
*
* @return ExtendedCacheItemInterface
* @throws PhpfastcacheInvalidTypeException
*/
public function prepend(array|string $data): ExtendedCacheItemInterface;
/**
* Return the data as a well-formatted string.
* Any scalar value will be casted to an array
*
* @param int $options \json_encode() options
* @param int $depth \json_encode() depth
*
* @return string
*/
public function getDataAsJsonString(int $options = JSON_THROW_ON_ERROR, int $depth = 512): string;
/**
* @param ExtendedCacheItemPoolInterface $driverPool
* @return bool
*/
public function doesItemBelongToThatDriverBackend(ExtendedCacheItemPoolInterface $driverPool): bool;
/**
* @param ExtendedCacheItemInterface $itemTarget
* @param ExtendedCacheItemPoolInterface|null $itemPoolTarget
*/
public function cloneInto(ExtendedCacheItemInterface $itemTarget, ?ExtendedCacheItemPoolInterface $itemPoolTarget = null): void;
}
@@ -0,0 +1,307 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Core\Item;
use DateTime;
use DateTimeInterface;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Event\EventManagerInterface;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidTypeException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
trait ExtendedCacheItemTrait
{
use CacheItemTrait;
protected ExtendedCacheItemPoolInterface $driver;
protected string $encodedKey;
/**
* Item constructor.
* @param ExtendedCacheItemPoolInterface $driver
* @param string $key
* @param EventManagerInterface $em
* @throws PhpfastcacheInvalidArgumentException
*/
public function __construct(ExtendedCacheItemPoolInterface $driver, string $key, EventManagerInterface $em)
{
$this->data = null;
$this->key = $key;
$this->setEventManager($em);
$this->setDriver($driver);
if ($driver->getConfig()->isUseStaticItemCaching()) {
$this->driver->setItem($this);
}
$this->expirationDate = new DateTime();
if ($this->driver->getConfig()->isItemDetailedDate()) {
$this->creationDate = new DateTime();
$this->modificationDate = new DateTime();
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @return ExtendedCacheItemInterface
* @throws PhpfastcacheInvalidArgumentException
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver): ExtendedCacheItemInterface
{
$driverClass = $this->getDriverClass();
if ($driver instanceof $driverClass) {
$this->driver = $driver;
return $this;
}
throw new PhpfastcacheInvalidArgumentException(\sprintf('Invalid driver instance "%s" for cache item "%s"', $driver::class, static::class));
}
/**
* @inheritDoc
*/
public function getEncodedKey(): string
{
if (!isset($this->encodedKey)) {
$this->encodedKey = $this->driver->getEncodedKey($this->getKey());
}
return $this->encodedKey;
}
/**
* @inheritDoc
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
*/
public function _getData(): mixed // @phpcs:ignore
{
return $this->data;
}
/**
* @inheritDoc
*/
public function getExpirationDate(): DateTimeInterface
{
return $this->expirationDate;
}
/**
* @inheritDoc
* @throws PhpfastcacheInvalidArgumentException
*/
public function setExpirationDate(DateTimeInterface $expiration): ExtendedCacheItemInterface
{
return $this->expiresAt($expiration);
}
/**
* @inheritDoc
* @throws PhpfastcacheLogicException
*/
public function getCreationDate(): DateTimeInterface
{
if ($this->driver->getConfig()->isItemDetailedDate()) {
return $this->creationDate;
}
throw new PhpfastcacheLogicException('Cannot access to the creation date when the "itemDetailedDate" configuration is disabled.');
}
/**
* @inheritDoc
* @throws PhpfastcacheLogicException
*/
public function setCreationDate(DateTimeInterface $date): ExtendedCacheItemInterface
{
if ($this->driver->getConfig()->isItemDetailedDate()) {
$this->creationDate = $this->demutateDatetime($date);
return $this;
}
throw new PhpfastcacheLogicException('Cannot access to the creation date when the "itemDetailedDate" configuration is disabled.');
}
/**
* @inheritDoc
* @throws PhpfastcacheLogicException
*/
public function getModificationDate(): DateTimeInterface
{
if ($this->driver->getConfig()->isItemDetailedDate()) {
return $this->modificationDate;
}
throw new PhpfastcacheLogicException('Cannot access to the modification date when the "itemDetailedDate" configuration is disabled.');
}
/**
* @inheritDoc
* @throws PhpfastcacheLogicException
*/
public function setModificationDate(DateTimeInterface $date): ExtendedCacheItemInterface
{
if ($this->driver->getConfig()->isItemDetailedDate()) {
$this->modificationDate = $this->demutateDatetime($date);
return $this;
}
throw new PhpfastcacheLogicException('Cannot access to the modification date when the "itemDetailedDate" configuration is disabled.');
}
public function getTtl(): int
{
return \max(0, $this->expirationDate->getTimestamp() - \time());
}
public function isExpired(): bool
{
return $this->getTtl() <= 0;
}
public function isNull(): bool
{
return $this->get() === null;
}
public function isEmpty(): bool
{
return empty($this->get());
}
/**
* Return the data length:
* Either the string length if it's a string (binary mode)
* # or the number of element (count) if it's an array
* # or the number returned by count() if it's an object implementing \Countable interface
* # -1 for anything else
* @return int
*/
public function getLength(): int
{
switch (\gettype($this->data)) {
case 'array':
case 'object':
if (\is_countable($this->data)) {
return \count($this->data);
}
break;
case 'string':
return \strlen($this->data);
}
return -1;
}
/**
* @throws PhpfastcacheInvalidTypeException
*/
public function increment(int $step = 1): ExtendedCacheItemInterface
{
if ($this->data !== null && !\is_numeric($this->data)) {
throw new PhpfastcacheInvalidTypeException(\sprintf('Cannot increment on a "%s" type.', \gettype($this->data)));
}
$this->data += $step;
return $this;
}
/**
* @throws PhpfastcacheInvalidTypeException
*/
public function decrement(int $step = 1): ExtendedCacheItemInterface
{
if ($this->data !== null && !\is_numeric($this->data)) {
throw new PhpfastcacheInvalidTypeException(\sprintf('Cannot decrement on a "%s" type.', \gettype($this->data)));
}
$this->data -= $step;
return $this;
}
/**
* @throws PhpfastcacheInvalidTypeException
*/
public function append(array|string $data): ExtendedCacheItemInterface
{
if ($this->data !== null && !\is_string($this->data) && !\is_array($this->data)) {
throw new PhpfastcacheInvalidTypeException(\sprintf('Cannot append on a "%s" type.', \gettype($this->data)));
}
if (\is_array($this->data)) {
$this->data[] = $data;
} else {
$this->data .= $data;
}
return $this;
}
/**
* @throws PhpfastcacheInvalidTypeException
*/
public function prepend(array|string $data): ExtendedCacheItemInterface
{
if ($this->data !== null && !\is_string($this->data) && !\is_array($this->data)) {
throw new PhpfastcacheInvalidTypeException(\sprintf('Cannot prepend on a "%s" type.', \gettype($this->data)));
}
if (\is_array($this->data)) {
\array_unshift($this->data, $data);
} else {
$this->data = $data . $this->data;
}
return $this;
}
/**
* Return the data as a well-formatted string.
* Any scalar value will be cast to an array
* @param int $options \json_encode() options
* @param int $depth \json_encode() depth
* @return string
*/
public function getDataAsJsonString(int $options = JSON_THROW_ON_ERROR, int $depth = 512): string
{
$data = $this->get();
if (\is_object($data) || \is_array($data)) {
$data = \json_encode($data, $options, $depth);
} else {
$data = \json_encode([$data], $options, $depth);
}
return \json_encode($data, $options, $depth);
}
public function jsonSerialize(): mixed
{
return $this->get();
}
public function doesItemBelongToThatDriverBackend(ExtendedCacheItemPoolInterface $driverPool): bool
{
return $driverPool::getClassNamespace() === self::getClassNamespace();
}
abstract protected function getDriverClass(): string;
}
@@ -0,0 +1,122 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Core\Item;
use Phpfastcache\Core\Pool\TaggableCacheItemPoolInterface;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
interface TaggableCacheItemInterface
{
/**
* Allows you to get cache item(s) by at least **ONE** of the specified matching tag(s).
* Default behavior
*/
public const TAG_STRATEGY_ONE = TaggableCacheItemPoolInterface::TAG_STRATEGY_ONE;
/**
* Allows you to get cache item(s) by **ALL** of the specified matching tag(s)
* The cache item *CAN* have additional tag(s)
*/
public const TAG_STRATEGY_ALL = TaggableCacheItemPoolInterface::TAG_STRATEGY_ALL;
/**
* Allows you to get cache item(s) by **ONLY** the specified matching tag(s)
* The cache item *CANNOT* have additional tag(s)
*/
public const TAG_STRATEGY_ONLY = TaggableCacheItemPoolInterface::TAG_STRATEGY_ONLY;
/**
* @param string $tagName
*
* @return ExtendedCacheItemInterface
* @throws PhpfastcacheInvalidArgumentException
*/
public function addTag(string $tagName): ExtendedCacheItemInterface;
/**
* @param string[] $tagNames
*
* @return ExtendedCacheItemInterface
* @throws PhpfastcacheInvalidArgumentException
*/
public function addTags(array $tagNames): ExtendedCacheItemInterface;
/**
* @param string $tagName
*
* @return bool
*/
public function hasTag(string $tagName): bool;
/**
* @return bool
*/
public function isTagged(): bool;
/**
* @param string[] $tagNames
* @param int $strategy
* @return bool
* @throws PhpfastcacheInvalidArgumentException
*/
public function hasTags(array $tagNames, int $strategy = self::TAG_STRATEGY_ONE): bool;
/**
* @param string[] $tags
*
* @return ExtendedCacheItemInterface
* @throws PhpfastcacheInvalidArgumentException
*/
public function setTags(array $tags): ExtendedCacheItemInterface;
/**
* @return string[]
*/
public function getTags(): array;
/**
* @param string $separator
*
* @return string
*/
public function getTagsAsString(string $separator = ', '): string;
/**
* @param string $tagName
*
* @return ExtendedCacheItemInterface
* @throws PhpfastcacheInvalidArgumentException
*/
public function removeTag(string $tagName): ExtendedCacheItemInterface;
/**
* @param string[] $tagNames
*
* @return ExtendedCacheItemInterface
*/
public function removeTags(array $tagNames): ExtendedCacheItemInterface;
/**
* @return string[]
*/
public function getRemovedTags(): array;
/**
* @return ExtendedCacheItemInterface
*/
public function clearRemovedTags(): ExtendedCacheItemInterface;
}
@@ -0,0 +1,192 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Core\Item;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
trait TaggableCacheItemTrait
{
use ExtendedCacheItemTrait;
/**
* @var string[]
*/
protected array $tags = [];
/**
* @var string[]
*/
protected array $removedTags = [];
/**
* @param string[] $tagNames
* @return ExtendedCacheItemInterface
*/
public function addTags(array $tagNames): ExtendedCacheItemInterface
{
foreach ($tagNames as $tagName) {
$this->addTag($tagName);
}
return $this;
}
/**
* @param string $tagName
* @return ExtendedCacheItemInterface
*/
public function addTag(string $tagName): ExtendedCacheItemInterface
{
$this->tags = \array_unique(\array_merge($this->tags, [$tagName]));
return $this;
}
/**
* @param string $tagName
*
* @return bool
*/
public function hasTag(string $tagName): bool
{
return \in_array($tagName, $this->tags, true);
}
/**
* @return bool
*/
public function isTagged(): bool
{
return !empty($this->tags);
}
/**
* @param string[] $tagNames
* @param int $strategy
* @return bool
* @throws PhpfastcacheInvalidArgumentException
*/
public function hasTags(array $tagNames, int $strategy = TaggableCacheItemInterface::TAG_STRATEGY_ONE): bool
{
return match ($strategy) {
TaggableCacheItemInterface::TAG_STRATEGY_ONE => !empty(array_intersect($tagNames, $this->tags)),
TaggableCacheItemInterface::TAG_STRATEGY_ALL => empty(\array_diff($tagNames, $this->tags)),
TaggableCacheItemInterface::TAG_STRATEGY_ONLY => empty(\array_diff($tagNames, $this->tags)) && empty(\array_diff($this->tags, $tagNames)),
default => throw new PhpfastcacheInvalidArgumentException('Invalid strategy constant provided.'),
};
}
/**
* @param string[] $tags
* @return ExtendedCacheItemInterface
* @throws PhpfastcacheInvalidArgumentException
*/
public function setTags(array $tags): ExtendedCacheItemInterface
{
if ($tags === [] || \array_filter($tags, 'is_string')) {
$this->tags = $tags;
} else {
throw new PhpfastcacheInvalidArgumentException('$tagName must be an array of string');
}
return $this;
}
/**
* @return string[]
*/
public function getTags(): array
{
return $this->tags;
}
/**
* @param string $separator
* @return string
*/
public function getTagsAsString(string $separator = ', '): string
{
return \implode($separator, $this->tags);
}
/**
* @param string[] $tagNames
* @return ExtendedCacheItemInterface
*/
public function removeTags(array $tagNames): ExtendedCacheItemInterface
{
foreach ($tagNames as $tagName) {
$this->removeTag($tagName);
}
return $this;
}
/**
* @param string $tagName
* @return ExtendedCacheItemInterface
*/
public function removeTag(string $tagName): ExtendedCacheItemInterface
{
if (($key = \array_search($tagName, $this->tags, true)) !== false) {
unset($this->tags[$key]);
$this->removedTags[] = $tagName;
}
return $this;
}
/**
* @return string[]
*/
public function getRemovedTags(): array
{
return \array_diff($this->removedTags, $this->tags);
}
/**
* @return ExtendedCacheItemInterface
*/
public function clearRemovedTags(): ExtendedCacheItemInterface
{
$this->removedTags = [];
return $this;
}
/**
* @throws PhpfastcacheLogicException
* @throws PhpfastcacheInvalidArgumentException
*/
public function cloneInto(ExtendedCacheItemInterface $itemTarget, ?ExtendedCacheItemPoolInterface $itemPoolTarget = null): void
{
$itemTarget->setEventManager($this->getEventManager())
->set($this->_getData())
->setHit($this->isHit())
->setTags($this->getTags())
->expiresAt(clone $this->getExpirationDate())
->setDriver($itemPoolTarget ?? $this->driver);
if ($this->driver->getConfig()->isItemDetailedDate()) {
$itemTarget->setCreationDate(clone $this->getCreationDate())
->setModificationDate(clone $this->getModificationDate());
}
}
}
@@ -0,0 +1,34 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
namespace Phpfastcache\Core\Pool;
use Phpfastcache\Cluster\ClusterPoolInterface;
trait AggregatablePoolTrait
{
protected ?ClusterPoolInterface $clusterPool = null;
public function isAggregatedBy(): ?ClusterPoolInterface
{
return $this->clusterPool;
}
public function setAggregatedBy(ClusterPoolInterface $clusterPool): static
{
$this->clusterPool = $clusterPool;
return $this;
}
}
@@ -0,0 +1,630 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Core\Pool;
use DateTime;
use Phpfastcache\Config\ConfigurationOptionInterface;
use Phpfastcache\Config\IOConfigurationOptionInterface;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Entities\DriverIO;
use Phpfastcache\Entities\ItemBatch;
use Phpfastcache\Event\Event;
use Phpfastcache\Event\EventManagerInterface;
use Phpfastcache\Event\EventReferenceParameter;
use Phpfastcache\Exceptions\PhpfastcacheCoreException;
use Phpfastcache\Exceptions\PhpfastcacheDriverException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidTypeException;
use Phpfastcache\Exceptions\PhpfastcacheIOException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Phpfastcache\Exceptions\PhpfastcacheUnsupportedMethodException;
use Psr\Cache\CacheItemInterface;
use RuntimeException;
/**
* @method string[] driverUnwrapTags(array $wrapper)
* @method void cleanItemTags(ExtendedCacheItemInterface $item)
*/
trait CacheItemPoolTrait
{
use DriverBaseTrait {
DriverBaseTrait::__construct as __driverBaseConstruct;
}
/**
* @var string
*/
protected static string $unsupportedKeyChars = '{}()/\@:';
/**
* @var ExtendedCacheItemInterface[]|CacheItemInterface[]
*/
protected array $deferredList = [];
/**
* @var ExtendedCacheItemInterface[]|CacheItemInterface[]
*/
protected array $itemInstances = [];
protected DriverIO $IO;
public function __construct(#[\SensitiveParameter] ConfigurationOptionInterface $config, string $instanceId, EventManagerInterface $em)
{
$this->IO = new DriverIO();
$this->__driverBaseConstruct($config, $instanceId, $em);
}
/**
* @throws PhpfastcacheLogicException
* @throws PhpfastcacheInvalidArgumentException
*/
public function setItem(CacheItemInterface $item): static
{
if (self::getItemClass() === $item::class) {
if (!$this->getConfig()->isUseStaticItemCaching()) {
throw new PhpfastcacheLogicException(
'The static item caching option (useStaticItemCaching) is disabled so you cannot attach an item.'
);
}
$this->itemInstances[$item->getKey()] = $item;
return $this;
}
throw new PhpfastcacheInvalidArgumentException(
\sprintf(
'Invalid cache item class "%s" for driver "%s".',
get_class($item),
get_class($this)
)
);
}
/**
* @inheritDoc
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
public function getItems(array $keys = []): iterable
{
$items = [];
/**
* Usually, drivers that are able to enable cache slams
* does not benefit of driverReadMultiple() call.
*/
if (!$this->getConfig()->isPreventCacheSlams()) {
$this->validateCacheKeys(...$keys);
/**
* Check for local item instances first.
*/
foreach ($keys as $index => $key) {
if (isset($this->itemInstances[$key]) && $this->getConfig()->isUseStaticItemCaching()) {
$items[$key] = $this->itemInstances[$key];
// Key already exists in local item instances, no need to fetch it again.
unset($keys[$index]);
}
}
$keys = array_values($keys);
/**
* If there's still keys to fetch, let's choose the right method (if supported).
*/
if (count($keys) > 1) {
$items = array_merge(
array_combine($keys, array_map(fn($key) => new (self::getItemClass())($this, $key, $this->eventManager), $keys)),
$items
);
try {
$driverArrays = $this->driverReadMultiple(...$items);
} catch (PhpfastcacheUnsupportedMethodException) {
/**
* Fallback for drivers that does not yet implement driverReadMultiple() method.
*/
$driverArrays = array_combine(
array_map(fn($item) => $item->getKey(), $items),
array_map(fn($item) => $this->driverRead($item), $items)
);
} finally {
foreach ($items as $item) {
$driverArray = $driverArrays[$item->getKey()] ?? null;
if ($driverArray !== null) {
$item->set($this->driverUnwrapData($driverArray));
$item->expiresAt($this->driverUnwrapEdate($driverArray));
if ($this->getConfig()->isItemDetailedDate()) {
/**
* If the itemDetailedDate has been
* set after caching, we MUST inject
* a new DateTime object on the fly
*/
$item->setCreationDate($this->driverUnwrapCdate($driverArray) ?: new DateTime());
$item->setModificationDate($this->driverUnwrapMdate($driverArray) ?: new DateTime());
}
$item->setTags($this->driverUnwrapTags($driverArray));
$this->handleExpiredCacheItem($item);
} else {
$item->expiresAfter((int) abs($this->getConfig()->getDefaultTtl()));
}
$item->isHit() ? $this->getIO()->incReadHit() : $this->getIO()->incReadMiss();
}
}
} else {
$index = array_key_first($keys);
if ($index !== null) {
$items[$keys[$index]] = $this->getItem($keys[$index]);
}
}
} else {
$collection = [];
foreach ($keys as $key) {
$collection[$key] = $this->getItem($key);
}
return $collection;
}
$this->eventManager->dispatch(Event::CACHE_GET_ITEMS, $this, $items);
return $items;
}
/**
* @param string $key
* @return ExtendedCacheItemInterface
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
* @throws PhpfastcacheDriverException
*
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.GotoStatement)
*/
public function getItem(string $key): ExtendedCacheItemInterface
{
/**
* Replace array_key_exists by isset
* due to performance issue on huge
* loop dispatching operations
*/
if (!isset($this->itemInstances[$key]) || !$this->getConfig()->isUseStaticItemCaching()) {
$this->validateCacheKeys($key);
/** @var $item ExtendedCacheItemInterface */
$item = new (self::getItemClass())($this, $key, $this->eventManager);
$getItemDriverRead = function (float $cacheSlamsSpendSeconds = 0) use (&$getItemDriverRead, $item): void {
$config = $this->getConfig();
$driverArray = $this->driverRead($item);
if ($driverArray) {
$driverData = $this->driverUnwrapData($driverArray);
if ($config instanceof IOConfigurationOptionInterface && $config->isPreventCacheSlams()) {
while ($driverData instanceof ItemBatch) {
if ($driverData->getItemDate()->getTimestamp() + $config->getCacheSlamsTimeout() < \time()) {
/**
* The timeout has been reached
* Consider that the batch has
* failed and serve an empty item
* to avoid get stuck with a
* batch item stored in driver
*/
$this->handleExpiredCacheItem($item);
return;
}
$this->eventManager->dispatch(Event::CACHE_GET_ITEM_IN_SLAM_BATCH, $this, $driverData, $cacheSlamsSpendSeconds);
/**
* Wait for a second before
* attempting to get exit
* the current batch process
*/
\usleep(100000);
$getItemDriverRead($cacheSlamsSpendSeconds + 0.1);
}
}
$item->set($driverData);
$item->expiresAt($this->driverUnwrapEdate($driverArray));
if ($this->getConfig()->isItemDetailedDate()) {
/**
* If the itemDetailedDate has been
* set after caching, we MUST inject
* a new DateTime object on the fly
*/
$item->setCreationDate($this->driverUnwrapCdate($driverArray) ?: new DateTime());
$item->setModificationDate($this->driverUnwrapMdate($driverArray) ?: new DateTime());
}
$item->setTags($this->driverUnwrapTags($driverArray));
$this->handleExpiredCacheItem($item);
} else {
$item->expiresAfter((int) abs($this->getConfig()->getDefaultTtl()));
}
};
$getItemDriverRead();
} else {
$item = $this->itemInstances[$key];
}
$this->eventManager->dispatch(Event::CACHE_GET_ITEM, $this, $item);
$item->isHit() ? $this->getIO()->incReadHit() : $this->getIO()->incReadMiss();
return $item;
}
/**
* @param string $key
* @return bool
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
public function hasItem(string $key): bool
{
return $this->getItem($key)->isHit();
}
/**
* @return bool
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheLogicException
* @throws PhpfastcacheIOException
*/
public function clear(): bool
{
$this->eventManager->dispatch(Event::CACHE_CLEAR_ITEM, $this, $this->itemInstances);
$this->getIO()->incWriteHit();
// Faster than detachAllItems()
$this->itemInstances = [];
return $this->driverClear();
}
/**
* @inheritDoc
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
public function deleteItems(array $keys): bool
{
if (count($keys) > 1) {
$return = true;
try {
$items = $this->getItems($keys);
$return = $this->driverDeleteMultiple($keys);
foreach ($items as $item) {
$item->setHit(false);
if (!\str_starts_with($item->getKey(), TaggableCacheItemPoolInterface::DRIVER_TAGS_KEY_PREFIX)) {
$this->cleanItemTags($item);
}
}
$this->getIO()->incWriteHit();
$this->eventManager->dispatch(Event::CACHE_DELETE_ITEMS, $this, $items);
$this->deregisterItems($keys);
} catch (PhpfastcacheUnsupportedMethodException) {
foreach ($keys as $key) {
$result = $this->deleteItem($key);
if ($result !== true) {
$return = false;
}
}
}
return $return;
}
$index = array_key_first($keys);
if ($index !== null) {
return $this->deleteItem($keys[$index]);
}
return false;
}
/**
* @param string $key
* @return bool
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
public function deleteItem(string $key): bool
{
$item = $this->getItem($key);
if ($item->isHit()) {
$result = $this->driverDelete($item->getKey(), $item->getEncodedKey());
$item->setHit(false);
$this->getIO()->incWriteHit();
$this->eventManager->dispatch(Event::CACHE_DELETE_ITEM, $this, $item);
/**
* De-register the item instance
* then collect gc cycles
*/
$this->deregisterItem($key);
/**
* Perform a tag cleanup to avoid memory leaks
*/
if (!\str_starts_with($key, TaggableCacheItemPoolInterface::DRIVER_TAGS_KEY_PREFIX)) {
$this->cleanItemTags($item);
}
return $result;
}
return false;
}
/**
* @param CacheItemInterface $item
* @return bool
*/
public function saveDeferred(CacheItemInterface $item): bool
{
$this->assertCacheItemType($item, self::getItemClass());
if (!\array_key_exists($item->getKey(), $this->itemInstances)) {
$this->itemInstances[$item->getKey()] = $item;
} elseif (\spl_object_hash($item) !== \spl_object_hash($this->itemInstances[$item->getKey()])) {
throw new RuntimeException('Spl object hash mismatches ! You probably tried to save a detached item which has been already retrieved from cache.');
}
$this->eventManager->dispatch(Event::CACHE_SAVE_DEFERRED_ITEM, $this, $item);
$this->deferredList[$item->getKey()] = $item;
return true;
}
/**
* @return bool
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
public function commit(): bool
{
$this->eventManager->dispatch(Event::CACHE_COMMIT_ITEM, $this, new EventReferenceParameter($this->deferredList));
if (\count($this->deferredList)) {
$return = true;
foreach ($this->deferredList as $key => $item) {
$result = $this->save($item);
unset($this->deferredList[$key]);
if ($result !== true) {
$return = $result;
}
}
return $return;
}
return false;
}
/**
* @param CacheItemInterface $item
* @return bool
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheIOException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
public function save(CacheItemInterface $item): bool
{
$this->assertCacheItemType($item, self::getItemClass());
/**
* @var ExtendedCacheItemInterface $item
*
* Replace array_key_exists by isset
* due to performance issue on huge
* loop dispatching operations
*/
if (!isset($this->itemInstances[$item->getKey()])) {
if ($this->getConfig()->isUseStaticItemCaching()) {
$this->itemInstances[$item->getKey()] = $item;
}
} elseif (\spl_object_hash($item) !== \spl_object_hash($this->itemInstances[$item->getKey()])) {
throw new RuntimeException('Spl object hash mismatches ! You probably tried to save a detached item which has been already retrieved from cache.');
}
$this->assertCacheItemType($item, self::getItemClass());
$this->eventManager->dispatch(Event::CACHE_SAVE_ITEM, $this, $item);
if ($this->getConfig() instanceof IOConfigurationOptionInterface && $this->getConfig()->isPreventCacheSlams()) {
/**
* @var $itemBatch ExtendedCacheItemInterface
*/
$itemClassName = self::getItemClass();
$itemBatch = new $itemClassName($this, $item->getKey(), $this->eventManager);
$itemBatch->set(new ItemBatch($item->getKey(), new DateTime()))
->expiresAfter($this->getConfig()->getCacheSlamsTimeout());
/**
* To avoid SPL mismatches
* we have to re-attach the
* original item to the pool
*/
$this->driverWrite($itemBatch);
$this->detachItem($itemBatch);
$this->attachItem($item);
}
if ($this->driverWrite($item) && $this->driverWriteTags($item)) {
$item->setHit(true)
->clearRemovedTags();
if ($this->getConfig()->isItemDetailedDate()) {
$item->setModificationDate(new \DateTime());
}
$this->getIO()->incWriteHit();
return true;
}
return false;
}
/**
* @return DriverIO
*/
public function getIO(): DriverIO
{
return $this->IO;
}
/**
* @internal This method de-register an item from $this->itemInstances
*/
protected function deregisterItem(string $itemKey): static
{
unset($this->itemInstances[$itemKey]);
if (\gc_enabled()) {
\gc_collect_cycles();
}
return $this;
}
/**
* @param string[] $itemKeys
* @internal This method de-register multiple items from $this->itemInstances
*/
protected function deregisterItems(array $itemKeys): static
{
$this->itemInstances = array_diff_key($this->itemInstances, array_flip($itemKeys));
if (\gc_enabled()) {
\gc_collect_cycles();
}
return $this;
}
/**
* @throws PhpfastcacheLogicException
*/
public function attachItem(CacheItemInterface $item): static
{
if (isset($this->itemInstances[$item->getKey()]) && \spl_object_hash($item) !== \spl_object_hash($this->itemInstances[$item->getKey()])) {
throw new PhpfastcacheLogicException(
'The item already exists and cannot be overwritten because the Spl object hash mismatches !
You probably tried to re-attach a detached item which has been already retrieved from cache.'
);
}
if (!$this->getConfig()->isUseStaticItemCaching()) {
throw new PhpfastcacheLogicException(
'The static item caching option (useStaticItemCaching) is disabled so you cannot attach an item.'
);
}
$this->itemInstances[$item->getKey()] = $item;
return $this;
}
public function isAttached(CacheItemInterface $item): bool
{
if (isset($this->itemInstances[$item->getKey()])) {
return \spl_object_hash($item) === \spl_object_hash($this->itemInstances[$item->getKey()]);
}
return false;
}
protected function validateCacheKeys(string ...$keys): void
{
foreach ($keys as $key) {
if (\preg_match('~([' . \preg_quote(self::$unsupportedKeyChars, '~') . ']+)~', $key, $matches)) {
throw new PhpfastcacheInvalidArgumentException(
'Unsupported key character detected: "' . $matches[1] . '".
Please check: https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV6%5D-Unsupported-characters-in-key-identifiers'
);
}
}
}
protected function handleExpiredCacheItem(ExtendedCacheItemInterface $item): void
{
if ($item->isExpired()) {
/**
* Using driverDelete() instead of delete()
* to avoid infinite loop caused by
* getItem() call in delete() method
* As we MUST return an item in any
* way, we do not de-register here
*/
$this->driverDelete($item->getKey(), $item->getEncodedKey());
/**
* Reset the Item
*/
$item->set(null)
->expiresAfter((int) abs($this->getConfig()->getDefaultTtl()))
->setHit(false)
->setTags([]);
if ($this->getConfig()->isItemDetailedDate()) {
/**
* If the itemDetailedDate has been
* set after caching, we MUST inject
* a new DateTime object on the fly
*/
$item->setCreationDate(new DateTime());
$item->setModificationDate(new DateTime());
}
} else {
$item->setHit(true);
}
}
/**
* @param ExtendedCacheItemInterface[] $items
* @param bool $encoded
* @param string $keyPrefix
* @return string[]
*/
protected function getKeys(array $items, bool $encoded = false, string $keyPrefix = ''): array
{
return array_map(
static fn(ExtendedCacheItemInterface $item) => $keyPrefix . ($encoded ? $item->getEncodedKey() : $item->getKey()),
$items
);
}
}
@@ -0,0 +1,324 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Core\Pool;
use DateTime;
use DateTimeInterface;
use Phpfastcache\Config\ConfigurationOptionInterface;
use Phpfastcache\Event\Event;
use Phpfastcache\Event\EventManagerDispatcherTrait;
use Phpfastcache\Event\EventManagerInterface;
use Phpfastcache\Exceptions\PhpfastcacheCorruptedDataException;
use Phpfastcache\Exceptions\PhpfastcacheDriverException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Util\ClassNamespaceResolverTrait;
use Throwable;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Entities\DriverIO;
use Phpfastcache\Exceptions\PhpfastcacheCoreException;
use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException;
use Phpfastcache\Exceptions\PhpfastcacheDriverConnectException;
use Phpfastcache\Exceptions\PhpfastcacheIOException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use ReflectionObject;
trait DriverBaseTrait
{
use DriverPoolAbstractTrait;
use ClassNamespaceResolverTrait;
use EventManagerDispatcherTrait;
/**
* @var string[]
*/
protected static array $cacheItemClasses = [];
protected ConfigurationOptionInterface $config;
/**
* @var object|null
*/
protected ?object $instance;
protected string $driverName;
protected string $instanceId;
/**
* Driver constructor.
* @param ConfigurationOptionInterface $config
* @param string $instanceId
* @param EventManagerInterface $em
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverCheckException
* @throws PhpfastcacheDriverConnectException
* @throws PhpfastcacheIOException
* @throws PhpfastcacheInvalidArgumentException
*/
public function __construct(#[\SensitiveParameter] ConfigurationOptionInterface $config, string $instanceId, EventManagerInterface $em)
{
$this->setEventManager($em->getScopedEventManager($this));
$this->setConfig($config);
$this->instanceId = $instanceId;
if (!$this->driverCheck()) {
throw new PhpfastcacheDriverCheckException(
\sprintf(
ExtendedCacheItemPoolInterface::DRIVER_CHECK_FAILURE,
$this->getDriverName(),
$this->getHelp() ? " Additionally, {$this->getHelp()}" : ''
)
);
}
$this->eventManager->dispatch(Event::CACHE_DRIVER_CHECKED, $this);
try {
$this->driverConnect();
$config->lock($this); // Lock the config only after a successful driver connection.
$this->eventManager->dispatch(Event::CACHE_DRIVER_CONNECTED, $this, $this->instance ?? null);
} catch (Throwable $e) {
throw new PhpfastcacheDriverConnectException(
sprintf(
ExtendedCacheItemPoolInterface::DRIVER_CONNECT_FAILURE,
$this->getDriverName(),
$e->getMessage(),
$e->getLine() ?: 'unknown line',
$e->getFile() ?: 'unknown file',
),
0,
$e
);
}
}
/**
* @return string
*/
public function getDriverName(): string
{
if (!isset($this->driverName)) {
$this->driverName = \ucfirst(\substr(\strrchr((new ReflectionObject($this))->getNamespaceName(), '\\'), 1));
}
return $this->driverName;
}
/**
* @return ConfigurationOptionInterface
*/
public function getDefaultConfig(): ConfigurationOptionInterface
{
$className = $this::getConfigClass();
return new $className();
}
/**
* @return string
*/
public static function getConfigClass(): string
{
$localConfigClass = \substr(static::class, 0, \strrpos(static::class, '\\')) . '\Config';
if (\class_exists($localConfigClass) && \is_a($localConfigClass, ConfigurationOption::class, true)) {
return $localConfigClass;
}
return ConfigurationOption::class;
}
public static function getItemClass(): string
{
if (!isset(self::$cacheItemClasses[static::class])) {
self::$cacheItemClasses[static::class] = self::getClassNamespace() . '\\' . 'Item';
}
return self::$cacheItemClasses[static::class];
}
/**
* @inheritDoc
*/
public function getEncodedKey(string $key): string
{
$keyHashFunction = $this->getConfig()->getDefaultKeyHashFunction();
if ($keyHashFunction) {
if (\is_callable($keyHashFunction)) {
return $keyHashFunction($key);
}
throw new PhpfastcacheLogicException('Unable to build the encoded key (defaultKeyHashFunction is not callable)');
}
return $key;
}
/**
* @param ExtendedCacheItemInterface $item
* @param bool $stringifyDate
* @return array<string, mixed>
* @throws PhpfastcacheLogicException
*/
public function driverPreWrap(ExtendedCacheItemInterface $item, bool $stringifyDate = false): array
{
$wrap = [
ExtendedCacheItemPoolInterface::DRIVER_KEY_WRAPPER_INDEX => $item->getKey(), // Stored but not really used, allow you to quickly identify the cache key
ExtendedCacheItemPoolInterface::DRIVER_DATA_WRAPPER_INDEX => $item->_getData(),
ExtendedCacheItemPoolInterface::DRIVER_EDATE_WRAPPER_INDEX => $item->getExpirationDate(),
TaggableCacheItemPoolInterface::DRIVER_TAGS_WRAPPER_INDEX => $item->getTags(),
];
if ($this->getConfig()->isItemDetailedDate()) {
$wrap[ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX] = new DateTime();// Always on the latest date
/**
* If the creation date exists
* reuse it else set a new Date
*/
$wrap[ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX] = $item->getCreationDate();
} else {
$wrap[ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX] = null;
$wrap[ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX] = null;
}
if ($stringifyDate) {
\array_walk($wrap, static function (mixed &$value, string $key): void {
if ($value instanceof DateTimeInterface && $key !== ExtendedCacheItemPoolInterface::DRIVER_DATA_WRAPPER_INDEX) {
$value = $value->format(DateTimeInterface::W3C);
}
});
}
return $wrap;
}
/**
* @return ConfigurationOptionInterface
*/
public function getConfig(): ConfigurationOptionInterface
{
return $this->config;
}
/**
* @param ConfigurationOptionInterface $config
* @return static
*/
public function setConfig(ConfigurationOptionInterface $config): static
{
$this->config = $config;
return $this;
}
/**
* @param array<string, mixed> $wrapper
* @return mixed
* @throws \Exception
*/
public function driverUnwrapData(array $wrapper): mixed
{
return $wrapper[ExtendedCacheItemPoolInterface::DRIVER_DATA_WRAPPER_INDEX];
}
/**
* @param array<string, mixed> $wrapper
* @return DateTimeInterface
*/
public function driverUnwrapEdate(array $wrapper): \DateTimeInterface
{
if ($wrapper[ExtendedCacheItemPoolInterface::DRIVER_EDATE_WRAPPER_INDEX] instanceof \DateTimeInterface) {
return $wrapper[ExtendedCacheItemPoolInterface::DRIVER_EDATE_WRAPPER_INDEX];
}
return DateTime::createFromFormat(\DateTimeInterface::W3C, $wrapper[ExtendedCacheItemPoolInterface::DRIVER_EDATE_WRAPPER_INDEX]);
}
/**
* @param array<string, mixed> $wrapper
* @return DateTimeInterface|null
*/
public function driverUnwrapCdate(array $wrapper): ?\DateTimeInterface
{
if ($wrapper[ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX] instanceof \DateTimeInterface) {
return $wrapper[ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX];
}
return DateTime::createFromFormat(\DateTimeInterface::W3C, $wrapper[ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX]);
}
/**
* @param array<string, mixed> $wrapper
* @return DateTimeInterface|null
*/
public function driverUnwrapMdate(array $wrapper): ?\DateTimeInterface
{
if ($wrapper[ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX] instanceof \DateTimeInterface) {
return $wrapper[ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX];
}
return DateTime::createFromFormat(\DateTimeInterface::W3C, $wrapper[ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX]);
}
/**
* @return string
*/
public function getInstanceId(): string
{
return $this->instanceId;
}
/**
* Encode data types such as object/array
* for driver that does not support
* non-scalar value
* @param mixed $data
* @return string
*/
protected function encode(mixed $data): string
{
return \serialize($data);
}
/**
* Decode data stored in the cache
* for driver that does not support
* non-scalar value storage.
* @param string|null $value
* @return array<string, mixed>|null
* @throws PhpfastcacheDriverException
*/
protected function decode(?string $value): ?array
{
$decoded = $this->unserialize($value);
if ($decoded === null || is_array($decoded)) {
return $decoded;
}
throw new PhpfastcacheCorruptedDataException(
sprintf(
'Failed to unserialize data from the cache, expected array or null but got "%s". Stored data may be corrupted.',
gettype($decoded)
),
$value
);
}
protected function unserialize(?string $value): mixed
{
return $value ? \unserialize($value, ['allowed_classes' => true]) : null;
}
}
@@ -0,0 +1,124 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Core\Pool;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheUnsupportedMethodException;
use Phpfastcache\Wiki;
use Psr\Cache\CacheItemInterface;
trait DriverPoolAbstractTrait
{
/**
* @return bool
*/
abstract protected function driverCheck(): bool;
/**
* @return bool
*/
abstract protected function driverConnect(): bool;
/**
* @param ExtendedCacheItemInterface $item
* @return ?array<string, mixed>
*/
abstract protected function driverRead(ExtendedCacheItemInterface $item): ?array;
/**
* @param ExtendedCacheItemInterface ...$items
* @return array<array<string, mixed>>
* @throws PhpfastcacheUnsupportedMethodException
*/
protected function driverReadMultiple(ExtendedCacheItemInterface ...$items): array
{
throw new PhpfastcacheUnsupportedMethodException();
}
/**
* @return \Traversable<int, string>
* @throws PhpfastcacheUnsupportedMethodException
*/
protected function driverReadAllKeys(string $pattern = ''): iterable
{
throw new PhpfastcacheUnsupportedMethodException(
sprintf(
'The "readAll" operation is unsupported by the the "%s" driver. See the Wiki for more information at %s',
$this->getDriverName(),
Wiki::FETCH_ALL_KEY_URL,
)
);
}
/**
* @param ExtendedCacheItemInterface $item
* @return bool
*/
abstract protected function driverWrite(ExtendedCacheItemInterface $item): bool;
/**
* @param ExtendedCacheItemInterface ...$item
* @return bool
* @throws PhpfastcacheUnsupportedMethodException
*/
protected function driverWriteMultiple(ExtendedCacheItemInterface ...$item): bool
{
/**
* @todo Implement bulk writes to be for v10:
* For methods commit() and saveMultiple()
*/
throw new PhpfastcacheUnsupportedMethodException();
}
/**
* @param string $key
* @param string $encodedKey
* @return bool
*/
abstract protected function driverDelete(string $key, string $encodedKey): bool;
/**
* @param string[] $keys
* @return bool
* @throws PhpfastcacheUnsupportedMethodException
*/
protected function driverDeleteMultiple(array $keys): bool
{
throw new PhpfastcacheUnsupportedMethodException();
}
/**
* @return bool
*/
abstract protected function driverClear(): bool;
/**
* @param CacheItemInterface $item
* @param string $expectedClassType
* @throws PhpfastcacheInvalidArgumentException
*/
protected function assertCacheItemType(CacheItemInterface $item, string $expectedClassType): void
{
if (!($item instanceof $expectedClassType)) {
throw new PhpfastcacheInvalidArgumentException(
\sprintf('Cross-driver type confusion detected: Expected "%s" object, got "%s"', $expectedClassType, $item::class)
);
}
}
}
@@ -0,0 +1,231 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Core\Pool;
use InvalidArgumentException;
use Phpfastcache\Config\ConfigurationOptionInterface;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Entities\DriverIO;
use Phpfastcache\Entities\DriverStatistic;
use Phpfastcache\Event\EventManagerDispatcherInterface;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Phpfastcache\Exceptions\PhpfastcacheUnsupportedMethodException;
use Phpfastcache\Util\ClassNamespaceResolverInterface;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
/**
* Extended cache item pool interface that
* contains all the phpfastcache-related
* methods that does not belong to PSR-6.
*/
interface ExtendedCacheItemPoolInterface extends CacheItemPoolInterface, EventManagerDispatcherInterface, ClassNamespaceResolverInterface, TaggableCacheItemPoolInterface
{
public const DRIVER_CHECK_FAILURE = '%s is not installed or is misconfigured, cannot continue.
Also, please verify the suggested dependencies in composer because as of the V6, 3rd party libraries are no longer required.%s';
public const DRIVER_CONNECT_FAILURE = '%s failed to connect with the following error message: "%s" line %d in %s.';
public const DRIVER_KEY_WRAPPER_INDEX = 'k';
public const DRIVER_DATA_WRAPPER_INDEX = 'd';
/**
* Expiration date Index
*/
public const DRIVER_EDATE_WRAPPER_INDEX = 'e';
/**
* Creation date Index
*/
public const DRIVER_CDATE_WRAPPER_INDEX = 'c';
/**
* Modification date Index
*/
public const DRIVER_MDATE_WRAPPER_INDEX = 'm';
/**
* Hard-limit count of items returns by getAllItems()
*/
public const MAX_ALL_KEYS_COUNT = 9999;
/**
* Return the config class name
* @return string
*/
public static function getConfigClass(): string;
/**
* Return the item class name
* @return string
*/
public static function getItemClass(): string;
/**
* @param string $key
* @return string
*/
public function getEncodedKey(string $key): string;
/**
* @return ConfigurationOptionInterface
*/
public function getConfig(): ConfigurationOptionInterface;
/**
* @return ConfigurationOptionInterface
*/
public function getDefaultConfig(): ConfigurationOptionInterface;
/**
* @return string
*/
public function getDriverName(): string;
/**
* @return mixed
*/
public function getInstanceId(): string;
/**
* [Phpfastcache phpDoc Override]
* Returns a Cache Item representing the specified key.
*
* This method must always return a CacheItemInterface object, even in case of
* a cache miss. It MUST NOT return null.
*
* @param string $key
* The key for which to return the corresponding Cache Item.
*
* @return ExtendedCacheItemInterface
* The corresponding Cache Item.
* @throws PhpfastcacheInvalidArgumentException
* If the $key string is not a legal value a phpfastcacheInvalidArgumentException
* MUST be thrown.
*
*/
public function getItem(string $key): ExtendedCacheItemInterface;
/**
* [Phpfastcache phpDoc Override]
* Returns a traversable set of cache items.
*
* @param string[] $keys
* An indexed array of keys of items to retrieve.
*
* @return iterable<ExtendedCacheItemInterface>
* A traversable collection of Cache Items keyed by the cache keys of
* each item. A Cache item will be returned for each key, even if that
* key is not found. However, if no keys are specified then an empty
* traversable MUST be returned instead.
* @throws InvalidArgumentException
* If any of the keys in $keys are not a legal value a phpfastcacheInvalidArgumentException
* MUST be thrown.
*
*/
public function getItems(array $keys = []): iterable;
/**
* Returns the WHOLE cache as a traversable set of cache items.
* A hard-limit of 9999 items is defined internally to prevent
* serious performances issues of your application.
* @see ExtendedCacheItemPoolInterface::MAX_ALL_KEYS_COUNT
*
* @param string $pattern
* An optional pattern supported by a limited range of drivers.
* If this parameter is unsupported by the driver, a PhpfastcacheInvalidArgumentException will be thrown.
*
* @return iterable<ExtendedCacheItemInterface>
* A traversable collection of Cache Items keyed by the cache keys of
* each item. However, if no keys are returned by the backend then an empty
* traversable WILL be returned instead.
*
* @throws PhpfastcacheInvalidArgumentException If the driver does not support the $pattern argument
* @throws PhpfastcacheUnsupportedMethodException If the driver does not permit to list all the keys through this implementation.
*/
public function getAllItems(string $pattern = ''): iterable;
/**
* Returns A json string that represents an array of items.
*
* @param array<string> $keys An indexed array of keys of items to retrieve.
* @param int $options \json_encode() options
* @param int $depth \json_encode() depth
*
* @return string
* @throws InvalidArgumentException
* If any of the keys in $keys are not a legal value a phpfastcacheInvalidArgumentException
* MUST be thrown.
*
*/
public function getItemsAsJsonString(array $keys = [], int $options = \JSON_THROW_ON_ERROR, int $depth = 512): string;
public function setItem(CacheItemInterface $item): static;
public function getStats(): DriverStatistic;
/**
* Get a quick help guide
* about the current driver
*/
public function getHelp(): string;
public function detachItem(CacheItemInterface $item): static;
public function detachAllItems(): static;
public function attachItem(CacheItemInterface $item): static;
/**
* Returns true if the item exists, is attached and the Spl Hash matches
* Returns false if the item exists, is attached and the Spl Hash mismatches
* Returns null if the item does not exist
*
* @param CacheItemInterface $item
* @return bool
* @throws PhpfastcacheLogicException
*/
public function isAttached(CacheItemInterface $item): bool;
/**
* Persists a cache item immediately.
*
* @param ExtendedCacheItemInterface|CacheItemInterface $item
* The cache item to save.
*
* @return bool
* True if the item was successfully persisted. False if there was an error.
*/
public function save(ExtendedCacheItemInterface|CacheItemInterface $item): bool;
/**
* Save multiple items, possible uses:
* saveMultiple([$item1, $item2, $item3]);
* saveMultiple($item1, $item2, $item3);
*
* @param ExtendedCacheItemInterface[] $items
* @return bool
*/
public function saveMultiple(ExtendedCacheItemInterface ...$items): bool;
/**
* @return DriverIO
*/
public function getIO(): DriverIO;
}
@@ -0,0 +1,135 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Core\Pool;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Event\Event;
use Phpfastcache\Event\EventReferenceParameter;
use Phpfastcache\Exceptions\PhpfastcacheCoreException;
use Phpfastcache\Exceptions\PhpfastcacheDriverException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Psr\Cache\CacheItemInterface;
trait ExtendedCacheItemPoolTrait
{
use CacheItemPoolTrait;
use AggregatablePoolTrait;
/**
* @inheritDoc
* @param string $pattern
* @return array<string, mixed>
*/
public function getAllItems(string $pattern = ''): iterable
{
$driverReadAllKeysCallback = fn (string $pattern): iterable => $this->driverReadAllKeys($pattern);
/**
* This event allow you to customize the callback and wrap it to an invoker
* like SebastianBergmann\Invoke\Invoke, so you can set up custom timeouts.
*/
$this->eventManager->dispatch(Event::CACHE_GET_ALL_ITEMS, $this, new EventReferenceParameter($driverReadAllKeysCallback));
$keys = $driverReadAllKeysCallback($pattern);
if (count($keys) > 0) {
return $this->getItems($keys instanceof \Traversable ? iterator_to_array($keys) : $keys);
}
return [];
}
/**
* @inheritDoc
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
public function getItemsAsJsonString(array $keys = [], int $options = \JSON_THROW_ON_ERROR, int $depth = 512): string
{
return \json_encode(
\array_map(
static fn(CacheItemInterface $item) => $item->get(),
\array_values($this->getItems($keys))
),
$options,
$depth
);
}
public function detachAllItems(): static
{
foreach ($this->itemInstances as $item) {
$this->detachItem($item);
}
return $this;
}
public function detachItem(CacheItemInterface $item): static
{
if (isset($this->itemInstances[$item->getKey()])) {
$this->deregisterItem($item->getKey());
}
return $this;
}
/**
* @param ExtendedCacheItemInterface ...$items
* @return bool
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
public function saveMultiple(ExtendedCacheItemInterface ...$items): bool
{
$this->eventManager->dispatch(Event::CACHE_SAVE_MULTIPLE_ITEMS, $this, new EventReferenceParameter($items));
if (\count($items)) {
foreach ($items as $item) {
$this->save($item);
}
return true;
}
return false;
}
/**
* @return string
*/
public function getHelp(): string
{
return '';
}
/**
* @throws PhpfastcacheInvalidArgumentException
*/
public function throwUnsupportedDriverReadAllPattern(string $linkReference = ''): void
{
throw new PhpfastcacheInvalidArgumentException(
sprintf(
'%s does not support a pattern argument.%s',
$this->getDriverName(),
$linkReference ? " See $linkReference" : ''
)
);
}
}
@@ -0,0 +1,314 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Core\Pool\IO;
use Phpfastcache\Config\IOConfigurationOptionInterface;
use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait;
use Phpfastcache\Entities\DriverStatistic;
use Phpfastcache\Event\Event;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheIOException;
use Phpfastcache\Util\Directory;
use Phpfastcache\Util\SapiDetector;
/**
* @method IOConfigurationOptionInterface getConfig()
*/
trait IOHelperTrait
{
use TaggableCacheItemPoolTrait;
/**
* @var array<string, string>
*/
public array $tmp = [];
/**
* Provide a generic getStats() method
* for files-based drivers
* @return DriverStatistic
* @throws PhpfastcacheIOException
* @throws PhpfastcacheInvalidArgumentException
*/
public function getStats(): DriverStatistic
{
$stat = new DriverStatistic();
$path = $this->getFilePath(false);
if (!is_dir($path)) {
throw new PhpfastcacheIOException("Can't read PATH:" . $path);
}
$stat->setSize(Directory::dirSize($path))
->setInfo('Number of files used to build the cache: ' . Directory::getFileCount($path))
->setRawData(
[
'tmp' => $this->tmp,
]
);
if ($this->getConfig()->isUseStaticItemCaching()) {
$stat->setData(implode(', ', \array_keys($this->itemInstances)));
} else {
$stat->setData('No data available since static item caching option (useStaticItemCaching) is disabled.');
}
return $stat;
}
/**
* @param string|bool $keyword
* @param bool $skip
* @return string
* @throws PhpfastcacheIOException
* @throws PhpfastcacheInvalidArgumentException
*/
protected function getFilePath(string|bool $keyword, bool $skip = false): string
{
$path = $this->getPath();
if ($keyword === false) {
return $path;
}
$filename = $this->encodeFilename($keyword);
$folder = \substr($filename, 0, 2) . DIRECTORY_SEPARATOR . \substr($filename, 2, 2);
$path = \rtrim($path, '/\\') . DIRECTORY_SEPARATOR . $folder;
/**
* Skip Create Sub Folders;
*/
if (!$skip && !\is_dir($path) && @!\mkdir($path, $this->getDefaultChmod(), true) && !\is_dir($path)) {
throw new PhpfastcacheIOException(
'Path "' . $path . '" is not writable, please set a chmod 0777 or any writable permission and make sure to make use of an absolute path !'
);
}
return $path . \DIRECTORY_SEPARATOR . $filename . '.' . $this->getConfig()->getCacheFileExtension();
}
/**
* @param bool $readonly
* @return string
* @throws PhpfastcacheIOException
* @throws PhpfastcacheInvalidArgumentException
*/
public function getPath(bool $readonly = false): string
{
$tmpDir = \rtrim(\ini_get('upload_tmp_dir') ?: \sys_get_temp_dir(), '\\/') . DIRECTORY_SEPARATOR . 'phpfastcache';
$httpHost = $this->getConfig()->getSuperGlobalAccessor()('SERVER', 'HTTP_HOST');
$securityKey = $this->buildSecurityKey($httpHost);
/**
* Extends the temporary directory
* with the security key and the driver name
*/
$tmpDir = \rtrim($tmpDir, '/') . DIRECTORY_SEPARATOR;
if (empty($this->getConfig()->getPath())) {
$path = $tmpDir;
} else {
$path = \rtrim($this->getConfig()->getPath(), '/') . DIRECTORY_SEPARATOR;
}
$pathSuffix = $securityKey . DIRECTORY_SEPARATOR . $this->getDriverName();
$fullPath = Directory::getAbsolutePath($path . $pathSuffix);
$fullPathTmp = Directory::getAbsolutePath($tmpDir . $pathSuffix);
$this->mkdir($fullPath, $fullPathTmp);
/**
* In readonly mode we only attempt
* to verify if the directory exists
* or not, if it does not then we
* return the temp dir
*/
if ($readonly) {
if ($this->getConfig()->isAutoTmpFallback() && (!@\file_exists($fullPath) || !@\is_writable($fullPath))) {
return $fullPathTmp;
}
return $fullPath;
}
return realpath($fullPath);
}
protected function buildSecurityKey(?string $httpHost): string
{
$securityKey = $this->getConfig()->getSecurityKey();
if (!$securityKey || \mb_strtolower($securityKey) === 'auto') {
if (isset($httpHost)) {
$securityKey = \preg_replace('/^www./', '', \strtolower(\str_replace(':', '_', $httpHost)));
} else {
$securityKey = (SapiDetector::isWebScript() ? 'web' : 'cli');
}
}
if (!empty($securityKey)) {
$securityKey .= '/';
}
return static::cleanFileName($securityKey);
}
/**
* @throws PhpfastcacheIOException
*/
protected function mkdir(string $fullPath, string $fullPathTmp): void
{
$fullPathHash = $this->getConfig()->getDefaultFileNameHashFunction()($fullPath);
if (!isset($this->tmp[$fullPathHash]) || (!@\file_exists($fullPath) || !@\is_writable($fullPath))) {
if (!@\file_exists($fullPath)) {
if (@mkdir($fullPath, $this->getDefaultChmod(), true) === false && !\is_dir($fullPath)) {
throw new PhpfastcacheIOException('The directory ' . $fullPath . ' could not be created.');
}
} elseif (!@\is_writable($fullPath) && !@\chmod($fullPath, $this->getDefaultChmod()) && $this->getConfig()->isAutoTmpFallback()) {
/**
* Switch back to tmp dir
* again if the path is not writable
*/
$fullPath = $fullPathTmp;
if (!@\file_exists($fullPath) && @\mkdir($fullPath, $this->getDefaultChmod(), true) && !\is_dir($fullPath)) {
throw new PhpfastcacheIOException('The directory ' . $fullPath . ' could not be created.');
}
}
/**
* In case there is no directory
* writable including the temporary
* one, we must throw an exception
*/
if (!@\file_exists($fullPath) || !@\is_writable($fullPath)) {
throw new PhpfastcacheIOException(
'Path "' . $fullPath . '" is not writable, please set a chmod 0777 or any writable permission and make sure to make use of an absolute path !'
);
}
$this->tmp[$fullPathHash] = $fullPath;
}
}
/**
* @param string $filename
* @return string
*/
protected static function cleanFileName(string $filename): string
{
$regex = [
'/[\?\[\]\/\\\=\<\>\:\;\,\'\"\&\$\#\*\(\)\|\~\`\!\{\}]/',
'/\.$/',
'/^\./',
];
$replace = ['-', '', ''];
return \trim(\preg_replace($regex, $replace, \trim($filename)), '-');
}
/**
* @return int
*/
protected function getDefaultChmod(): int
{
if (!$this->getConfig()->getDefaultChmod()) {
return 0777;
}
return $this->getConfig()->getDefaultChmod();
}
/**
* @param string $keyword
* @return string
*/
protected function encodeFilename(string $keyword): string
{
return $this->getConfig()->getDefaultFileNameHashFunction()($keyword);
}
/**
* @param string $file
* @return string
* @throws PhpfastcacheIOException
*/
protected function readFile(string $file): string
{
if (!\is_readable($file)) {
throw new PhpfastcacheIOException("Cannot read file located at: $file");
}
if (\function_exists('file_get_contents')) {
return (string)\file_get_contents($file);
}
$string = '';
$fileHandle = @\fopen($file, 'rb');
while (!\feof($fileHandle)) {
$line = \fgets($fileHandle);
$string .= $line;
}
\fclose($fileHandle);
return $string;
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @param string $file
* @param string $data
* @param bool $secureFileManipulation
* @return bool
* @throws PhpfastcacheIOException
* @throws \Exception
*/
protected function writeFile(string $file, string $data, bool $secureFileManipulation = false): bool
{
$this->eventManager->dispatch(Event::CACHE_WRITE_FILE_ON_DISK, $this, $file, $secureFileManipulation);
if ($secureFileManipulation) {
$tmpFilename = Directory::getAbsolutePath(
dirname($file) . \DIRECTORY_SEPARATOR . 'tmp_' . $this->getConfig()->getDefaultFileNameHashFunction()(
\bin2hex(\random_bytes(16))
)
) . '.' . $this->getConfig()->getCacheFileExtension() . \random_int(1000, 9999);
$handle = \fopen($tmpFilename, 'w+b');
if (\is_resource($handle)) {
\flock($handle, \LOCK_EX);
$octetWritten = fwrite($handle, $data);
\flock($handle, \LOCK_UN);
\fclose($handle);
}
if (!\rename($tmpFilename, $file)) {
throw new PhpfastcacheIOException(\sprintf('Failed to rename %s to %s', $tmpFilename, $file));
}
} else {
$handle = \fopen($file, 'w+b');
if (\is_resource($handle)) {
$octetWritten = \fwrite($handle, $data);
\fclose($handle);
}
}
return (bool)($octetWritten ?? false);
}
}
@@ -0,0 +1,288 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Core\Pool;
use InvalidArgumentException;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
interface TaggableCacheItemPoolInterface
{
public const DRIVER_TAGS_KEY_PREFIX = '_TAG_';
public const DRIVER_TAGS_WRAPPER_INDEX = 'g';
/**
* Allows you to get cache item(s) by at least **ONE** of the specified matching tag(s).
* Default behavior
*/
public const TAG_STRATEGY_ONE = 1;
/**
* Allows you to get cache item(s) by **ALL** of the specified matching tag(s)
* The cache item *CAN* have additional tag(s)
*/
public const TAG_STRATEGY_ALL = 2;
/**
* Allows you to get cache item(s) by **ONLY** the specified matching tag(s)
* The cache item *CANNOT* have additional tag(s)
*/
public const TAG_STRATEGY_ONLY = 4;
/**
* Returns a traversable set of cache items by a tag name.
*
* @param string $tagName
* An indexed array of keys of items to retrieve.
*
* @param int $strategy
*
* @return ExtendedCacheItemInterface[]
* A traversable collection of Cache Items keyed by the cache keys of
* each item. A Cache item will be returned for each key, even if that
* key is not found. However, if no keys are specified then an empty
* traversable MUST be returned instead.
* @throws InvalidArgumentException
* If any of the keys in $keys are not a legal value a phpfastcacheInvalidArgumentException
* MUST be thrown.
*
*/
public function getItemsByTag(string $tagName, int $strategy = self::TAG_STRATEGY_ONE): array;
/**
* Returns a traversable set of cache items by one of multiple tag names.
*
* @param string[] $tagNames
* An indexed array of keys of items to retrieve.
*
* @param int $strategy
*
* @return ExtendedCacheItemInterface[]
* A traversable collection of Cache Items keyed by the cache keys of
* each item. A Cache item will be returned for each key, even if that
* key is not found. However, if no keys are specified then an empty
* traversable MUST be returned instead.
* @throws InvalidArgumentException
* If any of the keys in $keys are not a legal value a phpfastcacheInvalidArgumentException
* MUST be thrown.
*
*/
public function getItemsByTags(array $tagNames, int $strategy = self::TAG_STRATEGY_ONE): array;
/**
* Returns A json string that represents an array of items by tags-based.
*
* @param string[] $tagNames
* An indexed array of keys of items to retrieve.
* @param int $option \json_encode() options
* @param int $depth \json_encode() depth
* @param int $strategy
*
* @return string
* @throws InvalidArgumentException
* If any of the keys in $keys are not a legal value a phpfastcacheInvalidArgumentException
* MUST be thrown.
*
*/
public function getItemsByTagsAsJsonString(array $tagNames, int $option = \JSON_THROW_ON_ERROR, int $depth = 512, int $strategy = self::TAG_STRATEGY_ONE): string;
/**
* Removes the item from the pool by tag.
*
* @param string $tagName
* The tag for which to delete
*
* @param int $strategy
*
* @return bool
* True if the item was successfully removed. False if there was an error.
* @throws InvalidArgumentException
* If the $key string is not a legal value a phpfastcacheInvalidArgumentException
* MUST be thrown.
*
*/
public function deleteItemsByTag(string $tagName, int $strategy = self::TAG_STRATEGY_ONE): bool;
/**
* Removes the item from the pool by one of multiple tag names.
*
* @param string[] $tagNames
* The tag for which to delete
*
* @param int $strategy
*
* @return bool
* True if the items were successfully removed. False if there was an error.
* @throws InvalidArgumentException
* If the $key string is not a legal value a phpfastcacheInvalidArgumentException
* MUST be thrown.
*
*/
public function deleteItemsByTags(array $tagNames, int $strategy = self::TAG_STRATEGY_ONE): bool;
/**
* Increment the items from the pool by tag.
*
* @param string $tagName
* The tag for which to increment
*
* @param int $step
*
* @param int $strategy
*
* @return bool
* True if the item was successfully incremented. False if there was an error.
* @throws InvalidArgumentException
* If the $key string is not a legal value a phpfastcacheInvalidArgumentException
* MUST be thrown.
*
*/
public function incrementItemsByTag(string $tagName, int $step = 1, int $strategy = self::TAG_STRATEGY_ONE): bool;
/**
* Increment the items from the pool by one of multiple tag names.
*
* @param string[] $tagNames
* The tag for which to increment
*
* @param int $step
*
* @param int $strategy
*
* @return bool
* True if the items were successfully incremented. False if there was an error.
* @throws InvalidArgumentException
* If the $key string is not a legal value a phpfastcacheInvalidArgumentException
* MUST be thrown.
*
*/
public function incrementItemsByTags(array $tagNames, int $step = 1, int $strategy = self::TAG_STRATEGY_ONE): bool;
/**
* Decrement the items from the pool by tag.
*
* @param string $tagName
* The tag for which to decrement
*
* @param int $step
*
* @param int $strategy
*
* @return bool
* True if the item was successfully decremented. False if there was an error.
* @throws InvalidArgumentException
* If the $key string is not a legal value a phpfastcacheInvalidArgumentException
* MUST be thrown.
*
*/
public function decrementItemsByTag(string $tagName, int $step = 1, int $strategy = self::TAG_STRATEGY_ONE): bool;
/**
* Decrement the items from the pool by one of multiple tag names.
*
* @param string[] $tagNames
* The tag for which to decrement
*
* @param int $step
*
* @param int $strategy
*
* @return bool
* True if the item was successfully decremented. False if there was an error.
* @throws InvalidArgumentException
* If the $key string is not a legal value a phpfastcacheInvalidArgumentException
* MUST be thrown.
*
*/
public function decrementItemsByTags(array $tagNames, int $step = 1, int $strategy = self::TAG_STRATEGY_ONE): bool;
/**
* Decrement the items from the pool by tag.
*
* @param string $tagName
* The tag for which to append
*
* @param array<mixed>|string $data
*
* @param int $strategy
*
* @return bool
* True if the item was successfully appended. False if there was an error.
* @throws InvalidArgumentException
* If the $key string is not a legal value a phpfastcacheInvalidArgumentException
* MUST be thrown.
*
*/
public function appendItemsByTag(string $tagName, array|string $data, int $strategy = self::TAG_STRATEGY_ONE): bool;
/**
* Append the items from the pool by one of multiple tag names.
*
* @param string[] $tagNames
* The tag for which to append
*
* @param array<mixed>|string $data
*
* @param int $strategy
*
* @return bool
* True if the items were successfully appended. False if there was an error.
* @throws InvalidArgumentException
* If the $key string is not a legal value a phpfastcacheInvalidArgumentException
* MUST be thrown.
*
*/
public function appendItemsByTags(array $tagNames, array|string $data, int $strategy = self::TAG_STRATEGY_ONE): bool;
/**
* Prepend the items from the pool by tag.
*
* @param string $tagName
* The tag for which to prepend
*
* @param array<mixed>|string $data
*
* @param int $strategy
*
* @return bool
* True if the item was successfully prepended. False if there was an error.
* @throws InvalidArgumentException
* If the $key string is not a legal value a phpfastcacheInvalidArgumentException
* MUST be thrown.
*
*/
public function prependItemsByTag(string $tagName, array|string $data, int $strategy = self::TAG_STRATEGY_ONE): bool;
/**
* Prepend the items from the pool by one of multiple tag names.
*
* @param string[] $tagNames
* The tag for which to prepend
*
* @param array<mixed>|string $data
*
* @param int $strategy
*
* @return bool
* True if the item was successfully prepended. False if there was an error.
* @throws InvalidArgumentException
* If the $key string is not a legal value a phpfastcacheInvalidArgumentException
* MUST be thrown.
*
*/
public function prependItemsByTags(array $tagNames, array|string $data, int $strategy = self::TAG_STRATEGY_ONE): bool;
}
@@ -0,0 +1,471 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Core\Pool;
use DateTime;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Exceptions\PhpfastcacheCoreException;
use Phpfastcache\Exceptions\PhpfastcacheDriverException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Psr\Cache\CacheItemInterface;
/**
* Trait TaggableCacheItemPoolTrait
* @package Phpfastcache\Core\Pool
*/
trait TaggableCacheItemPoolTrait
{
use ExtendedCacheItemPoolTrait;
/**
* @inheritDoc
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
public function getItemsByTagsAsJsonString(
array $tagNames,
int $option = \JSON_THROW_ON_ERROR,
int $depth = 512,
int $strategy = TaggableCacheItemPoolInterface::TAG_STRATEGY_ONE
): string {
return \json_encode(
\array_map(
static fn(CacheItemInterface $item) => $item->get(),
\array_values($this->getItemsByTags($tagNames, $strategy))
),
$option,
$depth,
);
}
/**
* @inheritDoc
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
public function getItemsByTags(array $tagNames, int $strategy = TaggableCacheItemPoolInterface::TAG_STRATEGY_ONE): array
{
$items = [];
foreach (\array_unique($tagNames) as $tagName) {
$items[] = $this->fetchItemsByTagFromBackend($tagName);
}
$items = \array_merge([], ...$items);
switch ($strategy) {
case TaggableCacheItemPoolInterface::TAG_STRATEGY_ALL:
foreach ($items as $key => $item) {
if (\array_diff($tagNames, $item->getTags())) {
unset($items[$key]);
}
}
break;
case TaggableCacheItemPoolInterface::TAG_STRATEGY_ONLY:
foreach ($items as $key => $item) {
if (\array_diff($tagNames, $item->getTags()) || \array_diff($item->getTags(), $tagNames)) {
unset($items[$key]);
}
}
break;
}
return $items;
}
/**
* @param string $tagName
* @return ExtendedCacheItemInterface[]
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
protected function fetchItemsByTagFromBackend(string $tagName): array
{
$driverResponse = $this->getItem($this->getTagKey($tagName));
if ($driverResponse->isHit()) {
$tagsItems = (array)$driverResponse->get();
/**
* getItems() may provide expired item(s)
* themselves provided by a cache of item
* keys based stored the tag item.
* Therefore, we pass a filter callback
* to remove the expired Item(s) provided by
* the item keys passed through getItems()
*
* #headache
*/
return \array_filter(
$this->getItems(\array_unique(\array_keys($tagsItems))),
static fn (ExtendedCacheItemInterface $item) => $item->isHit(),
);
}
return [];
}
/**
* @param string $key
* @return string
*/
protected function getTagKey(string $key): string
{
return TaggableCacheItemPoolInterface::DRIVER_TAGS_KEY_PREFIX . $key;
}
/**
* @inheritDoc
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
* @throws PhpfastcacheDriverException
*/
public function deleteItemsByTags(array $tagNames, int $strategy = TaggableCacheItemPoolInterface::TAG_STRATEGY_ONE): bool
{
$return = true;
foreach ($this->getItemsByTags($tagNames, $strategy) as $item) {
$result = $this->deleteItem($item->getKey());
if ($result !== true) {
$return = $result;
}
}
return $return;
}
/**
* @inheritDoc
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
* @throws PhpfastcacheDriverException
*/
public function deleteItemsByTag(string $tagName, int $strategy = TaggableCacheItemPoolInterface::TAG_STRATEGY_ONE): bool
{
$return = true;
foreach ($this->getItemsByTag($tagName, $strategy) as $item) {
$result = $this->deleteItem($item->getKey());
if ($result !== true) {
$return = $result;
}
}
return $return;
}
/**
* @inheritDoc
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
public function getItemsByTag(string $tagName, int $strategy = TaggableCacheItemPoolInterface::TAG_STRATEGY_ONE): array
{
$items = $this->fetchItemsByTagFromBackend($tagName);
if ($strategy === TaggableCacheItemPoolInterface::TAG_STRATEGY_ONLY) {
foreach ($items as $key => $item) {
if (\array_diff($item->getTags(), [$tagName])) {
unset($items[$key]);
}
}
}
return $items;
}
/**
* @inheritDoc
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
* @throws \ReflectionException
*/
public function incrementItemsByTags(array $tagNames, int $step = 1, int $strategy = TaggableCacheItemPoolInterface::TAG_STRATEGY_ONE): bool
{
$return = true;
foreach ($tagNames as $tagName) {
$result = $this->incrementItemsByTag($tagName, $step, $strategy);
if ($result !== true) {
$return = $result;
}
}
return $return;
}
/**
* @inheritDoc
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
* @throws \ReflectionException
*/
public function incrementItemsByTag(string $tagName, int $step = 1, int $strategy = TaggableCacheItemPoolInterface::TAG_STRATEGY_ONE): bool
{
foreach ($this->getItemsByTag($tagName, $strategy) as $item) {
$item->increment($step);
$this->saveDeferred($item);
}
return $this->commit();
}
/**
* @inheritDoc
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
* @throws \ReflectionException
*/
public function decrementItemsByTags(array $tagNames, int $step = 1, int $strategy = TaggableCacheItemPoolInterface::TAG_STRATEGY_ONE): bool
{
$return = true;
foreach ($tagNames as $tagName) {
$result = $this->decrementItemsByTag($tagName, $step, $strategy);
if ($result !== true) {
$return = $result;
}
}
return $return;
}
/**
* @inheritDoc
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
* @throws \ReflectionException
*/
public function decrementItemsByTag(string $tagName, int $step = 1, int $strategy = TaggableCacheItemPoolInterface::TAG_STRATEGY_ONE): bool
{
foreach ($this->getItemsByTag($tagName, $strategy) as $item) {
$item->decrement($step);
$this->saveDeferred($item);
}
return $this->commit();
}
/**
* @inheritDoc
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
* @throws \ReflectionException
*/
public function appendItemsByTags(array $tagNames, array|string $data, int $strategy = TaggableCacheItemPoolInterface::TAG_STRATEGY_ONE): bool
{
$return = true;
foreach ($tagNames as $tagName) {
$result = $this->appendItemsByTag($tagName, $data, $strategy);
if ($result !== true) {
$return = $result;
}
}
return $return;
}
/**
* @inheritDoc
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
* @throws \ReflectionException
*/
public function appendItemsByTag(string $tagName, array|string $data, int $strategy = TaggableCacheItemPoolInterface::TAG_STRATEGY_ONE): bool
{
foreach ($this->getItemsByTag($tagName, $strategy) as $item) {
$item->append($data);
$this->saveDeferred($item);
}
return $this->commit();
}
/**
* @inheritDoc
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
* @throws \ReflectionException
*/
public function prependItemsByTags(array $tagNames, array|string $data, int $strategy = TaggableCacheItemPoolInterface::TAG_STRATEGY_ONE): bool
{
$return = true;
foreach ($tagNames as $tagName) {
$result = $this->prependItemsByTag($tagName, $data, $strategy);
if ($result !== true) {
$return = $result;
}
}
return $return;
}
/**
* @inheritDoc
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
* @throws \ReflectionException
*/
public function prependItemsByTag(string $tagName, array|string $data, int $strategy = TaggableCacheItemPoolInterface::TAG_STRATEGY_ONE): bool
{
foreach ($this->getItemsByTag($tagName, $strategy) as $item) {
$item->prepend($data);
$this->saveDeferred($item);
}
return $this->commit();
}
/**
* @param array<mixed> $wrapper
* @return string[]
*/
protected function driverUnwrapTags(array $wrapper): array
{
return $wrapper[TaggableCacheItemPoolInterface::DRIVER_TAGS_WRAPPER_INDEX];
}
/**
* @param ExtendedCacheItemInterface $item
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
protected function cleanItemTags(ExtendedCacheItemInterface $item): void
{
if (!empty($item->getTags()) || !empty($item->getRemovedTags())) {
$this->driverWriteTags($item->removeTags($item->getTags()));
}
}
/**
* @param ExtendedCacheItemInterface $item
* @return bool
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
* @throws PhpfastcacheDriverException
*/
protected function driverWriteTags(ExtendedCacheItemInterface $item): bool
{
/**
* Do not attempt to write tags
* on tags item, it can lead
* to an infinite recursive calls
*/
if (str_starts_with($item->getKey(), TaggableCacheItemPoolInterface::DRIVER_TAGS_KEY_PREFIX)) {
throw new PhpfastcacheLogicException('Trying to set tag(s) to an Tag item index: ' . $item->getKey());
}
if (!$item->getTags() && !$item->getRemovedTags()) {
return true;
}
/**
* @var $tagsItems ExtendedCacheItemInterface[]
*/
$tagsItems = $this->getItems($this->getTagKeys($item->getTags()));
foreach ($tagsItems as $tagsItem) {
$data = $tagsItem->get();
$expTimestamp = $item->getExpirationDate()->getTimestamp();
/**
* Using the key will
* avoid to use array_unique
* that has slow performances
*/
$data = \array_merge((array)$data, [$item->getKey() => $expTimestamp]);
$tagsItem->set($data);
/**
* Recalculate the expiration date
*
* If the $tagsItem does not have
* any cache item references left
* then remove it from tagsItems index
*/
$tagsItem->expiresAt((new DateTime())->setTimestamp(max($data)));
$this->driverWrite($tagsItem);
$tagsItem->setHit(true);
}
/**
* Also update removed tags to
* keep the index up to date
*/
$tagsItems = $this->getItems($this->getTagKeys($item->getRemovedTags()));
foreach ($tagsItems as $tagsItem) {
$data = (array)$tagsItem->get();
unset($data[$item->getKey()]);
$tagsItem->set($data);
/**
* Recalculate the expiration date
*
* If the $tagsItem does not have
* any cache item references left
* then remove it from tagsItems index
*/
if (\count($data)) {
$tagsItem->expiresAt((new DateTime())->setTimestamp(max($data)));
$this->driverWrite($tagsItem);
$tagsItem->setHit(true);
} else {
$this->deleteItem($tagsItem->getKey());
}
}
return true;
}
/**
* @param array<string> $keys
* @return array<string>
*/
protected function getTagKeys(array $keys): array
{
return \array_map(
fn (string $key) => $this->getTagKey($key),
$keys
);
}
}
@@ -0,0 +1,23 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Apcu;
use Phpfastcache\Config\ConfigurationOption;
class Config extends ConfigurationOption
{
}
@@ -0,0 +1,118 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Apcu;
use DateTime;
use Phpfastcache\Cluster\AggregatablePoolInterface;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Config\ConfigurationOptionInterface;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Entities\DriverStatistic;
use Phpfastcache\Util\SapiDetector;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
/**
* Class Driver
* @method Config getConfig()
*/
class Driver implements AggregatablePoolInterface
{
use TaggableCacheItemPoolTrait;
/**
* @return bool
*/
public function driverCheck(): bool
{
return extension_loaded('apcu') && ((ini_get('apc.enabled') && SapiDetector::isWebScript()) || (ini_get('apc.enable_cli') && SapiDetector::isCliScript()));
}
/**
* @return DriverStatistic
*/
public function getStats(): DriverStatistic
{
$stats = (array)apcu_cache_info();
$date = (new DateTime())->setTimestamp($stats['start_time']);
return (new DriverStatistic())
->setData(implode(', ', array_keys($this->itemInstances)))
->setInfo(
sprintf(
"The APCU cache is up since %s, and have %d item(s) in cache.\n For more information see RawData.",
$date->format(DATE_RFC2822),
$stats['num_entries']
)
)
->setRawData($stats)
->setSize((int)$stats['mem_size']);
}
/**
* @return bool
*/
protected function driverConnect(): bool
{
return true;
}
/**
* @param ExtendedCacheItemInterface $item
* @return bool
* @throws PhpfastcacheInvalidArgumentException
*/
protected function driverWrite(ExtendedCacheItemInterface $item): bool
{
return (bool)apcu_store($item->getKey(), $this->driverPreWrap($item), $item->getTtl());
}
/**
* @param ExtendedCacheItemInterface $item
* @return ?array<string, mixed>
*/
protected function driverRead(ExtendedCacheItemInterface $item): ?array
{
$data = apcu_fetch($item->getKey(), $success);
if ($success === false || !\is_array($data)) {
return null;
}
return $data;
}
/**
* @param string $key
* @param string $encodedKey
* @return bool
*/
protected function driverDelete(string $key, string $encodedKey): bool
{
return (bool)apcu_delete($key);
}
/**
* @return bool
*/
protected function driverClear(): bool
{
return @apcu_clear_cache();
}
}
@@ -0,0 +1,30 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Apcu;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Item\TaggableCacheItemTrait;
class Item implements ExtendedCacheItemInterface
{
use TaggableCacheItemTrait;
protected function getDriverClass(): string
{
return Driver::class;
}
}
@@ -0,0 +1,172 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Cassandra;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
class Config extends ConfigurationOption
{
protected string $host = '127.0.0.1';
protected int $port = 9042;
protected int $timeout = 2;
protected string $username = '';
protected string $password = '';
protected bool $sslEnabled = false;
protected bool $sslVerify = false;
protected bool $useLegacyExecutionOptions = false;
public function getHost(): string
{
return $this->host;
}
/**
* @param string $host
* @throws PhpfastcacheLogicException
*/
public function setHost(string $host): static
{
return $this->setProperty('host', $host);
}
/**
* @return int
*/
public function getPort(): int
{
return $this->port;
}
/**
* @param int $port
* @throws PhpfastcacheLogicException
*/
public function setPort(int $port): static
{
return $this->setProperty('port', $port);
}
/**
* @return int
*/
public function getTimeout(): int
{
return $this->timeout;
}
/**
* @param int $timeout
* @throws PhpfastcacheLogicException
*/
public function setTimeout(int $timeout): static
{
return $this->setProperty('timeout', $timeout);
}
/**
* @return string
*/
public function getUsername(): string
{
return $this->username;
}
/**
* @param string $username
* @throws PhpfastcacheLogicException
*/
public function setUsername(string $username): static
{
return $this->setProperty('username', $username);
}
/**
* @return string
*/
public function getPassword(): string
{
return $this->password;
}
/**
* @param string $password
* @throws PhpfastcacheLogicException
*/
public function setPassword(string $password): static
{
return $this->setProperty('password', $password);
}
/**
* @return bool
*/
public function isSslEnabled(): bool
{
return $this->sslEnabled;
}
/**
* @param bool $sslEnabled
* @throws PhpfastcacheLogicException
*/
public function setSslEnabled(bool $sslEnabled): static
{
return $this->setProperty('sslEnabled', $sslEnabled);
}
/**
* @return bool
*/
public function isSslVerify(): bool
{
return $this->sslVerify;
}
/**
* @param bool $sslVerify
* @throws PhpfastcacheLogicException
*/
public function setSslVerify(bool $sslVerify): static
{
return $this->setProperty('sslVerify', $sslVerify);
}
/**
* @return bool
*/
public function isUseLegacyExecutionOptions(): bool
{
return $this->useLegacyExecutionOptions;
}
/**
* @param bool $useLegacyExecutionOptions
* @throws PhpfastcacheLogicException
*/
public function setUseLegacyExecutionOptions(bool $useLegacyExecutionOptions): static
{
return $this->setProperty('useLegacyExecutionOptions', $useLegacyExecutionOptions);
}
}
@@ -0,0 +1,318 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Cassandra;
use Cassandra;
use Cassandra\Exception;
use Cassandra\Exception\InvalidArgumentException;
use Cassandra\Session as CassandraSession;
use DateTime;
use Phpfastcache\Cluster\AggregatablePoolInterface;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait;
use Phpfastcache\Entities\DriverStatistic;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
/**
* Class Driver
* @property CassandraSession|null $instance Instance of driver service
* @method Config getConfig()
*/
class Driver implements AggregatablePoolInterface
{
use TaggableCacheItemPoolTrait;
protected const CASSANDRA_KEY_SPACE = 'phpfastcache';
protected const CASSANDRA_TABLE = 'cacheItems';
/**
* @return bool
*/
public function driverCheck(): bool
{
return extension_loaded('Cassandra') && class_exists(Cassandra::class);
}
/**
* @return bool
* @throws PhpfastcacheLogicException
* @throws Exception
*/
protected function driverConnect(): bool
{
$clientConfig = $this->getConfig();
$clusterBuilder = Cassandra::cluster()
->withContactPoints($clientConfig->getHost())
->withPort($clientConfig->getPort());
if (!empty($clientConfig->isSslEnabled())) {
$sslBuilder = Cassandra::ssl();
if (!empty($clientConfig->isSslVerify())) {
$sslBuilder->withVerifyFlags(Cassandra::VERIFY_PEER_CERT);
} else {
$sslBuilder->withVerifyFlags(Cassandra::VERIFY_NONE);
}
$clusterBuilder->withSSL($sslBuilder->build());
}
$clusterBuilder->withConnectTimeout($clientConfig->getTimeout());
if ($clientConfig->getUsername()) {
$clusterBuilder->withCredentials($clientConfig->getUsername(), $clientConfig->getPassword());
}
$this->instance = $clusterBuilder->build()->connect('');
/**
* In case of emergency:
* $this->instance->execute(
* new Cassandra\SimpleStatement(\sprintf("DROP KEYSPACE %s;", self::CASSANDRA_KEY_SPACE))
* );
*/
$this->instance->execute(
new Cassandra\SimpleStatement(
sprintf(
"CREATE KEYSPACE IF NOT EXISTS %s WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };",
self::CASSANDRA_KEY_SPACE
)
),
[]
);
$this->instance->execute(new Cassandra\SimpleStatement(sprintf('USE %s;', self::CASSANDRA_KEY_SPACE)), []);
$this->instance->execute(
new Cassandra\SimpleStatement(
sprintf(
'
CREATE TABLE IF NOT EXISTS %s (
cache_uuid uuid,
cache_id varchar,
cache_data text,
cache_creation_date timestamp,
cache_expiration_date timestamp,
cache_length int,
PRIMARY KEY (cache_id)
);',
self::CASSANDRA_TABLE
)
),
[]
);
return true;
}
/**
* @param ExtendedCacheItemInterface $item
* @return ?array<string, mixed>
*/
protected function driverRead(ExtendedCacheItemInterface $item): ?array
{
try {
$options = $this->getCompatibleExecutionOptionsArgument(
[
'arguments' => ['cache_id' => $item->getKey()],
'page_size' => 1,
]
);
$query = sprintf(
'SELECT cache_data FROM %s.%s WHERE cache_id = :cache_id;',
self::CASSANDRA_KEY_SPACE,
self::CASSANDRA_TABLE
);
$results = $this->instance->execute(new Cassandra\SimpleStatement($query), $options);
if ($results instanceof Cassandra\Rows && $results->count() === 1) {
return $this->decode($results->first()['cache_data']) ?: null;
}
return null;
} catch (Exception $e) {
return null;
}
}
/**
* @param ExtendedCacheItemInterface $item
* @return bool
* @throws PhpfastcacheInvalidArgumentException
*/
protected function driverWrite(ExtendedCacheItemInterface $item): bool
{
try {
$cacheData = $this->encode($this->driverPreWrap($item));
$options = $this->getCompatibleExecutionOptionsArgument(
[
'arguments' => [
'cache_uuid' => new Cassandra\Uuid(''),
'cache_id' => $item->getKey(),
'cache_data' => $cacheData,
'cache_creation_date' => new Cassandra\Timestamp((new DateTime())->getTimestamp(), 0),
'cache_expiration_date' => new Cassandra\Timestamp($item->getExpirationDate()->getTimestamp(), 0),
'cache_length' => strlen($cacheData),
],
'consistency' => Cassandra::CONSISTENCY_ALL,
'serial_consistency' => Cassandra::CONSISTENCY_SERIAL,
]
);
$query = sprintf(
'INSERT INTO %s.%s
(
cache_uuid,
cache_id,
cache_data,
cache_creation_date,
cache_expiration_date,
cache_length
)
VALUES (:cache_uuid, :cache_id, :cache_data, :cache_creation_date, :cache_expiration_date, :cache_length);
',
self::CASSANDRA_KEY_SPACE,
self::CASSANDRA_TABLE
);
$result = $this->instance->execute(new Cassandra\SimpleStatement($query), $options);
/**
* There's no real way atm
* to know if the item has
* been really upserted
*/
return $result instanceof Cassandra\Rows;
} catch (InvalidArgumentException $e) {
throw new PhpfastcacheInvalidArgumentException($e->getMessage(), 0, $e);
}
}
/**
* @param string $key
* @param string $encodedKey
* @return bool
*/
protected function driverDelete(string $key, string $encodedKey): bool
{
try {
$options = $this->getCompatibleExecutionOptionsArgument(
[
'arguments' => [
'cache_id' => $key,
],
]
);
$result = $this->instance->execute(
new Cassandra\SimpleStatement(
sprintf(
'DELETE FROM %s.%s WHERE cache_id = :cache_id;',
self::CASSANDRA_KEY_SPACE,
self::CASSANDRA_TABLE
)
),
$options
);
/**
* There's no real way atm
* to know if the item has
* been really deleted
*/
return $result instanceof Cassandra\Rows;
} catch (Exception $e) {
return false;
}
}
/**
* @return bool
*/
protected function driverClear(): bool
{
try {
$this->instance->execute(
new Cassandra\SimpleStatement(
sprintf(
'TRUNCATE %s.%s;',
self::CASSANDRA_KEY_SPACE,
self::CASSANDRA_TABLE
)
),
null
);
return true;
} catch (Exception) {
return false;
}
}
/**
* @return string
*/
public function getHelp(): string
{
return <<<HELP
<p>
To install the php Cassandra extension via Pecl:
<code>sudo pecl install cassandra</code>
More information on: https://github.com/datastax/php-driver
Please note that this repository only provide php stubs and C/C++ sources, it does NOT provide php client.
</p>
HELP;
}
/**
* @return DriverStatistic
* @throws Exception
*/
public function getStats(): DriverStatistic
{
$result = $this->instance->execute(
new Cassandra\SimpleStatement(
sprintf(
'SELECT SUM(cache_length) as cache_size FROM %s.%s',
self::CASSANDRA_KEY_SPACE,
self::CASSANDRA_TABLE
)
),
null
);
return (new DriverStatistic())
->setSize($result->first()['cache_size'])
->setRawData([])
->setData(implode(', ', array_keys($this->itemInstances)))
->setInfo('The cache size represents only the cache data itself without counting data structures associated to the cache entries.');
}
/**
* @param array<string, mixed> $options
* @return array<string, mixed>|Cassandra\ExecutionOptions
*/
protected function getCompatibleExecutionOptionsArgument(array $options): mixed
{
if ($this->getConfig()->isUseLegacyExecutionOptions()) {
return new Cassandra\ExecutionOptions($options);
}
return $options;
}
}
@@ -0,0 +1,30 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Cassandra;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Item\TaggableCacheItemTrait;
class Item implements ExtendedCacheItemInterface
{
use TaggableCacheItemTrait;
protected function getDriverClass(): string
{
return Driver::class;
}
}
@@ -0,0 +1,157 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Couchbasev3;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
class Config extends ConfigurationOption
{
protected const DEFAULT_VALUE = '_default';
protected string $host = '127.0.0.1';
protected int $port = 8091;
// SSL: 18091
protected string $username = '';
protected string $password = '';
protected string $bucketName = self::DEFAULT_VALUE;
protected string $scopeName = self::DEFAULT_VALUE;
protected string $collectionName = self::DEFAULT_VALUE;
public function getHost(): string
{
return $this->host;
}
/**
* @param string $host
* @return Config
* @throws PhpfastcacheLogicException
*/
public function setHost(string $host): Config
{
return $this->setProperty('host', $host);
}
/**
* @return int
*/
public function getPort()
{
return $this->port;
}
/**
* @param int $port
* @return Config
* @throws PhpfastcacheLogicException
*/
public function setPort(int $port): Config
{
return $this->setProperty('port', $port);
}
/**
* @return string
*/
public function getUsername(): string
{
return $this->username;
}
/**
* @param string $username
* @return Config
* @throws PhpfastcacheLogicException
*/
public function setUsername(string $username): Config
{
return $this->setProperty('username', $username);
}
/**
* @return string
*/
public function getPassword(): string
{
return $this->password;
}
/**
* @param string $password
* @return Config
* @throws PhpfastcacheLogicException
*/
public function setPassword(string $password): Config
{
return $this->setProperty('password', $password);
}
/**
* @return string
*/
public function getBucketName(): string
{
return $this->bucketName;
}
/**
* @param string $bucketName
* @return Config
* @throws PhpfastcacheLogicException
*/
public function setBucketName(string $bucketName): Config
{
return $this->setProperty('bucketName', $bucketName);
}
/**
* @return string
*/
public function getScopeName(): string
{
return $this->scopeName;
}
/**
* @param string $scopeName
* @return Config
* @throws PhpfastcacheLogicException
*/
public function setScopeName(string $scopeName): Config
{
return $this->setProperty('scopeName', $scopeName);
}
/**
* @return string
*/
public function getCollectionName(): string
{
return $this->collectionName;
}
/**
* @param string $collectionName
* @return Config
* @throws PhpfastcacheLogicException
*/
public function setCollectionName(string $collectionName): Config
{
return $this->setProperty('collectionName', $collectionName);
}
}
@@ -0,0 +1,324 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Couchbasev3;
use Couchbase\BaseException as CouchbaseException;
use Couchbase\Bucket as CouchbaseBucket;
use Couchbase\Cluster;
use Couchbase\ClusterOptions;
use Couchbase\Collection;
use Couchbase\DocumentNotFoundException;
use Couchbase\GetResult;
use Couchbase\Scope;
use Couchbase\UpsertOptions;
use DateTimeInterface;
use Phpfastcache\Cluster\AggregatablePoolInterface;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait;
use Phpfastcache\Entities\DriverStatistic;
use Phpfastcache\Event\EventManagerInterface;
use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Phpfastcache\Exceptions\PhpfastcacheUnsupportedException;
use Phpfastcache\Exceptions\PhpfastcacheUnsupportedMethodException;
/**
* @property Cluster $instance Instance of driver service
* @method Config getConfig()
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Driver implements AggregatablePoolInterface
{
use TaggableCacheItemPoolTrait;
protected Scope $scope;
protected Collection $collection;
protected CouchbaseBucket $bucketInstance;
/**
* @return bool
*/
public function driverCheck(): bool
{
return extension_loaded('couchbase');
}
/**
* @return bool
* @throws PhpfastcacheDriverCheckException
*/
protected function driverConnect(): bool
{
if (!\class_exists(ClusterOptions::class)) {
throw new PhpfastcacheDriverCheckException('You are using the Couchbase PHP SDK 2.x which is no longer supported in Phpfastcache v9');
}
$connectionString = "couchbase://{$this->getConfig()->getHost()}:{$this->getConfig()->getPort()}";
$options = new ClusterOptions();
$options->credentials($this->getConfig()->getUsername(), $this->getConfig()->getPassword());
$this->instance = new Cluster($connectionString, $options);
$this->setBucket($this->instance->bucket($this->getConfig()->getBucketName()));
$this->setScope($this->getBucket()->scope($this->getConfig()->getScopeName()));
$this->setCollection($this->getScope()->collection($this->getConfig()->getCollectionName()));
return true;
}
/**
* @param ExtendedCacheItemInterface $item
* @return ?array<string, mixed>
*/
protected function driverRead(ExtendedCacheItemInterface $item): ?array
{
try {
/**
* CouchbaseBucket::get() returns a GetResult interface
*/
return $this->decodeDocument((array)$this->getCollection()->get($item->getEncodedKey())->content());
} catch (DocumentNotFoundException) {
return null;
}
}
/**
* @param ExtendedCacheItemInterface $item
* @return array<array<string, mixed>>
*/
protected function driverReadMultiple(ExtendedCacheItemInterface ...$items): array
{
try {
$results = [];
/**
* CouchbaseBucket::get() returns a GetResult interface
*/
/** @var GetResult $document */
foreach ($this->getCollection()->getMulti($this->getKeys($items, true)) as $document) {
$content = $document->content();
if ($content) {
$decodedDocument = $this->decodeDocument($content);
$results[$decodedDocument[ExtendedCacheItemPoolInterface::DRIVER_KEY_WRAPPER_INDEX]] = $this->decodeDocument($content);
}
}
return $results;
} catch (DocumentNotFoundException) {
return [];
}
}
/**
* @param ExtendedCacheItemInterface $item
* @return bool
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
protected function driverWrite(ExtendedCacheItemInterface $item): bool
{
try {
$this->getCollection()->upsert(
$item->getEncodedKey(),
$this->encodeDocument($this->driverPreWrap($item)),
(new UpsertOptions())->expiry($item->getTtl())
);
return true;
} catch (CouchbaseException) {
return false;
}
}
/**
* @param string $key
* @param string $encodedKey
* @return bool
*/
protected function driverDelete(string $key, string $encodedKey): bool
{
try {
return $this->getCollection()->remove($encodedKey)->mutationToken() !== null;
} catch (DocumentNotFoundException) {
return true;
} catch (CouchbaseException) {
return false;
}
}
/**
* @param string[] $keys
* @return bool
*/
protected function driverDeleteMultiple(array $keys): bool
{
try {
$this->getCollection()->removeMulti(array_map(fn(string $key) => $this->getEncodedKey($key), $keys));
return true;
} catch (CouchbaseException) {
return false;
}
}
/**
* @return bool
* @throws PhpfastcacheUnsupportedMethodException
*/
protected function driverClear(): bool
{
if (!$this->instance->buckets()->getBucket($this->getConfig()->getBucketName())->flushEnabled()) {
$this->instance->buckets()->getBucket($this->getConfig()->getBucketName())->enableFlush(true);
/** @phpstan-ignore-next-line */
if (!$this->instance->buckets()->getBucket($this->getConfig()->getBucketName())->flushEnabled()) {
throw new PhpfastcacheUnsupportedMethodException(
'Flushing operation is not enabled on your Bucket. See https://docs.couchbase.com/server/current/manage/manage-buckets/flush-bucket.html'
);
}
}
$this->instance->buckets()->flush($this->getConfig()->getBucketName());
return true;
}
/**
* @return DriverStatistic
* @throws \Exception
*/
public function getStats(): DriverStatistic
{
/**
* Between SDK 2 and 3 we lost a lot of useful information :(
* @see https://docs.couchbase.com/java-sdk/current/project-docs/migrating-sdk-code-to-3.n.html#management-apis
*/
$info = $this->getBucket()->diagnostics(\bin2hex(\random_bytes(16)));
return (new DriverStatistic())
->setSize(0)
->setRawData($info)
->setData(implode(', ', array_keys($this->itemInstances)))
->setInfo($info['sdk'] . "\n For more information see RawData.");
}
/**
* @return Collection
*/
public function getCollection(): Collection
{
return $this->collection;
}
/**
* @param Collection $collection
* @return Driver
*/
public function setCollection(Collection $collection): Driver
{
$this->collection = $collection;
return $this;
}
/**
* @return Scope
*/
public function getScope(): Scope
{
return $this->scope;
}
/**
* @param Scope $scope
* @return Driver
*/
public function setScope(Scope $scope): Driver
{
$this->scope = $scope;
return $this;
}
/**
* @return CouchbaseBucket
*/
protected function getBucket(): CouchbaseBucket
{
return $this->bucketInstance;
}
/**
* @param CouchbaseBucket $couchbaseBucket
*/
protected function setBucket(CouchbaseBucket $couchbaseBucket): void
{
$this->bucketInstance = $couchbaseBucket;
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function encodeDocument(array $data): array
{
$data[ExtendedCacheItemPoolInterface::DRIVER_DATA_WRAPPER_INDEX] = $this->encode($data[ExtendedCacheItemPoolInterface::DRIVER_DATA_WRAPPER_INDEX]);
$data[ExtendedCacheItemPoolInterface::DRIVER_EDATE_WRAPPER_INDEX] = $data[ExtendedCacheItemPoolInterface::DRIVER_EDATE_WRAPPER_INDEX]
->format(DateTimeInterface::ATOM);
if ($this->getConfig()->isItemDetailedDate()) {
$data[ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX] = $data[ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX]
->format(\DateTimeInterface::ATOM);
$data[ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX] = $data[ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX]
->format(\DateTimeInterface::ATOM);
}
return $data;
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function decodeDocument(array $data): array
{
$data[ExtendedCacheItemPoolInterface::DRIVER_DATA_WRAPPER_INDEX] = $this->unserialize($data[ExtendedCacheItemPoolInterface::DRIVER_DATA_WRAPPER_INDEX]);
$data[ExtendedCacheItemPoolInterface::DRIVER_EDATE_WRAPPER_INDEX] = \DateTime::createFromFormat(
\DateTimeInterface::ATOM,
$data[ExtendedCacheItemPoolInterface::DRIVER_EDATE_WRAPPER_INDEX]
);
if ($this->getConfig()->isItemDetailedDate()) {
$data[ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX] = \DateTime::createFromFormat(
\DateTimeInterface::ATOM,
$data[ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX]
);
$data[ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX] = \DateTime::createFromFormat(
\DateTimeInterface::ATOM,
$data[ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX]
);
}
return $data;
}
}
@@ -0,0 +1,30 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Couchbasev3;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Item\TaggableCacheItemTrait;
class Item implements ExtendedCacheItemInterface
{
use TaggableCacheItemTrait;
protected function getDriverClass(): string
{
return Driver::class;
}
}
@@ -0,0 +1,23 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Devnull;
use Phpfastcache\Config\ConfigurationOption;
class Config extends ConfigurationOption
{
}
@@ -0,0 +1,101 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Devnull;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait;
use Phpfastcache\Entities\DriverStatistic;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @method Config getConfig()
*/
class Driver implements ExtendedCacheItemPoolInterface
{
use TaggableCacheItemPoolTrait;
/**
* @return bool
*/
public function driverCheck(): bool
{
return true;
}
/**
* @return DriverStatistic
*/
public function getStats(): DriverStatistic
{
$stat = new DriverStatistic();
$stat->setInfo('[Devnull] A void info string')
->setSize(0)
->setData(implode(', ', array_keys($this->itemInstances)))
->setRawData(null);
return $stat;
}
/**
* @param ExtendedCacheItemInterface $item
* @return mixed
* @throws PhpfastcacheInvalidArgumentException
*/
protected function driverWrite(ExtendedCacheItemInterface $item): bool
{
return true;
}
/**
* @param ExtendedCacheItemInterface $item
* @return ?array<string, mixed>
*/
protected function driverRead(CacheItemInterface $item): ?array
{
return null;
}
/**
* @param string $key
* @param string $encodedKey
* @return bool
*/
protected function driverDelete(string $key, string $encodedKey): bool
{
return true;
}
/**
* @return bool
*/
protected function driverClear(): bool
{
return true;
}
/**
* @return bool
*/
protected function driverConnect(): bool
{
return true;
}
}
@@ -0,0 +1,33 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Devnull;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Item\TaggableCacheItemTrait;
/**
* Class Item
*/
class Item implements ExtendedCacheItemInterface
{
use TaggableCacheItemTrait;
protected function getDriverClass(): string
{
return Driver::class;
}
}
@@ -0,0 +1,66 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Devrandom;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
class Config extends ConfigurationOption
{
protected int $dataLength = 16;
protected int $chanceOfRetrieval = 50;
/**
* @return int
*/
public function getDataLength(): int
{
return $this->dataLength;
}
/**
* @param int $dataLength
* @return Config
* @throws PhpfastcacheLogicException
*/
public function setDataLength(int $dataLength): Config
{
return $this->setProperty('dataLength', $dataLength);
}
/**
* @return int
*/
public function getChanceOfRetrieval(): int
{
return $this->chanceOfRetrieval;
}
/**
* @param int $chanceOfRetrieval
* @return Config
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
public function setChanceOfRetrieval(int $chanceOfRetrieval): Config
{
if ($chanceOfRetrieval < 0 || $chanceOfRetrieval > 100) {
throw new PhpfastcacheInvalidArgumentException('Chance of retrieval must be between 0 and 100');
}
return $this->setProperty('chanceOfRetrieval', $chanceOfRetrieval);
}
}
@@ -0,0 +1,114 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Devrandom;
use DateInterval;
use DateTime;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait;
use Phpfastcache\Entities\DriverStatistic;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Psr\Cache\CacheItemInterface;
/**
* @method Config getConfig()
*/
class Driver implements ExtendedCacheItemPoolInterface
{
use TaggableCacheItemPoolTrait;
/**
* @return bool
*/
public function driverCheck(): bool
{
return true;
}
/**
* @return DriverStatistic
*/
public function getStats(): DriverStatistic
{
$stat = new DriverStatistic();
$stat->setInfo('[Devrandom] A void info string')
->setSize(0)
->setData(implode(', ', array_keys($this->itemInstances)))
->setRawData(false);
return $stat;
}
/**
* @param ExtendedCacheItemInterface $item
* @return bool
* @throws PhpfastcacheInvalidArgumentException
*/
protected function driverWrite(ExtendedCacheItemInterface $item): bool
{
return true;
}
/**
* @param ExtendedCacheItemInterface $item
* @return ?array<string, mixed>
* @throws \Exception
*/
protected function driverRead(CacheItemInterface $item): ?array
{
$chanceOfRetrieval = $this->getConfig()->getChanceOfRetrieval();
$ttl = $this->getConfig()->getDefaultTtl();
if (\random_int(0, 100) < $chanceOfRetrieval) {
return [
self::DRIVER_DATA_WRAPPER_INDEX => \bin2hex(\random_bytes($this->getConfig()->getDataLength())),
self::DRIVER_TAGS_WRAPPER_INDEX => [],
self::DRIVER_EDATE_WRAPPER_INDEX => (new DateTime())->add(new DateInterval("PT{$ttl}S")),
];
}
return null;
}
/**
* @param string $key
* @param string $encodedKey
* @return bool
*/
protected function driverDelete(string $key, string $encodedKey): bool
{
return true;
}
/**
* @return bool
*/
protected function driverClear(): bool
{
return true;
}
/**
* @return bool
*/
protected function driverConnect(): bool
{
return true;
}
}
@@ -0,0 +1,30 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Devrandom;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Item\TaggableCacheItemTrait;
class Item implements ExtendedCacheItemInterface
{
use TaggableCacheItemTrait;
protected function getDriverClass(): string
{
return Driver::class;
}
}
@@ -0,0 +1,24 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Files;
use Phpfastcache\Config\IOConfigurationOptionInterface;
use Phpfastcache\Config\IOConfigurationOption;
class Config extends IOConfigurationOption implements IOConfigurationOptionInterface
{
}
@@ -0,0 +1,129 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Files;
use Exception;
use FilesystemIterator;
use Phpfastcache\Cluster\AggregatablePoolInterface;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Core\Pool\IO\IOHelperTrait;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheIOException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Phpfastcache\Util\Directory;
/**
* @method Config getConfig()
*
* Important NOTE:
* We are using getKey instead of getEncodedKey since this backend create filename that are
* managed by defaultFileNameHashFunction and not defaultKeyHashFunction
*/
class Driver implements AggregatablePoolInterface
{
use IOHelperTrait;
/**
* @return bool
* @throws PhpfastcacheIOException
* @throws PhpfastcacheInvalidArgumentException
*/
public function driverCheck(): bool
{
return is_writable($this->getPath()) || mkdir($concurrentDirectory = $this->getPath(), $this->getDefaultChmod(), true) || is_dir($concurrentDirectory);
}
/**
* @return bool
*/
protected function driverConnect(): bool
{
return true;
}
/**
* @param ExtendedCacheItemInterface $item
* @return ?array<string, mixed>
* @throws PhpfastcacheIOException
*/
protected function driverRead(ExtendedCacheItemInterface $item): ?array
{
$filePath = $this->getFilePath($item->getKey(), true);
try {
$content = $this->readFile($filePath);
} catch (PhpfastcacheIOException) {
return null;
}
return $this->decode($content);
}
/**
* @param ExtendedCacheItemInterface $item
* @return bool
* @throws PhpfastcacheIOException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
protected function driverWrite(ExtendedCacheItemInterface $item): bool
{
$filePath = $this->getFilePath($item->getKey());
$data = $this->encode($this->driverPreWrap($item));
try {
return $this->writeFile($filePath, $data, $this->getConfig()->isSecureFileManipulation());
} catch (Exception) {
return false;
}
}
/**
* @param string $key
* @param string $encodedKey
* @return bool
* @throws PhpfastcacheIOException
* @throws PhpfastcacheInvalidArgumentException
*/
protected function driverDelete(string $key, string $encodedKey): bool
{
$filePath = $this->getFilePath($key, true);
if (\file_exists($filePath) && @\unlink($filePath)) {
\clearstatcache(true, $filePath);
$dir = \dirname($filePath);
if (!(new FilesystemIterator($dir))->valid()) {
\rmdir($dir);
}
return true;
}
return false;
}
/**
* @return bool
* @throws \Phpfastcache\Exceptions\PhpfastcacheIOException
* @throws PhpfastcacheInvalidArgumentException
*/
protected function driverClear(): bool
{
return Directory::rrmdir($this->getPath(true));
}
}
@@ -0,0 +1,30 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Files;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Item\TaggableCacheItemTrait;
class Item implements ExtendedCacheItemInterface
{
use TaggableCacheItemTrait;
protected function getDriverClass(): string
{
return Driver::class;
}
}
@@ -0,0 +1,24 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Leveldb;
use Phpfastcache\Config\IOConfigurationOptionInterface;
use Phpfastcache\Config\IOConfigurationOption;
class Config extends IOConfigurationOption implements IOConfigurationOptionInterface
{
}
@@ -0,0 +1,135 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Leveldb;
use LevelDB as LeveldbClient;
use Phpfastcache\Cluster\AggregatablePoolInterface;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Core\Pool\IO\IOHelperTrait;
use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Exceptions\PhpfastcacheCoreException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
/**
* @property LeveldbClient|null $instance Instance of driver service
* @method Config getConfig()
*/
class Driver implements AggregatablePoolInterface
{
use IOHelperTrait;
protected const LEVELDB_FILENAME = '.database';
/**
* @return bool
*/
public function driverCheck(): bool
{
return extension_loaded('Leveldb');
}
/**
* Close connection on destruct
*/
public function __destruct()
{
if ($this->instance instanceof LeveldbClient) {
$this->instance->close();
$this->instance = null;
}
}
/**
* @param ExtendedCacheItemInterface $item
* @return ?array<string, mixed>
*/
protected function driverRead(ExtendedCacheItemInterface $item): ?array
{
$val = $this->instance->get($item->getKey());
if (!$val) {
return null;
}
return $this->decode($val);
}
/**
* @param ExtendedCacheItemInterface $item
* @return bool
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
protected function driverWrite(ExtendedCacheItemInterface $item): bool
{
return (bool)$this->instance->set($item->getKey(), $this->encode($this->driverPreWrap($item)));
}
/**
* @param string $key
* @param string $encodedKey
* @return bool
*/
protected function driverDelete(string $key, string $encodedKey): bool
{
return $this->instance->delete($key);
}
/**
* @return bool
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheLogicException
*/
protected function driverClear(): bool
{
if ($this->instance instanceof LeveldbClient) {
$this->instance->close();
$this->instance = null;
}
$result = LeveldbClient::destroy($this->getLeveldbFile());
$this->driverConnect();
return $result;
}
/**
* @return string
* @throws PhpfastcacheCoreException
*/
public function getLeveldbFile(): string
{
return $this->getPath() . '/' . self::LEVELDB_FILENAME;
}
/**
* @return bool
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheLogicException
*/
protected function driverConnect(): bool
{
if ($this->instance instanceof LeveldbClient) {
throw new PhpfastcacheLogicException('Already connected to Leveldb database');
}
$this->instance = new LeveldbClient($this->getLeveldbFile());
return true;
}
}
@@ -0,0 +1,30 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Leveldb;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Item\TaggableCacheItemTrait;
class Item implements ExtendedCacheItemInterface
{
use TaggableCacheItemTrait;
protected function getDriverClass(): string
{
return Driver::class;
}
}
@@ -0,0 +1,141 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Memcache;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Exceptions\PhpfastcacheDriverException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidConfigurationException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
class Config extends ConfigurationOption
{
/**
* @var array
*
* Multiple server can be added this way:
* $cfg->setServers([
* [
* // If you use an UNIX socket set the host and port to null
* 'host' => '127.0.0.1',
* //'path' => 'path/to/unix/socket',
* 'port' => 11211,
* ]
* ]);
*/
/** @var array<array<string, mixed>> */
protected array $servers = [];
protected string $host = '127.0.0.1';
protected int $port = 11211;
/**
* @return array<array<string, mixed>>
*/
public function getServers(): array
{
if (!count($this->servers)) {
return [
[
'host' => $this->getHost(),
'path' => $this->getPath(),
'port' => $this->getPort(),
],
];
}
return $this->servers;
}
/**
* @param array<array<string, mixed>> $servers
* @return self
* @throws PhpfastcacheInvalidConfigurationException
* @throws PhpfastcacheLogicException
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function setServers(array $servers): static
{
foreach ($servers as $server) {
if (\array_key_exists('saslUser', $server) || array_key_exists('saslPassword', $server)) {
throw new PhpfastcacheInvalidConfigurationException('Unlike Memcached, Memcache does not support SASL authentication');
}
if ($diff = array_diff(array_keys($server), ['host', 'port', 'path'])) {
throw new PhpfastcacheInvalidConfigurationException('Unknown keys for memcached server: ' . implode(', ', $diff));
}
if (!empty($server['host']) && !empty($server['path'])) {
throw new PhpfastcacheInvalidConfigurationException('Host and path cannot be simultaneous defined.');
}
if ((isset($server['host']) && !is_string($server['host'])) || (empty($server['path']) && empty($server['host']))) {
throw new PhpfastcacheInvalidConfigurationException('Host must be a valid string in "$server" configuration array if path is not defined');
}
if ((isset($server['path']) && !is_string($server['path'])) || (empty($server['host']) && empty($server['path']))) {
throw new PhpfastcacheInvalidConfigurationException('Path must be a valid string in "$server" configuration array if host is not defined');
}
if (!empty($server['host']) && (empty($server['port']) || !is_int($server['port']) || $server['port'] < 1)) {
throw new PhpfastcacheInvalidConfigurationException('Port must be a valid integer in "$server" configuration array');
}
if (!empty($server['port']) && !empty($server['path'])) {
throw new PhpfastcacheInvalidConfigurationException('Port should not be defined along with path');
}
}
return $this->setProperty('servers', $servers);
}
/**
* @return string
*/
public function getHost(): string
{
return $this->host;
}
/**
* @param string $host
* @return self
* @throws PhpfastcacheLogicException
*/
public function setHost(string $host): static
{
return $this->setProperty('host', $host);
}
/**
* @return int
*/
public function getPort(): int
{
return $this->port;
}
/**
* @param int $port
* @return self
* @throws PhpfastcacheLogicException
*/
public function setPort(int $port): static
{
return $this->setProperty('port', $port);
}
}
@@ -0,0 +1,195 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Memcache;
use DateTime;
use Exception;
use Memcache as MemcacheSoftware;
use Phpfastcache\Cluster\AggregatablePoolInterface;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Entities\DriverStatistic;
use Phpfastcache\Event\EventManagerInterface;
use Phpfastcache\Exceptions\PhpfastcacheCoreException;
use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException;
use Phpfastcache\Exceptions\PhpfastcacheDriverConnectException;
use Phpfastcache\Exceptions\PhpfastcacheDriverException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheIOException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Phpfastcache\Util\MemcacheDriverCollisionDetectorTrait;
/**
* @property MemcacheSoftware $instance
* @method Config getConfig()
*/
class Driver implements AggregatablePoolInterface
{
use TaggableCacheItemPoolTrait {
__construct as protected __parentConstruct;
}
use MemcacheDriverCollisionDetectorTrait;
protected int $memcacheFlags = 0;
/**
* Driver constructor.
* @param ConfigurationOption $config
* @param string $instanceId
* @param EventManagerInterface $em
* @throws PhpfastcacheDriverConnectException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverCheckException
* @throws PhpfastcacheIOException
*/
public function __construct(ConfigurationOption $config, string $instanceId, EventManagerInterface $em)
{
self::checkCollision('Memcache');
$this->__parentConstruct($config, $instanceId, $em);
}
/**
* @return bool
*/
public function driverCheck(): bool
{
return class_exists('Memcache');
}
/**
* @return DriverStatistic
*/
public function getStats(): DriverStatistic
{
$stats = (array)$this->instance->getstats();
$stats['uptime'] = (isset($stats['uptime']) ? $stats['uptime'] : 0);
$stats['version'] = (isset($stats['version']) ? $stats['version'] : 'UnknownVersion');
$stats['bytes'] = (isset($stats['bytes']) ? $stats['version'] : 0);
$date = (new DateTime())->setTimestamp(time() - $stats['uptime']);
return (new DriverStatistic())
->setData(implode(', ', array_keys($this->itemInstances)))
->setInfo(sprintf("The memcache daemon v%s is up since %s.\n For more information see RawData.", $stats['version'], $date->format(DATE_RFC2822)))
->setRawData($stats)
->setSize((int)$stats['bytes']);
}
/**
* @return bool
* @throws PhpfastcacheDriverException
*/
protected function driverConnect(): bool
{
$this->instance = new MemcacheSoftware();
foreach ($this->getConfig()->getServers() as $server) {
try {
/**
* If path is provided we consider it as a UNIX Socket
*/
if (!empty($server['path'])) {
$this->instance->addServer($server['path'], 0);
} elseif (!empty($server['host'])) {
$this->instance->addServer($server['host'], $server['port']);
}
if (!empty($server['saslUser']) && !empty($server['saslPassword'])) {
throw new PhpfastcacheDriverException('Unlike Memcached, Memcache does not support SASL authentication');
}
} catch (Exception $e) {
throw new PhpfastcacheDriverConnectException(
sprintf(
'Failed to connect to memcache host/path "%s" with the following error: %s',
$server['host'] ?: $server['path'],
$e->getMessage()
)
);
}
/**
* Since Memcached does not throw
* any error if not connected ...
*/
if (
!$this->instance->getServerStatus(
!empty($server['path']) ? $server['path'] : $server['host'],
!empty($server['port']) ? $server['port'] : 0
)
) {
throw new PhpfastcacheDriverException('Memcache seems to not be connected');
}
}
return true;
}
/**
* @param ExtendedCacheItemInterface $item
* @return ?array<string, mixed>
*/
protected function driverRead(ExtendedCacheItemInterface $item): ?array
{
$val = $this->instance->get($item->getKey());
if (empty($val) || !\is_array($val)) {
return null;
}
return $val;
}
/**
* @param ExtendedCacheItemInterface $item
* @return mixed
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
protected function driverWrite(ExtendedCacheItemInterface $item): bool
{
$ttl = $item->getExpirationDate()->getTimestamp() - time();
// Memcache will only allow an expiration timer less than 2592000 seconds,
// otherwise, it will assume you're giving it a UNIX timestamp.
if ($ttl > 2592000) {
$ttl = time() + $ttl;
}
return $this->instance->set($item->getKey(), $this->driverPreWrap($item), $this->memcacheFlags, $ttl);
}
/**
* @param string $key
* @param string $encodedKey
* @return bool
*/
protected function driverDelete(string $key, string $encodedKey): bool
{
return $this->instance->delete($key);
}
/**
* @return bool
*/
protected function driverClear(): bool
{
return $this->instance->flush();
}
}
@@ -0,0 +1,30 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Memcache;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Item\TaggableCacheItemTrait;
class Item implements ExtendedCacheItemInterface
{
use TaggableCacheItemTrait;
protected function getDriverClass(): string
{
return Driver::class;
}
}
@@ -0,0 +1,203 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Memcached;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Exceptions\PhpfastcacheInvalidConfigurationException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
class Config extends ConfigurationOption
{
/**
* @var array
*
* Multiple server can be added this way:
* $cfg->setServers([
* [
* // If you use a UNIX socket set the host and port to null
* 'host' => '127.0.0.1',
* //'path' => 'path/to/unix/socket',
* 'port' => 11211,
* 'saslUser' => null,
* 'saslPassword' => null,
* ]
* ]);
*/
/** @var array<array<string, mixed>> */
protected array $servers = [];
protected string $host = '127.0.0.1';
protected int $port = 11211;
protected string $saslUser = '';
protected string $saslPassword = '';
protected string $optPrefix = '';
/**
* @return string
*/
public function getSaslUser(): string
{
return $this->saslUser;
}
/**
* @param string $saslUser
* @return self
* @throws PhpfastcacheLogicException
*/
public function setSaslUser(string $saslUser): static
{
return $this->setProperty('saslUser', $saslUser);
}
/**
* @return string
*/
public function getSaslPassword(): string
{
return $this->saslPassword;
}
/**
* @param string $saslPassword
* @return self
* @throws PhpfastcacheLogicException
*/
public function setSaslPassword(string $saslPassword): static
{
return $this->setProperty('saslPassword', $saslPassword);
}
/**
* @return array<array<string, mixed>>
*/
public function getServers(): array
{
if (!count($this->servers)) {
return [
[
'host' => $this->getHost(),
'path' => $this->getPath(),
'port' => $this->getPort(),
'saslUser' => $this->getSaslUser() ?: null,
'saslPassword' => $this->getSaslPassword() ?: null,
],
];
}
return $this->servers;
}
/**
* @param array<array<string, mixed>> $servers
* @return self
* @throws PhpfastcacheInvalidConfigurationException
* @throws PhpfastcacheLogicException
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function setServers(array $servers): static
{
foreach ($servers as $server) {
if ($diff = array_diff(array_keys($server), ['host', 'port', 'saslUser', 'saslPassword', 'path'])) {
throw new PhpfastcacheInvalidConfigurationException('Unknown keys for memcached server: ' . implode(', ', $diff));
}
if (!empty($server['host']) && !empty($server['path'])) {
throw new PhpfastcacheInvalidConfigurationException('Host and path cannot be simultaneous defined.');
}
if ((isset($server['host']) && !is_string($server['host'])) || (empty($server['path']) && empty($server['host']))) {
throw new PhpfastcacheInvalidConfigurationException('Host must be a valid string in "$server" configuration array if path is not defined');
}
if ((isset($server['path']) && !is_string($server['path'])) || (empty($server['host']) && empty($server['path']))) {
throw new PhpfastcacheInvalidConfigurationException('Path must be a valid string in "$server" configuration array if host is not defined');
}
if (!empty($server['host']) && (empty($server['port']) || !is_int($server['port']) || $server['port'] < 1)) {
throw new PhpfastcacheInvalidConfigurationException('Port must be a valid integer in "$server" configuration array');
}
if (!empty($server['port']) && !empty($server['path'])) {
throw new PhpfastcacheInvalidConfigurationException('Port should not be defined along with path');
}
if (!empty($server['saslUser']) && !empty($server['saslPassword']) && (!is_string($server['saslUser']) || !is_string($server['saslPassword']))) {
throw new PhpfastcacheInvalidConfigurationException('If provided, saslUser and saslPassword must be a string');
}
}
return $this->setProperty('servers', $servers);
}
/**
* @return string
*/
public function getHost(): string
{
return $this->host;
}
/**
* @param string $host
* @return self
* @throws PhpfastcacheLogicException
*/
public function setHost(string $host): static
{
return $this->setProperty('host', $host);
}
/**
* @return int
*/
public function getPort(): int
{
return $this->port;
}
/**
* @param int $port
* @return Config
* @throws PhpfastcacheLogicException
*/
public function setPort(int $port): static
{
return $this->setProperty('port', $port);
}
/**
* @return string
* @since 8.0.2
*/
public function getOptPrefix(): string
{
return $this->optPrefix;
}
/**
* @param string $optPrefix
* @return Config
* @throws PhpfastcacheLogicException
* @since 8.0.2
*/
public function setOptPrefix(string $optPrefix): Config
{
return $this->setProperty('optPrefix', trim($optPrefix));
}
}
@@ -0,0 +1,230 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Memcached;
use DateTime;
use Memcached as MemcachedSoftware;
use Phpfastcache\Cluster\AggregatablePoolInterface;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Entities\DriverStatistic;
use Phpfastcache\Event\EventManagerInterface;
use Phpfastcache\Exceptions\PhpfastcacheCoreException;
use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException;
use Phpfastcache\Exceptions\PhpfastcacheDriverConnectException;
use Phpfastcache\Exceptions\PhpfastcacheDriverException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidTypeException;
use Phpfastcache\Exceptions\PhpfastcacheIOException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Phpfastcache\Util\MemcacheDriverCollisionDetectorTrait;
use Psr\Cache\CacheItemInterface;
/**
* @property MemcachedSoftware $instance
* @method Config getConfig()
*/
class Driver implements AggregatablePoolInterface
{
use TaggableCacheItemPoolTrait {
__construct as protected __parentConstruct;
}
use MemcacheDriverCollisionDetectorTrait;
/**
* Driver constructor.
* @param ConfigurationOption $config
* @param string $instanceId
* @param EventManagerInterface $em
* @throws PhpfastcacheDriverConnectException
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheCoreException
* @throws PhpfastcacheDriverCheckException
* @throws PhpfastcacheIOException
*/
public function __construct(ConfigurationOption $config, string $instanceId, EventManagerInterface $em)
{
self::checkCollision('Memcached');
$this->__parentConstruct($config, $instanceId, $em);
}
/**
* @return bool
*/
public function driverCheck(): bool
{
return class_exists('Memcached');
}
/**
* @return DriverStatistic
*/
public function getStats(): DriverStatistic
{
$stats = current($this->instance->getStats());
$stats['uptime'] = $stats['uptime'] ?? 0;
$stats['bytes'] = $stats['bytes'] ?? 0;
$stats['version'] = $stats['version'] ?? $this->instance->getVersion();
$date = (new DateTime())->setTimestamp(time() - $stats['uptime']);
return (new DriverStatistic())
->setData(implode(', ', array_keys($this->itemInstances)))
->setInfo(sprintf("The memcache daemon v%s is up since %s.\n For more information see RawData.", $stats['version'], $date->format(DATE_RFC2822)))
->setRawData($stats)
->setSize((int)$stats['bytes']);
}
/**
* @return bool
* @throws PhpfastcacheDriverException
*/
protected function driverConnect(): bool
{
$this->instance = new MemcachedSoftware();
$optPrefix = $this->getConfig()->getOptPrefix();
$this->instance->setOption(MemcachedSoftware::OPT_BINARY_PROTOCOL, true);
if ($optPrefix) {
$this->instance->setOption(MemcachedSoftware::OPT_PREFIX_KEY, $optPrefix);
}
foreach ($this->getConfig()->getServers() as $server) {
$connected = false;
/**
* If path is provided we consider it as an UNIX Socket
*/
if (!empty($server['path'])) {
$connected = $this->instance->addServer($server['path'], 0);
} elseif (!empty($server['host'])) {
$connected = $this->instance->addServer($server['host'], $server['port']);
}
if (!empty($server['saslUser']) && !empty($server['saslPassword'])) {
$this->instance->setSaslAuthData($server['saslUser'], $server['saslPassword']);
}
if (!$connected) {
throw new PhpfastcacheDriverConnectException(
sprintf(
'Failed to connect to memcache host/path "%s".',
$server['host'] ?: $server['path'],
)
);
}
}
/**
* Since Memcached does not throw
* any error if not connected ...
*/
$version = $this->instance->getVersion();
if (!$version || $this->instance->getResultCode() !== MemcachedSoftware::RES_SUCCESS) {
throw new PhpfastcacheDriverException('Memcached seems to not be connected');
}
return true;
}
/**
* @param ExtendedCacheItemInterface $item
* @return ?array<string, mixed>
*/
protected function driverRead(ExtendedCacheItemInterface $item): ?array
{
$val = $this->instance->get($item->getKey());
if (empty($val) || !\is_array($val)) {
return null;
}
return $val;
}
/**
* @param ExtendedCacheItemInterface ...$items
* @return array<array<string, mixed>>
*/
protected function driverReadMultiple(ExtendedCacheItemInterface ...$items): array
{
$keys = $this->getKeys($items);
$val = $this->instance->getMulti($keys);
if (empty($val) || !\is_array($val)) {
return [];
}
return $val;
}
/**
* @return array<string, mixed>
* @throws PhpfastcacheInvalidArgumentException
*/
protected function driverReadAllKeys(string $pattern = ''): iterable
{
if ($pattern !== '') {
$this->throwUnsupportedDriverReadAllPattern('https://www.php.net/manual/en/memcached.getallkeys.php');
}
$keys = $this->instance->getAllKeys();
if (is_iterable($keys)) {
return $keys;
} else {
return [];
}
}
/**
* @param ExtendedCacheItemInterface $item
* @return bool
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
protected function driverWrite(ExtendedCacheItemInterface $item): bool
{
$ttl = $item->getExpirationDate()->getTimestamp() - time();
// Memcache will only allow a expiration timer less than 2592000 seconds,
// otherwise, it will assume you're giving it a UNIX timestamp.
if ($ttl > 2592000) {
$ttl = time() + $ttl;
}
return $this->instance->set($item->getKey(), $this->driverPreWrap($item), $ttl);
}
/**
* @param string $key
* @param string $encodedKey
* @return bool
*/
protected function driverDelete(string $key, string $encodedKey): bool
{
return $this->instance->delete($key);
}
/**
* @return bool
*/
protected function driverClear(): bool
{
return $this->instance->flush();
}
}
@@ -0,0 +1,30 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Memcached;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Item\TaggableCacheItemTrait;
class Item implements ExtendedCacheItemInterface
{
use TaggableCacheItemTrait;
protected function getDriverClass(): string
{
return Driver::class;
}
}
@@ -0,0 +1,23 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Memory;
use Phpfastcache\Config\ConfigurationOption;
class Config extends ConfigurationOption
{
}
@@ -0,0 +1,128 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Memory;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Entities\DriverStatistic;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidTypeException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @method Config getConfig()
*/
class Driver implements ExtendedCacheItemPoolInterface
{
use TaggableCacheItemPoolTrait;
/**
* @var array<string, array<string, mixed>>
*/
protected array $staticStack = [];
/**
* @return bool
*/
public function driverCheck(): bool
{
return true;
}
/**
* @return bool
*/
protected function driverConnect(): bool
{
return true;
}
/**
* @param ExtendedCacheItemInterface $item
* @return ?array<string, mixed>
*/
protected function driverRead(ExtendedCacheItemInterface $item): ?array
{
return $this->staticStack[$item->getKey()] ?? null;
}
/**
* @return array<int, string>
*/
protected function driverReadAllKeys(string $pattern = ''): iterable
{
return array_filter(array_keys($this->staticStack), function (string $key) use ($pattern) {
return $pattern
? preg_match('/' . str_replace('*', '(.*)', $pattern) . '/', $key)
: true;
});
}
/**
* @param ExtendedCacheItemInterface $item
* @return bool
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
protected function driverWrite(ExtendedCacheItemInterface $item): bool
{
$this->staticStack[$item->getKey()] = $this->driverPreWrap($item);
return true;
}
/**
* @param string $key
* @param string $encodedKey
* @return bool
*/
protected function driverDelete(string $key, string $encodedKey): bool
{
if (isset($this->staticStack[$key])) {
unset($this->staticStack[$key]);
return true;
}
return false;
}
/**
* @return bool
*/
protected function driverClear(): bool
{
unset($this->staticStack);
$this->staticStack = [];
return true;
}
/**
* @return DriverStatistic
*/
public function getStats(): DriverStatistic
{
$stat = new DriverStatistic();
$stat->setInfo('[Memstatic] A memory static driver')
->setSize(mb_strlen(serialize($this->staticStack)))
->setData(implode(', ', array_keys($this->itemInstances)))
->setRawData($this->staticStack);
return $stat;
}
}
@@ -0,0 +1,30 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Memory;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Item\TaggableCacheItemTrait;
class Item implements ExtendedCacheItemInterface
{
use TaggableCacheItemTrait;
protected function getDriverClass(): string
{
return Driver::class;
}
}
@@ -0,0 +1,30 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Memstatic;
/**
* @deprecated Memstatic driver has changed its name, it is now called "Memory".
* @see \Phpfastcache\Drivers\Memory\Config
*/
class Config extends \Phpfastcache\Drivers\Memory\Config
{
public function __construct(array $parameters = [])
{
trigger_error('Memstatic driver has changed its name, it is now called "Memory"', E_USER_DEPRECATED);
parent::__construct($parameters);
}
}
@@ -0,0 +1,33 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Memstatic;
use Phpfastcache\Config\ConfigurationOptionInterface;
use Phpfastcache\Event\EventManagerInterface;
/**
* @deprecated Memstatic driver has changed its name, it is now called "Memory".
* @see \Phpfastcache\Drivers\Memory\Driver
*/
class Driver extends \Phpfastcache\Drivers\Memory\Driver
{
public function __construct(#[\SensitiveParameter] ConfigurationOptionInterface $config, string $instanceId, EventManagerInterface $em)
{
trigger_error('Memstatic driver has changed its name, it is now called "Memory"', E_USER_DEPRECATED);
parent::__construct($config, $instanceId, $em);
}
}
@@ -0,0 +1,33 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Memstatic;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Event\EventManagerInterface;
/**
* @deprecated Memstatic driver has changed its name, it is now called "Memory".
* @see \Phpfastcache\Drivers\Memory\Item
*/
class Item extends \Phpfastcache\Drivers\Memory\Item
{
public function __construct(ExtendedCacheItemPoolInterface $driver, string $key, EventManagerInterface $em)
{
trigger_error('Memstatic driver has changed its name, it is now called "Memory"', E_USER_DEPRECATED);
parent::__construct($driver, $key, $em);
}
}
@@ -0,0 +1,216 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Predis;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Exceptions\PhpfastcacheInvalidConfigurationException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Predis\Client;
class Config extends ConfigurationOption
{
protected string $host = '127.0.0.1';
protected int $port = 6379;
protected string $password = '';
protected int $database = 0;
protected ?Client $predisClient = null;
protected string $optPrefix = '';
protected int $timeout = 5;
protected bool $persistent = false;
protected string $scheme = 'unix';
/**
* @return array<string, mixed>
*/
public function getPredisConfigArray(): array
{
return [
'host' => $this->getHost(),
'port' => $this->getPort(),
'password' => $this->getPassword() ?: null,
'database' => $this->getDatabase(),
'timeout' => $this->getTimeout(),
];
}
/**
* @return string
*/
public function getHost(): string
{
return $this->host;
}
/**
* @param string $host
* @return Config
* @throws PhpfastcacheLogicException
*/
public function setHost(string $host): static
{
return $this->setProperty('host', $host);
}
/**
* @return int
*/
public function getPort(): int
{
return $this->port;
}
/**
* @param int $port
* @return Config
* @throws PhpfastcacheLogicException
*/
public function setPort(int $port): static
{
return $this->setProperty('port', $port);
}
/**
* @return string
*/
public function getPassword(): string
{
return $this->password;
}
/**
* @param string $password
* @return self
* @throws PhpfastcacheLogicException
*/
public function setPassword(string $password): static
{
return $this->setProperty('password', $password);
}
/**
* @return int
*/
public function getDatabase(): int
{
return $this->database;
}
/**
* @param int $database
* @return Config
* @throws PhpfastcacheLogicException
*/
public function setDatabase(int $database): static
{
return $this->setProperty('database', $database);
}
/**
* @return int
*/
public function getTimeout(): int
{
return $this->timeout;
}
/**
* @param int $timeout
* @return self
* @throws PhpfastcacheLogicException
*/
public function setTimeout(int $timeout): static
{
return $this->setProperty('timeout', $timeout);
}
/**
* @return Client|null
*/
public function getPredisClient(): ?Client
{
return $this->predisClient;
}
/**
* @param Client|null $predisClient
* @return Config
* @throws PhpfastcacheLogicException
*/
public function setPredisClient(?Client $predisClient = null): Config
{
return $this->setProperty('predisClient', $predisClient);
}
/**
* @return string
* @since 7.0.2
*/
public function getOptPrefix(): string
{
return $this->optPrefix;
}
/**
* @param string $optPrefix
* @return Config
* @throws PhpfastcacheLogicException
* @since 7.0.2
*/
public function setOptPrefix(string $optPrefix): Config
{
return $this->setProperty('optPrefix', trim($optPrefix));
}
/**
* @return bool
*/
public function isPersistent(): bool
{
return $this->persistent;
}
/**
* @param bool $persistent
* @return Config
* @throws PhpfastcacheLogicException
*/
public function setPersistent(bool $persistent): Config
{
return $this->setProperty('persistent', $persistent);
}
/**
* @return string
*/
public function getScheme(): string
{
return $this->scheme;
}
/**
* @param string $scheme
* @return Config
* @throws PhpfastcacheInvalidConfigurationException
* @throws PhpfastcacheLogicException
*/
public function setScheme(string $scheme): Config
{
if (!in_array($scheme, ['unix', 'tls'], true)) {
throw new PhpfastcacheInvalidConfigurationException('Invalid scheme: ' . $scheme);
}
return $this->setProperty('scheme', $scheme);
}
}
@@ -0,0 +1,235 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Predis;
use DateTime;
use Phpfastcache\Cluster\AggregatablePoolInterface;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Entities\DriverStatistic;
use Phpfastcache\Exceptions\PhpfastcacheDriverException;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Predis\Client as PredisClient;
use Predis\Collection\Iterator as PredisIterator;
use Predis\Connection\ConnectionException as PredisConnectionException;
/**
* @property PredisClient $instance Instance of driver service
* @method Config getConfig()
*/
class Driver implements AggregatablePoolInterface
{
use TaggableCacheItemPoolTrait;
/**
* @return bool
*/
public function driverCheck(): bool
{
if (extension_loaded('Redis')) {
trigger_error('The native Redis extension is installed, you should use Redis instead of Predis to increase performances', E_USER_NOTICE);
}
return class_exists(\Predis\Client::class);
}
/**
* @return string
*/
public function getHelp(): string
{
return <<<HELP
<p>
To install the Predis library via Composer:
<code>composer require "predis/predis" "~1.1.0"</code>
</p>
HELP;
}
/**
* @return DriverStatistic
*/
public function getStats(): DriverStatistic
{
$info = $this->instance->info();
$size = ($info['Memory']['used_memory'] ?? 0);
$version = ($info['Server']['redis_version'] ?? 0);
$date = (isset($info['Server']['uptime_in_seconds']) ? (new DateTime())->setTimestamp(time() - $info['Server']['uptime_in_seconds']) : 'unknown date');
return (new DriverStatistic())
->setData(implode(', ', array_keys($this->itemInstances)))
->setRawData($info)
->setSize((int)$size)
->setInfo(
sprintf(
"The Redis daemon v%s (with Predis v%s) is up since %s.\n For more information see RawData. \n Driver size includes the memory allocation size.",
$version,
PredisClient::VERSION,
$date->format(DATE_RFC2822)
)
);
}
/**
* @return bool
* @throws PhpfastcacheDriverException
* @throws PhpfastcacheLogicException
*/
protected function driverConnect(): bool
{
/**
* In case of a user-provided
* Predis client just return here
*/
if ($this->getConfig()->getPredisClient() instanceof PredisClient) {
$this->instance = $this->getConfig()->getPredisClient();
if (!$this->instance->isConnected()) {
$this->instance->connect();
}
return true;
}
$options = [];
if ($this->getConfig()->getOptPrefix()) {
$options['prefix'] = $this->getConfig()->getOptPrefix();
}
if (!empty($this->getConfig()->getPath())) {
$this->instance = new PredisClient(
[
'scheme' => $this->getConfig()->getScheme(),
'persistent' => $this->getConfig()->isPersistent(),
'timeout' => $this->getConfig()->getTimeout(),
'path' => $this->getConfig()->getPath(),
],
$options
);
} else {
$this->instance = new PredisClient($this->getConfig()->getPredisConfigArray(), $options);
}
try {
$this->instance->connect();
} catch (PredisConnectionException $e) {
throw new PhpfastcacheDriverException(
'Failed to connect to predis server. Check the Predis documentation: https://github.com/nrk/predis/tree/v1.1#how-to-install-and-use-predis',
0,
$e
);
}
return true;
}
/**
* @param ExtendedCacheItemInterface $item
* @return ?array<string, mixed>
*/
protected function driverRead(ExtendedCacheItemInterface $item): ?array
{
$val = $this->instance->get($item->getKey());
if ($val === null) {
return null;
}
return $this->decode($val);
}
/**
* @param ExtendedCacheItemInterface ...$items
* @return array<array<string, mixed>>
* @throws \Phpfastcache\Exceptions\PhpfastcacheDriverException
* @throws \RedisException
*/
protected function driverReadMultiple(ExtendedCacheItemInterface ...$items): array
{
$keys = $this->getKeys($items);
return array_combine($keys, array_map(
fn($val) => $val ? $this->decode($val) : null,
$this->instance->mget($keys)
));
}
/**
* @return array<int, string>
* @throws \RedisException
*/
protected function driverReadAllKeys(string $pattern = '*'): iterable
{
$keys = [];
foreach (new PredisIterator\Keyspace($this->instance, $pattern, ExtendedCacheItemPoolInterface::MAX_ALL_KEYS_COUNT) as $key) {
$keys[] = $key;
}
return $keys;
}
/**
* @param ExtendedCacheItemInterface $item
* @return mixed
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
protected function driverWrite(ExtendedCacheItemInterface $item): bool
{
$ttl = $item->getExpirationDate()->getTimestamp() - time();
/**
* @see https://redis.io/commands/setex
* @see https://redis.io/commands/expire
*/
if ($ttl <= 0) {
return (bool)$this->instance->expire($item->getKey(), 0);
}
return $this->instance->setex($item->getKey(), $ttl, $this->encode($this->driverPreWrap($item)))->getPayload() === 'OK';
}
/**
* @param string $key
* @param string $encodedKey
* @return bool
*/
protected function driverDelete(string $key, string $encodedKey): bool
{
return (bool)$this->instance->del([$key]);
}
/**
* @param string[] $keys
* @return bool
*/
protected function driverDeleteMultiple(array $keys): bool
{
return (bool) $this->instance->del(...$keys);
}
/**
* @return bool
*/
protected function driverClear(): bool
{
return $this->instance->flushdb()->getPayload() === 'OK';
}
}
@@ -0,0 +1,30 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Predis;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Item\TaggableCacheItemTrait;
class Item implements ExtendedCacheItemInterface
{
use TaggableCacheItemTrait;
protected function getDriverClass(): string
{
return Driver::class;
}
}
@@ -0,0 +1,161 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Redis;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Redis as RedisClient;
class Config extends ConfigurationOption
{
protected string $host = '127.0.0.1';
protected int $port = 6379;
protected string $password = '';
protected int $database = 0;
protected int $timeout = 5;
protected ?RedisClient $redisClient = null;
protected string $optPrefix = '';
/**
* @return string
*/
public function getHost(): string
{
return $this->host;
}
/**
* @param string $host
* @return static
* @throws PhpfastcacheLogicException
*/
public function setHost(string $host): static
{
return $this->setProperty('host', $host);
}
/**
* @return int
*/
public function getPort(): int
{
return $this->port;
}
/**
* @param int $port
* @return static
* @throws PhpfastcacheLogicException
*/
public function setPort(int $port): static
{
return $this->setProperty('port', $port);
}
/**
* @return string
*/
public function getPassword(): string
{
return $this->password;
}
/**
* @param string $password
*
* @return static
* @throws PhpfastcacheLogicException
*/
public function setPassword(string $password): static
{
return $this->setProperty('password', $password);
}
/**
* @return null|int
*/
public function getDatabase(): ?int
{
return $this->database;
}
/**
* @param int|null $database
*
* @return static
* @throws PhpfastcacheLogicException
*/
public function setDatabase(?int $database = null): static
{
return $this->setProperty('database', $database);
}
/**
* @return int
*/
public function getTimeout(): int
{
return $this->timeout;
}
/**
* @param int $timeout
* @return static
* @throws PhpfastcacheLogicException
*/
public function setTimeout(int $timeout): static
{
return $this->setProperty('timeout', $timeout);
}
/**
* @return RedisClient|null
*/
public function getRedisClient(): ?RedisClient
{
return $this->redisClient;
}
/**
* @param RedisClient|null $redisClient
* @return Config
* @throws PhpfastcacheLogicException
*/
public function setRedisClient(?RedisClient $redisClient): Config
{
return $this->setProperty('redisClient', $redisClient);
}
/**
* @return string
* @since 7.0.2
*/
public function getOptPrefix(): string
{
return $this->optPrefix;
}
/**
* @param string $optPrefix
* @return Config
* @throws PhpfastcacheLogicException
* @since 7.0.2
*/
public function setOptPrefix(string $optPrefix): Config
{
return $this->setProperty('optPrefix', trim($optPrefix));
}
}
@@ -0,0 +1,146 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Redis;
use DateTime;
use Phpfastcache\Cluster\AggregatablePoolInterface;
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait;
use Phpfastcache\Entities\DriverStatistic;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Redis as RedisClient;
/**
* @property RedisClient $instance
* @method Config getConfig()
*/
class Driver implements AggregatablePoolInterface
{
use RedisDriverTrait, TaggableCacheItemPoolTrait {
RedisDriverTrait::driverReadMultiple insteadof TaggableCacheItemPoolTrait;
RedisDriverTrait::driverDeleteMultiple insteadof TaggableCacheItemPoolTrait;
}
/**
* @return bool
*/
public function driverCheck(): bool
{
return extension_loaded('Redis') && class_exists(RedisClient::class);
}
/**
* @return DriverStatistic
*/
public function getStats(): DriverStatistic
{
// used_memory
$info = $this->instance->info();
$date = (new DateTime())->setTimestamp(time() - $info['uptime_in_seconds']);
return (new DriverStatistic())
->setData(implode(', ', array_keys($this->itemInstances)))
->setRawData($info)
->setSize((int)$info['used_memory_dataset'])
->setInfo(
sprintf(
"The Redis daemon v%s, php-ext v%s, is up since %s.\n For more information see RawData.",
$info['redis_version'],
\phpversion("redis"),
$date->format(DATE_RFC2822)
)
);
}
/**
* @return bool
* @throws PhpfastcacheLogicException
*/
protected function driverConnect(): bool
{
if (isset($this->instance) && $this->instance instanceof RedisClient) {
throw new PhpfastcacheLogicException('Already connected to Redis server');
}
/**
* In case of an user-provided
* Redis client just return here
*/
if ($this->getConfig()->getRedisClient() instanceof RedisClient) {
/**
* Unlike Predis, we can't test if we're connected
* or not, so let's just assume that we are
*/
$this->instance = $this->getConfig()->getRedisClient();
return true;
}
$this->instance = $this->instance ?? new RedisClient();
/**
* If path is provided we consider it as a UNIX Socket
*/
if ($this->getConfig()->getPath()) {
$isConnected = $this->instance->connect($this->getConfig()->getPath());
} else {
$isConnected = $this->instance->connect($this->getConfig()->getHost(), $this->getConfig()->getPort(), $this->getConfig()->getTimeout());
}
if (!$isConnected && $this->getConfig()->getPath()) {
return false;
}
if ($this->getConfig()->getOptPrefix()) {
$this->instance->setOption(RedisClient::OPT_PREFIX, $this->getConfig()->getOptPrefix());
}
if ($this->getConfig()->getPassword() && !$this->instance->auth($this->getConfig()->getPassword())) {
return false;
}
if ($this->getConfig()->getDatabase() !== null) {
$this->instance->select($this->getConfig()->getDatabase());
}
return true;
}
/**
* @return array<int, string>
* @throws \RedisException
*/
protected function driverReadAllKeys(string $pattern = '*'): iterable
{
$i = null;
$pattern = $pattern === '' ? '*' : $pattern;
do {
$keys[] = $this->instance->scan($i, $pattern);
if (\count($keys) > ExtendedCacheItemPoolInterface::MAX_ALL_KEYS_COUNT) {
break;
}
} while ($i > 0);
return \array_merge([], ...$keys);
}
/**
* @return bool
*/
protected function driverClear(): bool
{
return $this->instance->flushDB();
}
}
@@ -0,0 +1,30 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Redis;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Core\Item\TaggableCacheItemTrait;
class Item implements ExtendedCacheItemInterface
{
use TaggableCacheItemTrait;
protected function getDriverClass(): string
{
return Driver::class;
}
}
@@ -0,0 +1,103 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Redis;
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use Redis as RedisClient;
use RedisCluster as RedisClusterClient;
/**
* @property RedisClient|RedisClusterClient $instance
* @method Config getConfig()
*/
trait RedisDriverTrait
{
/**
* @param ExtendedCacheItemInterface $item
* @return ?array<string, mixed>
*/
protected function driverRead(ExtendedCacheItemInterface $item): ?array
{
$val = $this->instance->get($item->getKey());
if (!$val) {
return null;
}
return $this->decode($val);
}
/**
* @param ExtendedCacheItemInterface ...$items
* @return array<array<string, mixed>>
* @throws \Phpfastcache\Exceptions\PhpfastcacheDriverException
* @throws \RedisException
*/
protected function driverReadMultiple(ExtendedCacheItemInterface ...$items): array
{
$keys = $this->getKeys($items);
return array_combine($keys, array_map(
fn($val) => $val ? $this->decode($val) : null,
$this->instance->mGet($keys)
));
}
/**
* @param ExtendedCacheItemInterface $item
* @return mixed
* @throws PhpfastcacheInvalidArgumentException
* @throws PhpfastcacheLogicException
*/
protected function driverWrite(ExtendedCacheItemInterface $item): bool
{
$this->assertCacheItemType($item, self::getItemClass());
$ttl = $item->getExpirationDate()->getTimestamp() - time();
/**
* @see https://redis.io/commands/setex
* @see https://redis.io/commands/expire
*/
if ($ttl <= 0) {
return $this->instance->expire($item->getKey(), 0);
}
return $this->instance->setex($item->getKey(), $ttl, $this->encode($this->driverPreWrap($item)));
}
/**
* @param string $key
* @param string $encodedKey
* @return bool
* @throws \RedisException
*/
protected function driverDelete(string $key, string $encodedKey): bool
{
return (bool) $this->instance->del($key);
}
/**
* @param string[] $keys
* @return bool
*/
protected function driverDeleteMultiple(array $keys): bool
{
return (bool) $this->instance->del(...$keys);
}
}
@@ -0,0 +1,186 @@
<?php
/**
*
* This file is part of Phpfastcache.
*
* @license MIT License (MIT)
*
* For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
*
* @author Georges.L (Geolim4) <contact@geolim4.com>
* @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
*/
declare(strict_types=1);
namespace Phpfastcache\Drivers\Rediscluster;
use Phpfastcache\Config\ConfigurationOption;
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
use RedisCluster as RedisClusterClient;
class Config extends ConfigurationOption
{
/**
* @var array<string>
*/
protected array $clusters = [];
protected string $password = '';
protected int $timeout = 5;
protected int $readTimeout = 5;
protected ?RedisClusterClient $redisClusterClient = null;
protected string $optPrefix = '';
protected ?int $slaveFailover = null;
/**
* @return array<string>
*/
public function getClusters(): array
{
return $this->clusters;
}
/**
* @param string $cluster
* @return Config
*/
public function addCluster(string $cluster): static
{
$this->enforceLockedProperty(__FUNCTION__);
$this->clusters[] = $cluster;
return $this;
}
/**
* @param string $clusters
* @return Config
*/
public function setClusters(...$clusters): static
{
return $this->setProperty('clusters', $clusters);
}
/**
* @return string
*/
public function getPassword(): string
{
return $this->password;
}
/**
* @param string $password
*
* @return static
* @throws PhpfastcacheLogicException
*/
public function setPassword(string $password): static
{
return $this->setProperty('password', $password);
}
/**
* @return int
*/
public function getTimeout(): int
{
return $this->timeout;
}
/**
* @param int $timeout
* @return static
* @throws PhpfastcacheLogicException
*/
public function setTimeout(int $timeout): static
{
return $this->setProperty('timeout', $timeout);
}
/**
* @return int
*/
public function getReadTimeout(): int
{
return $this->readTimeout;
}
/**
* @param int $readTimeout
* @return static
* @throws PhpfastcacheLogicException
*/
public function setReadTimeout(int $readTimeout): static
{
return $this->setProperty('readTimeout', $readTimeout);
}
/**
* @return RedisClusterClient|null
*/
public function getRedisClusterClient(): ?RedisClusterClient
{
return $this->redisClusterClient;
}
/**
* @param RedisClusterClient|null $redisClusterClient
* @return Config
* @throws PhpfastcacheLogicException
*/
public function setRedisClusterClient(?RedisClusterClient $redisClusterClient): static
{
return $this->setProperty('redisClusterClient', $redisClusterClient);
}
/**
* @return string
* @since 7.0.2
*/
public function getOptPrefix(): string
{
return $this->optPrefix;
}
/**
* @param string $optPrefix
* @return Config
* @throws PhpfastcacheLogicException
* @since 7.0.2
*/
public function setOptPrefix(string $optPrefix): static
{
return $this->setProperty('optPrefix', trim($optPrefix));
}
/**
* @return int|null
*/
public function getSlaveFailover(): ?int
{
return $this->slaveFailover;
}
/**
* @param int|null $slaveFailover
* @return Config
* @throws PhpfastcacheInvalidArgumentException
*/
public function setSlaveFailover(?int $slaveFailover): static
{
if (
$slaveFailover !== null && !in_array($slaveFailover, [
RedisClusterClient::FAILOVER_NONE,
RedisClusterClient::FAILOVER_ERROR,
RedisClusterClient::FAILOVER_DISTRIBUTE,
RedisClusterClient::FAILOVER_DISTRIBUTE_SLAVES,
])
) {
throw new PhpfastcacheInvalidArgumentException('Invalid Slave Failover option: ' . $slaveFailover);
}
return $this->setProperty('slaveFailover', $slaveFailover);
}
}
Loaded 100 of 1485 files, more files were not shown because too many files have changed in this diff. Show more