- Updated local libraries
- PHP 7.1 support
- New, proper caching method
- Special cache folder
This commit is contained in:
Wruczek
2017-01-29 22:56:17 +01:00
parent af2d44a713
commit 1ffaee0730
110 changed files with 8445 additions and 4370 deletions

View File

@ -0,0 +1,3 @@
order deny,allow
deny from all
allow from 127.0.0.1

View File

@ -0,0 +1,72 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache;
/**
* Class Api
* @package phpFastCache
*/
class Api
{
protected static $version = '1.1.3';
/**
* This method will returns the current
* API version, the API version will be
* updated by following the semantic versioning
* based on changes of:
* - ExtendedCacheItemPoolInterface
* - ExtendedCacheItemInterface
*
* @see http://semver.org/
* @return string
*/
public static function getVersion()
{
return self::$version;
}
/**
* Return the API changelog, as a string.
* @return string
*/
public static function getChangelog()
{
return <<<CHANGELOG
- 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
CHANGELOG;
}
}

View File

@ -0,0 +1,334 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Cache;
use phpFastCache\Core\ExtendedCacheItemPoolTrait;
use phpFastCache\Exceptions\phpFastCacheDriverException;
/**
* Class DriverBaseTrait
* @package phpFastCache\Cache
*/
trait DriverBaseTrait
{
use ExtendedCacheItemPoolTrait;
/**
* @var array default options, this will be merge to Driver's Options
*/
protected $config = [];
/**
* @var bool
*/
protected $fallback = false;
/**
* @var mixed Instance of driver service
*/
protected $instance;
/**
* @param $config_name
* @param string $value
*/
public function setup($config_name, $value = '')
{
/**
* Config for class
*/
if (is_array($config_name)) {
$this->config = array_merge($this->config, $config_name);
} else {
$this->config[ $config_name ] = $value;
}
}
/**
* @return array
*/
public function getConfig()
{
return $this->config;
}
/**
* @param $file
* @return string
* @throws \Exception
*/
protected function readfile($file)
{
if (function_exists('file_get_contents')) {
return file_get_contents($file);
} else {
$string = '';
$file_handle = @fopen($file, 'r');
if (!$file_handle) {
throw new phpFastCacheDriverException("Can't Read File", 96);
}
while (!feof($file_handle)) {
$line = fgets($file_handle);
$string .= $line;
}
fclose($file_handle);
return $string;
}
}
/**
* Encode data types such as object/array
* for driver that does not support
* non-scalar value
* @param $data
* @return string
*/
protected function encode($data)
{
return serialize($data);
}
/**
* Decode data types such as object/array
* for driver that does not support
* non-scalar value
* @param $value
* @return mixed
*/
protected function decode($value)
{
return @unserialize($value);
}
/**
* Check phpModules or CGI
* @return bool
*/
protected function isPHPModule()
{
if (PHP_SAPI === 'apache2handler') {
return true;
} else {
if (strpos(PHP_SAPI, 'handler') !== false) {
return true;
}
}
return false;
}
/**
* @param $class
* @return bool
*/
protected function isExistingDriver($class)
{
return class_exists("\\phpFastCache\\Drivers\\{$class}");
}
/**
* @param $tag
* @return string
*/
protected function _getTagName($tag)
{
return "__tag__" . $tag;
}
/**
* @param \phpFastCache\Cache\ExtendedCacheItemInterface $item
* @return array
*/
public function driverPreWrap(ExtendedCacheItemInterface $item)
{
return [
self::DRIVER_DATA_WRAPPER_INDEX => $item->get(),
self::DRIVER_TIME_WRAPPER_INDEX => $item->getExpirationDate(),
self::DRIVER_TAGS_WRAPPER_INDEX => $item->getTags(),
];
}
/**
* @param array $wrapper
* @return mixed
*/
public function driverUnwrapData(array $wrapper)
{
return $wrapper[ self::DRIVER_DATA_WRAPPER_INDEX ];
}
/**
* @param array $wrapper
* @return mixed
*/
public function driverUnwrapTags(array $wrapper)
{
return $wrapper[ self::DRIVER_TAGS_WRAPPER_INDEX ];
}
/**
* @param array $wrapper
* @return \DateTime
*/
public function driverUnwrapTime(array $wrapper)
{
return $wrapper[ self::DRIVER_TIME_WRAPPER_INDEX ];
}
/**
* @return string
*/
public function getDriverName()
{
static $driverName;
return ($driverName ?: $driverName = ucfirst(substr(strrchr((new \ReflectionObject($this))->getNamespaceName(), '\\'), 1)));
}
/**
* @param \phpFastCache\Cache\ExtendedCacheItemInterface $item
* @return bool
* @throws \LogicException
*/
public function driverWriteTags(ExtendedCacheItemInterface $item)
{
/**
* Do not attempt to write tags
* on tags item, it can leads
* to an infinite recursive calls
*/
if(strpos($item->getKey(), self::DRIVER_TAGS_KEY_PREFIX ) === 0){
throw new \LogicException('Trying to set tag(s) to an Tag item index: ' . $item->getKey());
}
/**
* @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
*/
$tagsItem->set(array_merge((array) $data, [$item->getKey() => $expTimestamp]));
/**
* Set the expiration date
* of the $tagsItem based
* on the older $item
* expiration date
*/
if ($expTimestamp > $tagsItem->getExpirationDate()->getTimestamp()) {
$tagsItem->expiresAt($item->getExpirationDate());
}
$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(max($data));
$this->driverWrite($tagsItem);
$tagsItem->setHit(true);
} else {
$this->deleteItem($tagsItem->getKey());
}
}
return true;
}
/**
* @param $key
* @return string
*/
public function getTagKey($key)
{
return self::DRIVER_TAGS_KEY_PREFIX . $key;
}
/**
* @param $key
* @return string
*/
public function getTagKeys(array $keys)
{
foreach ($keys as &$key) {
$key = $this->getTagKey($key);
}
return $keys;
}
/**
* @param string $optionName
* @param mixed $optionValue
* @return bool
* @throws \InvalidArgumentException
*/
public static function isValidOption($optionName, $optionValue)
{
if (!is_string($optionName)) {
throw new \InvalidArgumentException('$optionName must be a string');
}
return true;
}
/**
* @return array
*/
public static function getRequiredOptions()
{
return [];
}
/**
* @return array
*/
public static function getValidOptions()
{
return [];
}
}

View File

@ -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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Cache;
use Psr\Cache\CacheItemInterface;
/**
* Interface ExtendedCacheItemInterface
* @package phpFastCache\Cache
*/
interface ExtendedCacheItemInterface extends CacheItemInterface, \JsonSerializable
{
/**
* Returns the encoded key for the current cache item.
* Usually as a MD5 hash
*
* @return string
* The encoded key string for this cache item.
*/
public function getEncodedKey();
/**
* @return mixed
*/
public function getUncommittedData();
/**
* @return \DateTimeInterface
*/
public function getExpirationDate();
/**
* @return int
*/
public function getTtl();
/**
* @return bool
*/
public function isExpired();
/**
* @param \phpFastCache\Cache\ExtendedCacheItemPoolInterface $driver
* @return mixed
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver);
/**
* @param bool $isHit
* @return $this
* @throws \InvalidArgumentException
*/
public function setHit($isHit);
/**
* @param int $step
* @return $this
* @throws \InvalidArgumentException
*/
public function increment($step = 1);
/**
* @param int $step
* @return $this
* @throws \InvalidArgumentException
*/
public function decrement($step = 1);
/**
* @param array|string $data
* @return $this
* @throws \InvalidArgumentException
*/
public function append($data);
/**
* @param array|string $data
* @return $this
* @throws \InvalidArgumentException
*/
public function prepend($data);
/**
* Sets the expiration time for this cache item.
*
* @param int|\DateInterval $time
* The period of time from the present after which the item MUST be considered
* expired. An integer parameter is understood to be the time in seconds until
* expiration. 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 static
* The called object.
*
* @deprecated Use CacheItemInterface::expiresAfter() instead
*/
public function touch($time);
/**
* @param string $tagName
* @return $this
* @throws \InvalidArgumentException
*/
public function addTag($tagName);
/**
* @param array $tagNames
* @return $this
*/
public function addTags(array $tagNames);
/**
* @param array $tags
* @return $this
* @throws \InvalidArgumentException
*/
public function setTags(array $tags);
/**
* @return array
*/
public function getTags();
/**
* @param string $separator
* @return mixed
*/
public function getTagsAsString($separator = ', ');
/**
* @param array $tagName
* @return $this
*/
public function removeTag($tagName);
/**
* @param array $tagNames
* @return $this
*/
public function removeTags(array $tagNames);
/**
* @return array
*/
public function getRemovedTags();
/**
* Return the data as a well-formatted string.
* Any scalar value will be casted to an array
* @param int $option json_encode() options
* @param int $depth json_encode() depth
* @return string
*/
public function getDataAsJsonString($option = 0, $depth = 512);
}

View File

@ -0,0 +1,357 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Cache;
use InvalidArgumentException;
use phpFastCache\Entities\driverStatistic;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
/**
* Interface ExtendedCacheItemPoolInterface
* @package phpFastCache\Cache
*/
interface ExtendedCacheItemPoolInterface extends CacheItemPoolInterface
{
/**
* @return array
*/
public function getConfig();
/**
* @return string
*/
public function getDriverName();
/**
* [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.
*
* @throws InvalidArgumentException
* If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return ExtendedCacheItemInterface
* The corresponding Cache Item.
*/
public function getItem($key);
/**
* [phpFastCache phpDoc Override]
* Returns a traversable set of cache items.
*
* @param array $keys
* An indexed array of keys of items to retrieve.
*
* @throws InvalidArgumentException
* If any of the keys in $keys are not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @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.
*/
public function getItems(array $keys = []);
/**
* Returns A json string that represents an array of items.
*
* @param array $keys
* An indexed array of keys of items to retrieve.
* @param int $option json_encode() options
* @param int $depth json_encode() depth
*
* @throws InvalidArgumentException
* If any of the keys in $keys are not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return string
*/
public function getItemsAsJsonString(array $keys = [], $option = 0, $depth = 512);
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
public function setItem(CacheItemInterface $item);
/**
* Deletes all items in the pool.
* @deprecated Use clear() instead
* Will be removed in 5.1
*
* @return bool
* True if the pool was successfully cleared. False if there was an error.
*/
public function clean();
/**
* @return driverStatistic
*/
public function getStats();
/**
* Returns a traversable set of cache items by a tag name.
*
* @param string $tagName
* An indexed array of keys of items to retrieve.
*
* @throws InvalidArgumentException
* If any of the keys in $keys are not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @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.
*/
public function getItemsByTag($tagName);
/**
* Returns a traversable set of cache items by a tag name.
*
* @param array $tagNames
* An indexed array of keys of items to retrieve.
*
* @throws InvalidArgumentException
* If any of the keys in $keys are not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @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.
*/
public function getItemsByTags(array $tagNames);
/**
* Returns A json string that represents an array of items by tags-based.
*
* @param array $tagNames
* An indexed array of keys of items to retrieve.
* @param int $option json_encode() options
* @param int $depth json_encode() depth
*
* @throws InvalidArgumentException
* If any of the keys in $keys are not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return string
*/
public function getItemsByTagsAsJsonString(array $tagNames, $option = 0, $depth = 512);
/**
* Removes the item from the pool by tag.
*
* @param string $tagName
* The tag for which to delete
*
* @throws InvalidArgumentException
* If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return bool
* True if the item was successfully removed. False if there was an error.
*/
public function deleteItemsByTag($tagName);
/**
* Removes the item from the pool by tag.
*
* @param array $tagNames
* The tag for which to delete
*
* @throws InvalidArgumentException
* If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return bool
* True if the item was successfully removed. False if there was an error.
*/
public function deleteItemsByTags(array $tagNames);
/**
* Increment the items from the pool by tag.
*
* @param string $tagName
* The tag for which to increment
* @param int $step
*
* @throws InvalidArgumentException
* If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return bool
* True if the item was successfully incremented. False if there was an error.
*/
public function incrementItemsByTag($tagName, $step = 1);
/**
* Increment the items from the pool by tag.
*
* @param array $tagNames
* The tag for which to increment
* @param int $step
*
* @throws InvalidArgumentException
* If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return bool
* True if the item was successfully incremented. False if there was an error.
*/
public function incrementItemsByTags(array $tagNames, $step = 1);
/**
* Decrement the items from the pool by tag.
*
* @param string $tagName
* The tag for which to decrement
* @param int $step
*
* @throws InvalidArgumentException
* If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return bool
* True if the item was successfully decremented. False if there was an error.
*/
public function decrementItemsByTag($tagName, $step = 1);
/**
* Decrement the items from the pool by tag.
*
* @param array $tagNames
* The tag for which to decrement
* @param int $step
*
* @throws InvalidArgumentException
* If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return bool
* True if the item was successfully decremented. False if there was an error.
*/
public function decrementItemsByTags(array $tagNames, $step = 1);
/**
* Decrement the items from the pool by tag.
*
* @param string $tagName
* The tag for which to append
*
* @param array|string $data
*
* @throws InvalidArgumentException
* If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return bool
* True if the item was successfully appended. False if there was an error.
*/
public function appendItemsByTag($tagName, $data);
/**
* Decrement the items from the pool by tag.
*
* @param array $tagNames
* The tag for which to append
*
* @param array|string $data
*
* @throws InvalidArgumentException
* If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return bool
* True if the item was successfully appended. False if there was an error.
*/
public function appendItemsByTags(array $tagNames, $data);
/**
* Prepend the items from the pool by tag.
*
* @param string $tagName
* The tag for which to prepend
*
* @param array|string $data
*
* @throws InvalidArgumentException
* If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return bool
* True if the item was successfully prepended. False if there was an error.
*/
public function prependItemsByTag($tagName, $data);
/**
* Prepend the items from the pool by tag.
*
* @param array $tagNames
* The tag for which to prepend
*
* @param array|string $data
*
* @throws InvalidArgumentException
* If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return bool
* True if the item was successfully prepended. False if there was an error.
*/
public function prependItemsByTags(array $tagNames, $data);
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return void
*/
public function detachItem(CacheItemInterface $item);
/**
* @return void
*/
public function detachAllItems();
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return void
* @throws \LogicException
*/
public function attachItem(CacheItemInterface $item);
/**
* 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 exists
*
* @param \Psr\Cache\CacheItemInterface $item
* @return bool|null
* @throws \LogicException
*/
public function isAttached(CacheItemInterface $item);
}

View File

@ -0,0 +1,447 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Cache;
use phpFastCache\Core\DriverAbstract;
trait ItemBaseTrait
{
/**
* @var bool
*/
protected $fetched = false;
/**
* @var DriverAbstract
*/
protected $driver;
/**
* @var string
*/
protected $key;
/**
* @var mixed
*/
protected $data;
/**
* @var \DateTime
*/
protected $expirationDate;
/**
* @var array
*/
protected $tags = [];
/**
* @var array
*/
protected $removedTags = [];
/**
* @var bool
*/
protected $isHit = false;
/********************
*
* PSR-6 Methods
*
*******************/
/**
* @return string
*/
public function getKey()
{
return $this->key;
}
/**
* @return mixed
*/
public function get()
{
return $this->data;
}
/**
* @param mixed $value
* @return $this
*/
public function set($value)
{
/**
* The user set a value,
* therefore there is no need to
* fetch from source anymore
*/
$this->fetched = true;
$this->data = $value;
return $this;
}
/**
* @return bool
* @throws \InvalidArgumentException
*/
public function isHit()
{
return $this->isHit;
}
/**
* @param bool $isHit
* @return $this
* @throws \InvalidArgumentException
*/
public function setHit($isHit)
{
if (is_bool($isHit)) {
$this->isHit = $isHit;
return $this;
} else {
throw new \InvalidArgumentException('$isHit must be a boolean');
}
}
/**
* @param \DateTimeInterface $expiration
* @return $this
*/
public function expiresAt($expiration)
{
if ($expiration instanceof \DateTimeInterface) {
$this->expirationDate = $expiration;
} else {
throw new \InvalidArgumentException('$expiration must be an object implementing the DateTimeInterface');
}
return $this;
}
/**
* Sets the expiration time for this cache item.
*
* @param int|\DateInterval $time
* The period of time from the present after which the item MUST be considered
* expired. An integer parameter is understood to be the time in seconds until
* expiration. 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 static
* The called object.
*
* @deprecated Use CacheItemInterface::expiresAfter() instead
*/
public function touch($time)
{
trigger_error('touch() is deprecated and will be removed in the next major release, use CacheItemInterface::expiresAfter() instead');
return $this->expiresAfter($time);
}
/**
* @param \DateInterval|int $time
* @return $this
* @throws \InvalidArgumentException
*/
public function expiresAfter($time)
{
if (is_numeric($time)) {
if ($time <= 0) {
/**
* 5 years, however memcached or memory cached will gone when u restart it
* just recommended for sqlite. files
*/
$time = 30 * 24 * 3600 * 5;
}
$this->expirationDate = (new \DateTime())->add(new \DateInterval(sprintf('PT%dS', $time)));
} else if ($time instanceof \DateInterval) {
$this->expirationDate = (new \DateTime())->add($time);
} else {
throw new \InvalidArgumentException('Invalid date format');
}
return $this;
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return string
*/
public function getEncodedKey()
{
return md5($this->getKey());
}
/**
* @return mixed
*/
public function getUncommittedData()
{
return $this->data;
}
/**
* @return \DateTimeInterface
*/
public function getExpirationDate()
{
return $this->expirationDate;
}
/**
* @return int
*/
public function getTtl()
{
$ttl = $this->expirationDate->getTimestamp() - time();
if ($ttl > 2592000) {
$ttl = time() + $ttl;
}
return $ttl;
}
/**
* @return bool
*/
public function isExpired()
{
return $this->expirationDate->getTimestamp() < (new \DateTime())->getTimestamp();
}
/**
* @param int $step
* @return $this
* @throws \InvalidArgumentException
*/
public function increment($step = 1)
{
if (is_int($step)) {
$this->fetched = true;
$this->data += $step;
} else {
throw new \InvalidArgumentException('$step must be numeric.');
}
return $this;
}
/**
* @param int $step
* @return $this
* @throws \InvalidArgumentException
*/
public function decrement($step = 1)
{
if (is_int($step)) {
$this->fetched = true;
$this->data -= $step;
} else {
throw new \InvalidArgumentException('$step must be numeric.');
}
return $this;
}
/**
* @param array|string $data
* @return $this
* @throws \InvalidArgumentException
*/
public function append($data)
{
if (is_array($this->data)) {
array_push($this->data, $data);
} else if (is_string($data)) {
$this->data .= (string) $data;
} else {
throw new \InvalidArgumentException('$data must be either array nor string.');
}
return $this;
}
/**
* @param array|string $data
* @return $this
* @throws \InvalidArgumentException
*/
public function prepend($data)
{
if (is_array($this->data)) {
array_unshift($this->data, $data);
} else if (is_string($data)) {
$this->data = (string) $data . $this->data;
} else {
throw new \InvalidArgumentException('$data must be either array nor string.');
}
return $this;
}
/**
* @param $tagName
* @return $this
* @throws \InvalidArgumentException
*/
public function addTag($tagName)
{
if (is_string($tagName)) {
$this->tags = array_unique(array_merge($this->tags, [$tagName]));
return $this;
} else {
throw new \InvalidArgumentException('$tagName must be a string');
}
}
/**
* @param array $tagNames
* @return $this
*/
public function addTags(array $tagNames)
{
foreach ($tagNames as $tagName) {
$this->addTag($tagName);
}
return $this;
}
/**
* @param array $tags
* @return $this
* @throws \InvalidArgumentException
*/
public function setTags(array $tags)
{
if (count($tags)) {
if (array_filter($tags, 'is_string')) {
$this->tags = $tags;
} else {
throw new \InvalidArgumentException('$tagName must be an array of string');
}
}
return $this;
}
/**
* @return array
*/
public function getTags()
{
return $this->tags;
}
/**
* @return string
*/
public function getTagsAsString($separator = ', ')
{
return implode($separator, $this->tags);
}
/**
* @param $tagName
* @return $this
*/
public function removeTag($tagName)
{
if (($key = array_search($tagName, $this->tags)) !== false) {
unset($this->tags[ $key ]);
$this->removedTags[] = $tagName;
}
return $this;
}
/**
* @param array $tagNames
* @return $this
*/
public function removeTags(array $tagNames)
{
foreach ($tagNames as $tagName) {
$this->removeTag($tagName);
}
return $this;
}
/**
* @return array
*/
public function getRemovedTags()
{
return array_diff($this->removedTags, $this->tags);
}
/**
* Return the data as a well-formatted string.
* Any scalar value will be casted to an array
* @param int $option json_encode() options
* @param int $depth json_encode() depth
* @return string
*/
public function getDataAsJsonString($option = 0, $depth = 512)
{
$data = $this->get();
if (is_object($data) || is_array($data)) {
$data = json_encode($data, $option, $depth);
} else {
$data = json_encode([$data], $option, $depth);
}
return json_encode($data, $option, $depth);
}
/**
* Implements \JsonSerializable interface
* @return mixed
*/
public function jsonSerialize()
{
return $this->get();
}
/**
* Prevent recursions for Debug (php 5.6+)
* @return array
*/
final public function __debugInfo()
{
$info = get_object_vars($this);
$info[ 'driver' ] = 'object(' . get_class($info[ 'driver' ]) . ')';
return (array) $info;
}
}

View File

@ -0,0 +1,270 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
/**
* Class CacheManager
* @package phpFastCache
*
* @method static ExtendedCacheItemPoolInterface Apc() Apc($config = []) Return a driver "apc" instance
* @method static ExtendedCacheItemPoolInterface Apcu() Apcu($config = []) Return a driver "apcu" instance
* @method static ExtendedCacheItemPoolInterface Cookie() Cookie($config = []) Return a driver "cookie" instance
* @method static ExtendedCacheItemPoolInterface Couchbase() Couchbase($config = []) Return a driver "couchbase" instance
* @method static ExtendedCacheItemPoolInterface Files() Files($config = []) Return a driver "files" instance
* @method static ExtendedCacheItemPoolInterface Leveldb() Leveldb($config = []) Return a driver "leveldb" instance
* @method static ExtendedCacheItemPoolInterface Memcache() Memcache($config = []) Return a driver "memcache" instance
* @method static ExtendedCacheItemPoolInterface Memcached() Memcached($config = []) Return a driver "memcached" instance
* @method static ExtendedCacheItemPoolInterface Mongodb() Mongodb($config = []) Return a driver "mongodb" instance
* @method static ExtendedCacheItemPoolInterface Predis() Predis($config = []) Return a driver "predis" instance
* @method static ExtendedCacheItemPoolInterface Redis() Redis($config = []) Return a driver "redis" instance
* @method static ExtendedCacheItemPoolInterface Sqlite() Sqlite($config = []) Return a driver "sqlite" instance
* @method static ExtendedCacheItemPoolInterface Ssdb() Ssdb($config = []) Return a driver "ssdb" instance
* @method static ExtendedCacheItemPoolInterface Wincache() Wincache($config = []) Return a driver "wincache" instance
* @method static ExtendedCacheItemPoolInterface Xcache() Xcache($config = []) Return a driver "xcache" instance
* @method static ExtendedCacheItemPoolInterface Zenddisk() Zenddisk($config = []) Return a driver "zend disk cache" instance
* @method static ExtendedCacheItemPoolInterface Zendshm() Zendshm($config = []) Return a driver "zend memory cache" instance
*
*/
class CacheManager
{
/**
* @var int
*/
public static $ReadHits = 0;
/**
* @var int
*/
public static $WriteHits = 0;
/**
* @var array
*/
protected static $config = [
'securityKey' => 'auto', // The securityKey that will be used to create the sub-directory
'ignoreSymfonyNotice' => false, // Ignore Symfony notices for Symfony projects that do not makes use of PhpFastCache's Symfony Bundle
'defaultTtl' => 900, // Default time-to-live in seconds
'htaccess' => true, // Auto-generate .htaccess if it is missing
'default_chmod' => 0777, // 0777 is recommended
'path' => '', // If not set will be the value of sys_get_temp_dir()
'fallback' => false, // Fall back when old driver is not supported
'limited_memory_each_object' => 4096, // Maximum size (bytes) of object store in memory
'compress_data' => false, // Compress stored data if the backend supports it
];
/**
* @var string
*/
protected static $namespacePath;
/**
* @var array
*/
protected static $instances = [];
/**
* @param string $driver
* @param array $config
* @return ExtendedCacheItemPoolInterface
*/
public static function getInstance($driver = 'auto', $config = [])
{
static $badPracticeOmeter = [];
/**
* @todo: Standardize a method for driver name
*/
$driver = self::standardizeDriverName($driver);
$config = array_merge(self::$config, $config);
if (!$driver || $driver === 'Auto') {
$driver = self::getAutoClass($config);
}
$instance = crc32($driver . serialize($config));
if (!isset(self::$instances[ $instance ])) {
$badPracticeOmeter[$driver] = 1;
if(!$config['ignoreSymfonyNotice'] && interface_exists('Symfony\Component\HttpKernel\KernelInterface') && !class_exists('phpFastCache\Bundle\phpFastCacheBundle')){
trigger_error('A Symfony Bundle to make the PhpFastCache integration more easier is now available here: https://github.com/PHPSocialNetwork/phpfastcache-bundle', E_USER_NOTICE);
}
$class = self::getNamespacePath() . $driver . '\Driver';
try{
self::$instances[ $instance ] = new $class($config);
}catch(phpFastCacheDriverCheckException $e){
$fallback = self::standardizeDriverName($config['fallback']);
if($fallback && $fallback !== $driver){
$class = self::getNamespacePath() . $fallback . '\Driver';
self::$instances[ $instance ] = new $class($config);
trigger_error(sprintf('The "%s" driver is unavailable at the moment, the fallback driver "%s" has been used instead.', $driver, $fallback), E_USER_WARNING);
}else{
throw new phpFastCacheDriverCheckException($e->getMessage(), $e->getCode(), $e);
}
}
} else if(++$badPracticeOmeter[$driver] >= 5){
trigger_error('[' . $driver . '] Calling many times CacheManager::getInstance() for already instanced drivers is a bad practice and have a significant impact on performances.
See https://github.com/PHPSocialNetwork/phpfastcache/wiki/[V5]-Why-calling-getInstance%28%29-each-time-is-a-bad-practice-%3F');
}
return self::$instances[ $instance ];
}
/**
* @param $config
* @return string
* @throws phpFastCacheDriverCheckException
*/
public static function getAutoClass($config = [])
{
static $autoDriver;
if ($autoDriver === null) {
foreach (self::getStaticSystemDrivers() as $driver) {
try {
self::getInstance($driver, $config);
$autoDriver = $driver;
} catch (phpFastCacheDriverCheckException $e) {
continue;
}
}
}
return $autoDriver;
}
/**
* @param string $name
* @param array $arguments
* @return \Psr\Cache\CacheItemPoolInterface
*/
public static function __callStatic($name, $arguments)
{
$options = (array_key_exists(0, $arguments) && is_array($arguments) ? $arguments[ 0 ] : []);
return self::getInstance($name, $options);
}
/**
* @return bool
*/
public static function clearInstances()
{
self::$instances = [];
gc_collect_cycles();
return !count(self::$instances);
}
/**
* @return string
*/
public static function getNamespacePath()
{
return self::$namespacePath ?: __NAMESPACE__ . '\Drivers\\';
}
/**
* @param string $path
*/
public static function setNamespacePath($path)
{
self::$namespacePath = $path;
}
/**
* @param $name
* @param string $value
* @deprecated Method "setup" is deprecated and will be removed in V6. Use method "setDefaultConfig" instead.
* @throws \InvalidArgumentException
*/
public static function setup($name, $value = '')
{
trigger_error('Method "setup" is deprecated and will be removed in V6 Use method "setDefaultConfig" instead.', E_USER_DEPRECATED);
self::setDefaultConfig($name, $value);
}
/**
* @param $name string|array
* @param mixed $value
* @throws \InvalidArgumentException
*/
public static function setDefaultConfig($name, $value = null)
{
if (is_array($name)) {
self::$config = array_merge(self::$config, $name);
} else if (is_string($name)){
self::$config[ $name ] = $value;
}else{
throw new \InvalidArgumentException('Invalid variable type: $name');
}
}
/**
* @return array
*/
public static function getDefaultConfig()
{
return self::$config;
}
/**
* @return array
*/
public static function getStaticSystemDrivers()
{
return [
'Sqlite',
'Files',
'Apc',
'Apcu',
'Memcache',
'Memcached',
'Couchbase',
'Mongodb',
'Predis',
'Redis',
'Ssdb',
'Leveldb',
'Wincache',
'Xcache',
'Zenddisk',
'Zendshm',
'Devnull',
];
}
/**
* @return array
*/
public static function getStaticAllDrivers()
{
return array_merge(self::getStaticSystemDrivers(), [
'Devtrue',
'Devfalse',
'Cookie',
]);
}
/**
* @param string $driverName
* @return string
*/
public static function standardizeDriverName($driverName)
{
return ucfirst(strtolower(trim($driverName)));
}
}

View File

@ -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 file.
*
* @author Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Core;
/**
* Trait ClassNamespaceResolverTrait
* @package phpFastCache\Core
*/
trait ClassNamespaceResolverTrait
{
/**
* @return string
*/
protected function getClassNamespace()
{
static $namespace;
if (!$namespace) {
$namespace = (new \ReflectionObject($this))->getNamespaceName();
}
return $namespace;
}
}

View File

@ -0,0 +1,67 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Core;
use phpFastCache\Cache\DriverBaseTrait;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use Psr\Cache\CacheItemInterface;
/**
* Class DriverAbstract
* @package phpFastCache\Core
*/
abstract class DriverAbstract implements ExtendedCacheItemPoolInterface
{
use DriverBaseTrait;
const DRIVER_CHECK_FAILURE = '%s is not installed or is misconfigured, cannot continue.';
const DRIVER_TAGS_KEY_PREFIX = '_TAG_';
const DRIVER_DATA_WRAPPER_INDEX = 'd';
const DRIVER_TIME_WRAPPER_INDEX = 't';
const DRIVER_TAGS_WRAPPER_INDEX = 'g';
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return array [
* 'd' => 'THE ITEM DATA'
* 't' => 'THE ITEM DATE EXPIRATION'
* 'g' => 'THE ITEM TAGS'
* ]
*
*/
abstract protected function driverRead(CacheItemInterface $item);
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
abstract protected function driverWrite(CacheItemInterface $item);
/**
* @return bool
*/
abstract protected function driverClear();
/**
* @return bool
*/
abstract protected function driverConnect();
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
*/
abstract protected function driverDelete(CacheItemInterface $item);
}

View File

@ -0,0 +1,370 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Core;
use InvalidArgumentException;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use Psr\Cache\CacheItemInterface;
trait ExtendedCacheItemPoolTrait
{
use StandardPsr6StructureTrait;
/**
* Deletes all items in the pool.
* @deprecated Use clear() instead
* Will be removed in 5.1
*
* @return bool
* True if the pool was successfully cleared. False if there was an error.
*/
public function clean()
{
trigger_error('Cache clean() method is deprecated, use clear() method instead', E_USER_DEPRECATED);
return $this->clear();
}
/**
* @param array $keys
* An indexed array of keys of items to retrieve.
* @param int $option json_encode() options
* @param int $depth json_encode() depth
* @return string
* @throws \InvalidArgumentException
*/
public function getItemsAsJsonString(array $keys = [], $option = 0, $depth = 512)
{
$callback = function(CacheItemInterface $item){
return $item->get();
};
return json_encode(array_map($callback, array_values($this->getItems($keys))), $option, $depth);
}
/**
* @param string $tagName
* @return \phpFastCache\Cache\ExtendedCacheItemInterface[]
* @throws InvalidArgumentException
*/
public function getItemsByTag($tagName)
{
if (is_string($tagName)) {
$driverResponse = $this->getItem($this->getTagKey($tagName));
if ($driverResponse->isHit()) {
$items = (array) $driverResponse->get();
/**
* getItems() may provides 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($items))), function(ExtendedCacheItemInterface $item){
return $item->isHit();
});
} else {
return [];
}
} else {
throw new InvalidArgumentException('$tagName must be a string');
}
}
/**
* @param array $tagNames
* @return \phpFastCache\Cache\ExtendedCacheItemInterface[]
* @throws InvalidArgumentException
*/
public function getItemsByTags(array $tagNames)
{
$items = [];
foreach (array_unique($tagNames) as $tagName) {
$items = array_merge($items, $this->getItemsByTag($tagName));
}
return $items;
}
/**
* Returns A json string that represents an array of items by tags-based.
*
* @param array $tagNames
* An indexed array of keys of items to retrieve.
* @param int $option json_encode() options
* @param int $depth json_encode() depth
*
* @throws InvalidArgumentException
* If any of the keys in $keys are not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return string
*/
public function getItemsByTagsAsJsonString(array $tagNames, $option = 0, $depth = 512)
{
$callback = function(CacheItemInterface $item){
return $item->get();
};
return json_encode(array_map($callback, array_values($this->getItemsByTags($tagNames))), $option, $depth);
}
/**
* @param string $tagName
* @return bool|null
* @throws InvalidArgumentException
*/
public function deleteItemsByTag($tagName)
{
if (is_string($tagName)) {
$return = null;
foreach ($this->getItemsByTag($tagName) as $item) {
$result = $this->deleteItem($item->getKey());
if ($return !== false) {
$return = $result;
}
}
return $return;
} else {
throw new InvalidArgumentException('$tagName must be a string');
}
}
/**
* @param array $tagNames
* @return bool|null
* @throws InvalidArgumentException
*/
public function deleteItemsByTags(array $tagNames)
{
$return = null;
foreach ($tagNames as $tagName) {
$result = $this->deleteItemsByTag($tagName);
if ($return !== false) {
$return = $result;
}
}
return $return;
}
/**
* @inheritdoc
*/
public function incrementItemsByTag($tagName, $step = 1)
{
if (is_string($tagName) && is_int($step)) {
foreach ($this->getItemsByTag($tagName) as $item) {
$item->increment($step);
$this->saveDeferred($item);
}
return $this->commit();
} else {
throw new InvalidArgumentException('$tagName must be a string and $step an integer');
}
}
/**
* @inheritdoc
*/
public function incrementItemsByTags(array $tagNames, $step = 1)
{
$return = null;
foreach ($tagNames as $tagName) {
$result = $this->incrementItemsByTag($tagName, $step);
if ($return !== false) {
$return = $result;
}
}
return $return;
}
/**
* @inheritdoc
*/
public function decrementItemsByTag($tagName, $step = 1)
{
if (is_string($tagName) && is_int($step)) {
foreach ($this->getItemsByTag($tagName) as $item) {
$item->decrement($step);
$this->saveDeferred($item);
}
return $this->commit();
} else {
throw new InvalidArgumentException('$tagName must be a string and $step an integer');
}
}
/**
* @inheritdoc
*/
public function decrementItemsByTags(array $tagNames, $step = 1)
{
$return = null;
foreach ($tagNames as $tagName) {
$result = $this->decrementItemsByTag($tagName, $step);
if ($return !== false) {
$return = $result;
}
}
return $return;
}
/**
* @inheritdoc
*/
public function appendItemsByTag($tagName, $data)
{
if (is_string($tagName)) {
foreach ($this->getItemsByTag($tagName) as $item) {
$item->append($data);
$this->saveDeferred($item);
}
return $this->commit();
} else {
throw new InvalidArgumentException('$tagName must be a string');
}
}
/**
* @inheritdoc
*/
public function appendItemsByTags(array $tagNames, $data)
{
$return = null;
foreach ($tagNames as $tagName) {
$result = $this->appendItemsByTag($tagName, $data);
if ($return !== false) {
$return = $result;
}
}
return $return;
}
/**
* @inheritdoc
*/
public function prependItemsByTag($tagName, $data)
{
if (is_string($tagName)) {
foreach ($this->getItemsByTag($tagName) as $item) {
$item->prepend($data);
$this->saveDeferred($item);
}
return $this->commit();
} else {
throw new InvalidArgumentException('$tagName must be a string');
}
}
/**
* @inheritdoc
*/
public function prependItemsByTags(array $tagNames, $data)
{
$return = null;
foreach ($tagNames as $tagName) {
$result = $this->prependItemsByTag($tagName, $data);
if ($return !== false) {
$return = $result;
}
}
return $return;
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return void
*/
public function detachItem(CacheItemInterface $item)
{
if(isset($this->itemInstances[$item->getKey()])){
$this->deregisterItem($item);
}
}
/**
* @return void
*/
public function detachAllItems()
{
foreach ($this->itemInstances as $item) {
$this->detachItem($item);
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return void
* @throws \LogicException
*/
public function attachItem(CacheItemInterface $item)
{
if(isset($this->itemInstances[$item->getKey()]) && spl_object_hash($item) !== spl_object_hash($this->itemInstances[ $item->getKey() ])){
throw new \LogicException('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.');
}else{
$this->itemInstances[$item->getKey()] = $item;
}
}
/**
* @internal This method de-register an item from $this->itemInstances
* @param CacheItemInterface|string $item
* @throws \InvalidArgumentException
*/
protected function deregisterItem($item)
{
if($item instanceof CacheItemInterface){
unset($this->itemInstances[ $item->getKey() ]);
}else if(is_string($item)){
unset($this->itemInstances[ $item ]);
}else{
throw new \InvalidArgumentException('Invalid type for $item variable');
}
if(gc_enabled()){
gc_collect_cycles();
}
}
/**
* 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 exists
*
* @param \Psr\Cache\CacheItemInterface $item
* @return bool|null
* @throws \LogicException
*/
public function isAttached(CacheItemInterface $item)
{
if(isset($this->itemInstances[$item->getKey()])){
return spl_object_hash($item) === spl_object_hash($this->itemInstances[ $item->getKey() ]);
}
return null;
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace phpFastCache\Core;
/**
* Trait MemcacheDriverCollisionDetectorTrait
* @package phpFastCache\Core
*/
trait MemcacheDriverCollisionDetectorTrait
{
/**
* @var string
*/
protected static $driverUsed;
/**
* @param $driverName
* @return bool
*/
public static function checkCollision($driverName)
{
$CONSTANT_NAME = __NAMESPACE__ . '\MEMCACHE_DRIVER_USED';
if ($driverName && is_string($driverName)) {
if (!defined($CONSTANT_NAME)) {
define($CONSTANT_NAME, $driverName);
return true;
} else if (constant($CONSTANT_NAME) !== $driverName) {
trigger_error('Memcache collision detected, you used both Memcache and Memcached driver in your script, this may leads to unexpected behaviours',
E_USER_WARNING);
return false;
}
return true;
}
return false;
}
}

View File

@ -0,0 +1,242 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Core;
use phpFastCache\Exceptions\phpFastCacheCoreException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use phpFastCache\Util\Directory;
/**
* Trait PathSeekerTrait
* @package phpFastCache\Core\Pool\IO
* @property array $config The configuration array passed via DriverBaseTrait
*/
trait PathSeekerTrait
{
/**
* @var array
*/
public $tmp = [];
/**
* @param bool $readonly
* @return string
* @throws phpFastCacheDriverException
*/
public function getPath($readonly = false)
{
/**
* Get the base system temporary directory
*/
$tmp_dir = rtrim(ini_get('upload_tmp_dir') ?: sys_get_temp_dir(), '\\/') . DIRECTORY_SEPARATOR . 'phpfastcache';
/**
* Calculate the security key
*/
{
$securityKey = array_key_exists('securityKey', $this->config) ? $this->config[ 'securityKey' ] : '';
if (!$securityKey || $securityKey === 'auto') {
if (isset($_SERVER[ 'HTTP_HOST' ])) {
$securityKey = preg_replace('/^www./', '', strtolower(str_replace(':', '_', $_SERVER[ 'HTTP_HOST' ])));
} else {
$securityKey = ($this->isPHPModule() ? 'web' : 'cli');
}
}
if ($securityKey !== '') {
$securityKey .= '/';
}
$securityKey = static::cleanFileName($securityKey);
}
/**
* Extends the temporary directory
* with the security key and the driver name
*/
$tmp_dir = rtrim($tmp_dir, '/') . DIRECTORY_SEPARATOR;
if (empty($this->config[ 'path' ]) || !is_string($this->config[ 'path' ])) {
$path = $tmp_dir;
} else {
$path = rtrim($this->config[ 'path' ], '/') . DIRECTORY_SEPARATOR;
}
$path_suffix = $securityKey . DIRECTORY_SEPARATOR . $this->getDriverName();
$full_path = Directory::getAbsolutePath($path . $path_suffix);
$full_path_tmp = Directory::getAbsolutePath($tmp_dir . $path_suffix);
$full_path_hash = md5($full_path);
/**
* 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 === true) {
if(!@file_exists($full_path) || !@is_writable($full_path)){
return $full_path_tmp;
}
return $full_path;
}else{
if (!isset($this->tmp[ $full_path_hash ]) || (!@file_exists($full_path) || !@is_writable($full_path))) {
if (!@file_exists($full_path)) {
@mkdir($full_path, $this->setChmodAuto(), true);
}elseif (!@is_writable($full_path)) {
if (!@chmod($full_path, $this->setChmodAuto()))
{
/**
* Switch back to tmp dir
* again if the path is not writable
*/
$full_path = $full_path_tmp;
if (!@file_exists($full_path)) {
@mkdir($full_path, $this->setChmodAuto(), true);
}
}
}
/**
* In case there is no directory
* writable including tye temporary
* one, we must throw an exception
*/
if (!@file_exists($full_path) || !@is_writable($full_path)) {
throw new phpFastCacheDriverException('PLEASE CREATE OR CHMOD ' . $full_path . ' - 0777 OR ANY WRITABLE PERMISSION!');
}
$this->tmp[ $full_path_hash ] = $full_path;
$this->htaccessGen($full_path, array_key_exists('htaccess', $this->config) ? $this->config[ 'htaccess' ] : false);
}
}
return realpath($full_path);
}
/**
* @param $keyword
* @return string
*/
protected function encodeFilename($keyword)
{
return md5($keyword);
}
/**
* @return bool
*/
public function isExpired()
{
trigger_error(__FUNCTION__ . '() is deprecated, use ExtendedCacheItemInterface::isExpired() instead.', E_USER_DEPRECATED);
return true;
}
/**
* @return string
* @throws \phpFastCache\Exceptions\phpFastCacheCoreException
*/
public function getFileDir()
{
return $this->getPath() . DIRECTORY_SEPARATOR . self::FILE_DIR;
}
/**
* @param $keyword
* @param bool $skip
* @return string
* @throws phpFastCacheDriverException
*/
private function getFilePath($keyword, $skip = false)
{
$path = $this->getFileDir();
if ($keyword === false) {
return $path;
}
$filename = $this->encodeFilename($keyword);
$folder = substr($filename, 0, 2);
$path = rtrim($path, '/') . '/' . $folder;
/**
* Skip Create Sub Folders;
*/
if ($skip == false) {
if (!file_exists($path)) {
if (@!mkdir($path, $this->setChmodAuto(), true)) {
throw new phpFastCacheDriverException('PLEASE CHMOD ' . $this->getPath() . ' - ' . $this->setChmodAuto() . ' OR ANY WRITABLE PERMISSION!');
}
}
}
return $path . '/' . $filename . '.txt';
}
/**
* @param $this ->config
* @return int
*/
public function setChmodAuto()
{
if (!isset($this->config[ 'default_chmod' ]) || $this->config[ 'default_chmod' ] == '' || is_null($this->config[ 'default_chmod' ])) {
return 0777;
} else {
return $this->config[ 'default_chmod' ];
}
}
/**
* @param $filename
* @return mixed
*/
protected static function cleanFileName($filename)
{
$regex = [
'/[\?\[\]\/\\\=\<\>\:\;\,\'\"\&\$\#\*\(\)\|\~\`\!\{\}]/',
'/\.$/',
'/^\./',
];
$replace = ['-', '', ''];
return trim(preg_replace($regex, $replace, trim($filename)), '-');
}
/**
* @param $path
* @param bool $create
* @throws \Exception
*/
protected function htaccessGen($path, $create = true)
{
if ($create === true) {
if (!is_writable($path)) {
try {
if(!chmod($path, 0777)){
throw new phpFastCacheDriverException('Chmod failed on : ' . $path);
}
} catch (phpFastCacheDriverException $e) {
throw new phpFastCacheDriverException('PLEASE CHMOD ' . $path . ' - 0777 OR ANY WRITABLE PERMISSION!', 0, $e);
}
}
if (!file_exists($path . "/.htaccess")) {
$html = "order deny, allow \r\n
deny from all \r\n
allow from 127.0.0.1";
$file = @fopen($path . '/.htaccess', 'w+');
if (!$file) {
throw new phpFastCacheDriverException('PLEASE CHMOD ' . $path . ' - 0777 OR ANY WRITABLE PERMISSION!');
}
fwrite($file, $html);
fclose($file);
}
}
}
}

View File

@ -0,0 +1,247 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Core;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\CacheManager;
use phpFastCache\Exceptions\phpFastCacheCoreException;
use Psr\Cache\CacheItemInterface;
/**
* Trait StandardPsr6StructureTrait
* @package phpFastCache\Core
*/
trait StandardPsr6StructureTrait
{
use ClassNamespaceResolverTrait;
/**
* @var array
*/
protected $deferredList = [];
/**
* @var ExtendedCacheItemInterface[]
*/
protected $itemInstances = [];
/**
* @param string $key
* @return \phpFastCache\Cache\ExtendedCacheItemInterface
* @throws \InvalidArgumentException
* @throws phpFastCacheCoreException
*/
public function getItem($key)
{
if (is_string($key)) {
if (!array_key_exists($key, $this->itemInstances)) {
/**
* @var $item ExtendedCacheItemInterface
*/
CacheManager::$ReadHits++;
$class = new \ReflectionClass((new \ReflectionObject($this))->getNamespaceName() . '\Item');
$item = $class->newInstanceArgs([$this, $key]);
$driverArray = $this->driverRead($item);
if ($driverArray) {
if(!is_array($driverArray)){
throw new phpFastCacheCoreException(sprintf('The driverRead method returned an unexpected variable type: %s', gettype($driverArray)));
}
$item->set($this->driverUnwrapData($driverArray));
$item->expiresAt($this->driverUnwrapTime($driverArray));
$item->setTags($this->driverUnwrapTags($driverArray));
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);
} else {
$item->setHit(true);
}
} else {
$item->expiresAfter(abs((int) $this->getConfig()[ 'defaultTtl' ]));
}
}
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
return $this->itemInstances[ $key ];
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return $this
* @throws \InvalidArgumentException
*/
public function setItem(CacheItemInterface $item)
{
if ($this->getClassNamespace() . '\\Item' === get_class($item)) {
$this->itemInstances[ $item->getKey() ] = $item;
return $this;
} else {
throw new \InvalidArgumentException(sprintf('Invalid Item Class "%s" for this driver.', get_class($item)));
}
}
/**
* @param array $keys
* @return CacheItemInterface[]
* @throws \InvalidArgumentException
*/
public function getItems(array $keys = [])
{
$collection = [];
foreach ($keys as $key) {
$collection[ $key ] = $this->getItem($key);
}
return $collection;
}
/**
* @param string $key
* @return bool
* @throws \InvalidArgumentException
*/
public function hasItem($key)
{
CacheManager::$ReadHits++;
return $this->getItem($key)->isHit();
}
/**
* @return bool
*/
public function clear()
{
CacheManager::$WriteHits++;
$this->itemInstances = [];
return $this->driverClear();
}
/**
* @param string $key
* @return bool
* @throws \InvalidArgumentException
*/
public function deleteItem($key)
{
$item = $this->getItem($key);
if ($this->hasItem($key) && $this->driverDelete($item)) {
$item->setHit(false);
CacheManager::$WriteHits++;
/**
* De-register the item instance
* then collect gc cycles
*/
$this->deregisterItem($key);
return true;
}
return false;
}
/**
* @param array $keys
* @return bool
* @throws \InvalidArgumentException
*/
public function deleteItems(array $keys)
{
$return = null;
foreach ($keys as $key) {
$result = $this->deleteItem($key);
if ($result !== false) {
$return = $result;
}
}
return (bool) $return;
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
* @throws \RuntimeException
*/
public function save(CacheItemInterface $item)
{
/**
* @var ExtendedCacheItemInterface $item
*/
if (!array_key_exists($item->getKey(), $this->itemInstances)) {
$this->itemInstances[ $item->getKey() ] = $item;
} else if(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.');
}
if ($this->driverWrite($item) && $this->driverWriteTags($item)) {
$item->setHit(true);
CacheManager::$WriteHits++;
return true;
}
return false;
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return \Psr\Cache\CacheItemInterface
* @throws \RuntimeException
*/
public function saveDeferred(CacheItemInterface $item)
{
if (!array_key_exists($item->getKey(), $this->itemInstances)) {
$this->itemInstances[ $item->getKey() ] = $item;
}else if(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.');
}
return $this->deferredList[ $item->getKey() ] = $item;
}
/**
* @return mixed|null
* @throws \InvalidArgumentException
*/
public function commit()
{
$return = null;
foreach ($this->deferredList as $key => $item) {
$result = $this->save($item);
if ($return !== false) {
unset($this->deferredList[ $key ]);
$return = $result;
}
}
return (bool) $return;
}
}

View File

@ -0,0 +1,143 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Apc;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
}
}
/**
* @return bool
*/
public function driverCheck()
{
if (extension_loaded('apc') && ini_get('apc.enabled')) {
return true;
} else {
return false;
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
$ttl = $item->getExpirationDate()->getTimestamp() - time();
return apc_store($item->getKey(), $this->driverPreWrap($item), ($ttl > 0 ? $ttl : 0));
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
protected function driverRead(CacheItemInterface $item)
{
$data = apc_fetch($item->getKey(), $success);
if ($success === false) {
return null;
}
return $data;
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return apc_delete($item->getKey());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
return @apc_clear_cache() && @apc_clear_cache('user');
}
/**
* @return bool
*/
protected function driverConnect()
{
return true;
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
$stats = (array) apc_cache_info('user');
$date = (new \DateTime())->setTimestamp($stats[ 'start_time' ]);
return (new driverStatistic())
->setData(implode(', ', array_keys($this->itemInstances)))
->setInfo(sprintf("The APC 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($stats[ 'mem_size' ]);
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Apc;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Apc\Driver as ApcDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Apc
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Apc\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(ApcDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof ApcDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -0,0 +1,142 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Apcu;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
}
}
/**
* @return bool
*/
public function driverCheck()
{
if (extension_loaded('apcu') && ini_get('apc.enabled')) {
return true;
} else {
return false;
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
$ttl = $item->getExpirationDate()->getTimestamp() - time();
return apcu_store($item->getKey(), $this->driverPreWrap($item), ($ttl > 0 ? $ttl : 0));
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
protected function driverRead(CacheItemInterface $item)
{
$data = apcu_fetch($item->getKey(), $success);
if ($success === false) {
return null;
}
return $data;
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return apcu_delete($item->getKey());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
return @apcu_clear_cache() && @apcu_clear_cache('user');
}
/**
* @return bool
*/
protected function driverConnect()
{
return true;
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
$stats = (array) apcu_cache_info('user');
$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($stats[ 'mem_size' ]);
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Apcu;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Apcu\Driver as ApcuDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Apcu
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Apcu\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(ApcuDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof ApcuDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Cookie;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
const PREFIX = 'PFC_';
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
}
}
/**
* @return bool
*/
public function driverCheck()
{
if (function_exists('setcookie')) {
return true;
} else {
return false;
}
}
/**
* @return bool
*/
protected function driverConnect()
{
return !(!array_key_exists('phpFastCache', $_COOKIE) && !@setcookie('phpFastCache', 1, 10));
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
$this->driverConnect();
$keyword = self::PREFIX . $item->getKey();
$v = json_encode($this->driverPreWrap($item));
if (isset($this->config[ 'limited_memory_each_object' ]) && strlen($v) > $this->config[ 'limited_memory_each_object' ]) {
return false;
}
return setcookie($keyword, $v, $item->getExpirationDate()->getTimestamp(), '/');
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \phpFastCache\Exceptions\phpFastCacheDriverException
*/
protected function driverRead(CacheItemInterface $item)
{
$this->driverConnect();
// return null if no caching
// return value if in caching
$keyword = self::PREFIX . $item->getKey();
$x = isset($_COOKIE[ $keyword ]) ? json_decode($_COOKIE[ $keyword ], true) : false;
if ($x == false) {
return null;
} else {
if (!is_scalar($this->driverUnwrapData($x)) && !is_null($this->driverUnwrapData($x))) {
throw new phpFastCacheDriverException('Hacking attempt: The decoding returned a non-scalar value, Cookie driver does not allow this.');
}
return $x;
}
}
/**
* @param $key
* @return int
*/
protected function driverReadExpirationDate($key)
{
$this->driverConnect();
$keyword = self::PREFIX . $key;
$x = isset($_COOKIE[ $keyword ]) ? $this->decode(json_decode($_COOKIE[ $keyword ])->t) : false;
return $x ? $x - time() : $x;
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
$this->driverConnect();
$keyword = self::PREFIX . $item->getKey();
$_COOKIE[ $keyword ] = null;
return @setcookie($keyword, null, -10);
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
$return = null;
$this->driverConnect();
foreach ($_COOKIE as $keyword => $value) {
if (strpos($keyword, self::PREFIX) !== false) {
$_COOKIE[ $keyword ] = null;
$result = @setcookie($keyword, null, -10);
if ($return !== false) {
$return = $result;
}
}
}
return $return;
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
$size = 0;
$stat = new driverStatistic();
$stat->setData($_COOKIE);
/**
* Only count PFC Cookie
*/
foreach ($_COOKIE as $key => $value) {
if (strpos($key, self::PREFIX) === 0) {
$size += strlen($value);
}
}
$stat->setSize($size);
return $stat;
}
}

View File

@ -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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Cookie;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Cookie\Driver as CookieDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Apc
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Cookie\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(CookieDriver $driver, $key)
{
if (is_string($key)) {
$this->expirationDate = new \DateTime();
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.',
gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof CookieDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -0,0 +1,199 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Couchbase;
use CouchbaseCluster as CouchbaseClient;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
/**
* @var CouchbaseClient
*/
public $instance;
/**
* @var \CouchbaseBucket[]
*/
protected $bucketInstances = [];
/**
* @var string
*/
protected $bucketCurrent = '';
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
} else {
$this->driverConnect();
}
}
/**
* @return bool
*/
public function driverCheck()
{
return extension_loaded('Couchbase');
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return $this->getBucket()->upsert($item->getKey(), $this->encode($this->driverPreWrap($item)), ['expiry' => $item->getTtl()]);
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
protected function driverRead(CacheItemInterface $item)
{
try {
/**
* CouchbaseBucket::get() returns a CouchbaseMetaDoc object
*/
return $this->decode($this->getBucket()->get($item->getKey())->value);
} catch (\CouchbaseException $e) {
return null;
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return $this->getBucket()->remove($item->getKey());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
return $this->getBucket()->manager()->flush();
}
/**
* @return bool
*/
protected function driverConnect()
{
if ($this->instance instanceof CouchbaseClient) {
throw new \LogicException('Already connected to Couchbase server');
} else {
$host = isset($this->config[ 'host' ]) ? $this->config[ 'host' ] : '127.0.0.1';
//$port = isset($server[ 'port' ]) ? $server[ 'port' ] : '11211';
$password = isset($this->config[ 'password' ]) ? $this->config[ 'password' ] : '';
$username = isset($this->config[ 'username' ]) ? $this->config[ 'username' ] : '';
$buckets = isset($this->config[ 'buckets' ]) ? $this->config[ 'buckets' ] : [
[
'bucket' => 'default',
'password' => '',
],
];
$this->instance = $this->instance ?: new CouchbaseClient("couchbase://{$host}", $username, $password);
foreach ($buckets as $bucket) {
$this->bucketCurrent = $this->bucketCurrent ?: $bucket[ 'bucket' ];
$this->setBucket($bucket[ 'bucket' ], $this->instance->openBucket($bucket[ 'bucket' ], $bucket[ 'password' ]));
}
}
}
/**
* @return \CouchbaseBucket
*/
protected function getBucket()
{
return $this->bucketInstances[ $this->bucketCurrent ];
}
/**
* @param $bucketName
* @param \CouchbaseBucket $CouchbaseBucket
* @throws \LogicException
*/
protected function setBucket($bucketName, \CouchbaseBucket $CouchbaseBucket)
{
if (!array_key_exists($bucketName, $this->bucketInstances)) {
$this->bucketInstances[ $bucketName ] = $CouchbaseBucket;
} else {
throw new \LogicException('A bucket instance with this name already exists.');
}
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
$info = $this->getBucket()->manager()->info();
return (new driverStatistic())
->setSize($info[ 'basicStats' ][ 'diskUsed' ])
->setRawData($info)
->setData(implode(', ', array_keys($this->itemInstances)))
->setInfo('CouchBase version ' . $info[ 'nodes' ][ 0 ][ 'version' ] . ', Uptime (in days): ' . round($info[ 'nodes' ][ 0 ][ 'uptime' ] / 86400, 1) . "\n For more information see RawData.");
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Couchbase;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Couchbase\Driver as CouchbaseDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Apc
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Couchbase\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(CouchbaseDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof CouchbaseDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -0,0 +1,136 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Devfalse;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
}
}
/**
* @return bool
*/
public function driverCheck()
{
return true;
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return true;
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return array [
* 'd' => 'THE ITEM DATA'
* 't' => 'THE ITEM DATE EXPIRATION'
* 'g' => 'THE ITEM TAGS'
* ]
*/
protected function driverRead(CacheItemInterface $item)
{
return [
self::DRIVER_DATA_WRAPPER_INDEX => false,
self::DRIVER_TAGS_WRAPPER_INDEX => [],
self::DRIVER_TIME_WRAPPER_INDEX => new \DateTime(),
];
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return true;
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
return true;
}
/**
* @return bool
*/
protected function driverConnect()
{
return true;
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
$stat = new driverStatistic();
$stat->setInfo('[Devfalse] A void info string')
->setSize(0)
->setData(implode(', ', array_keys($this->itemInstances)))
->setRawData(false);
return $stat;
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Devfalse;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Devnull\Driver as DevnullDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Devnull
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Devnull\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(DevnullDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof DevnullDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -0,0 +1,138 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Devnull;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
}
}
/**
* @return bool
*/
public function driverCheck()
{
return true;
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return true;
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return array [
* 'd' => 'THE ITEM DATA'
* 't' => 'THE ITEM DATE EXPIRATION'
* 'g' => 'THE ITEM TAGS'
* ]
*/
protected function driverRead(CacheItemInterface $item)
{
return [
self::DRIVER_DATA_WRAPPER_INDEX => null,
self::DRIVER_TAGS_WRAPPER_INDEX => [],
self::DRIVER_TIME_WRAPPER_INDEX => new \DateTime(),
];
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return true;
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
return true;
}
/**
* @return bool
*/
protected function driverConnect()
{
return true;
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
$stat = new driverStatistic();
$stat->setInfo('[Devnull] A void info string')
->setSize(0)
->setData(implode(', ', array_keys($this->itemInstances)))
->setRawData(null);
return $stat;
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Devnull;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Devnull\Driver as DevnullDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Devnull
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Devnull\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(DevnullDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof DevnullDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -0,0 +1,138 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Devtrue;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
}
}
/**
* @return bool
*/
public function driverCheck()
{
return true;
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return false;
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return array [
* 'd' => 'THE ITEM DATA'
* 't' => 'THE ITEM DATE EXPIRATION'
* 'g' => 'THE ITEM TAGS'
* ]
*/
protected function driverRead(CacheItemInterface $item)
{
return [
self::DRIVER_DATA_WRAPPER_INDEX => true,
self::DRIVER_TAGS_WRAPPER_INDEX => [],
self::DRIVER_TIME_WRAPPER_INDEX => new \DateTime(),
];
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return false;
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
return false;
}
/**
* @return bool
*/
protected function driverConnect()
{
return false;
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
$stat = new driverStatistic();
$stat->setInfo('[Devtrue] A void info string')
->setSize(0)
->setData(implode(', ', array_keys($this->itemInstances)))
->setRawData(true);
return $stat;
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Devtrue;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Devtrue\Driver as DevtrueDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Devtrue
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Devtrue\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(DevtrueDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof DevtrueDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -0,0 +1,239 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Files;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\PathSeekerTrait;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use phpFastCache\Util\Directory;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
use PathSeekerTrait;
/**
*
*/
const FILE_DIR = 'files';
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
}
}
/**
* @return bool
*/
public function driverCheck()
{
return is_writable($this->getFileDir()) || @mkdir($this->getFileDir(), $this->setChmodAuto(), true);
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
$file_path = $this->getFilePath($item->getKey());
$data = $this->encode($this->driverPreWrap($item));
$toWrite = true;
/**
* Skip if Existing Caching in Options
*/
if (isset($this->config[ 'skipExisting' ]) && $this->config[ 'skipExisting' ] == true && file_exists($file_path)) {
$content = $this->readfile($file_path);
$old = $this->decode($content);
$toWrite = false;
if ($old->isExpired()) {
$toWrite = true;
}
}
/**
* Force write
*/
try {
if ($toWrite == true) {
$f = fopen($file_path, 'w+');
fwrite($f, $data);
fclose($f);
return true;
}
} catch (\Exception $e) {
return false;
}
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
protected function driverRead(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
$file_path = $this->getFilePath($item->getKey());
if (!file_exists($file_path)) {
return null;
}
$content = $this->readfile($file_path);
return $this->decode($content);
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
$file_path = $this->getFilePath($item->getKey(), true);
if (file_exists($file_path) && @unlink($file_path)) {
return true;
} else {
return false;
}
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
return (bool) Directory::rrmdir($this->getPath(true));
}
/**
* @return bool
*/
protected function driverConnect()
{
return true;
}
/**
* @param string $optionName
* @param mixed $optionValue
* @return bool
* @throws \InvalidArgumentException
*/
public static function isValidOption($optionName, $optionValue)
{
parent::isValidOption($optionName, $optionValue);
switch ($optionName) {
case 'path':
return is_string($optionValue);
break;
case 'default_chmod':
return is_numeric($optionValue);
break;
case 'securityKey':
return is_string($optionValue);
break;
case 'htaccess':
return is_bool($optionValue);
break;
default:
return false;
break;
}
}
/**
* @return array
*/
public static function getValidOptions()
{
return ['path', 'default_chmod', 'securityKey', 'htaccess'];
}
/**
* @return array
*/
public static function getRequiredOptions()
{
return ['path'];
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
* @throws \phpFastCache\Exceptions\phpFastCacheCoreException
* @throws \phpFastCache\Exceptions\phpFastCacheDriverException
*/
public function getStats()
{
$stat = new driverStatistic();
$path = $this->getFilePath(false);
if (!is_dir($path)) {
throw new phpFastCacheDriverException("Can't read PATH:" . $path, 94);
}
$stat->setData(implode(', ', array_keys($this->itemInstances)))
->setRawData([])
->setSize(Directory::dirSize($path))
->setInfo('Number of files used to build the cache: ' . Directory::getFileCount($path));
return $stat;
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Files;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Files\Driver as FilesDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Apc
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Files\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(FilesDriver $driver, $key)
{
if (is_string($key)) {
$this->expirationDate = new \DateTime();
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', get_class($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof FilesDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -0,0 +1,177 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Leveldb;
use LevelDB as LeveldbClient;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\PathSeekerTrait;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use phpFastCache\Util\Directory;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
use PathSeekerTrait;
const LEVELDB_FILENAME = '.database';
/**
* @var LeveldbClient Instance of driver service
*/
public $instance;
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
} else {
$this->driverConnect();
}
}
/**
* @return string
* @throws \phpFastCache\Exceptions\phpFastCacheCoreException
*/
public function getLeveldbFile()
{
return $this->getPath() . '/' . self::LEVELDB_FILENAME;
}
/**
* @return bool
*/
public function driverCheck()
{
return extension_loaded('Leveldb');
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return $this->instance->set($item->getKey(), $this->encode($this->driverPreWrap($item)));
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
protected function driverRead(CacheItemInterface $item)
{
$val = $this->instance->get($item->getKey());
if ($val == false) {
return null;
} else {
return $this->decode($val);
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return $this->instance->delete($item->getKey());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
if ($this->instance instanceof LeveldbClient) {
$this->instance->close();
$this->instance = null;
}
$result = LeveldbClient::destroy($this->getLeveldbFile());
$this->driverConnect();
return $result;
}
/**
* @return bool
*/
protected function driverConnect()
{
if ($this->instance instanceof LeveldbClient) {
throw new \LogicException('Already connected to Leveldb database');
} else {
$this->instance = $this->instance ?: new LeveldbClient($this->getLeveldbFile());
}
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
return (new driverStatistic())
->setData(implode(', ', array_keys($this->itemInstances)))
->setInfo('Number of files used to build the cache: ' . Directory::getFileCount($this->getLeveldbFile()))
->setSize(Directory::dirSize($this->getLeveldbFile()));
}
/**
* Close connection on destruct
*/
public function __destruct()
{
if ($this->instance instanceof LeveldbClient) {
$this->instance->close();
$this->instance = null;
}
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Leveldb;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Leveldb\Driver as LeveldbDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Leveldb
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Leveldb\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(LeveldbDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof LeveldbDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -0,0 +1,176 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Memcache;
use Memcache as MemcacheSoftware;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\MemcacheDriverCollisionDetectorTrait;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
use MemcacheDriverCollisionDetectorTrait;
/**
* @var int
*/
protected $memcacheFlags = 0;
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
self::checkCollision('Memcache');
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
} else {
$this->instance = new MemcacheSoftware();
$this->driverConnect();
if (array_key_exists('compress_data', $config) && $config[ 'compress_data' ] === true) {
$this->memcacheFlags = MEMCACHE_COMPRESSED;
}
}
}
/**
* @return bool
*/
public function driverCheck()
{
return class_exists('Memcache');
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return $this->instance->set($item->getKey(), $this->driverPreWrap($item), $this->memcacheFlags, $item->getTtl());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
protected function driverRead(CacheItemInterface $item)
{
$val = $this->instance->get($item->getKey());
if ($val === false) {
return null;
} else {
return $val;
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return $this->instance->delete($item->getKey());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
return $this->instance->flush();
}
/**
* @return bool
*/
protected function driverConnect()
{
$servers = (!empty($this->config[ 'memcache' ]) && is_array($this->config[ 'memcache' ]) ? $this->config[ 'memcache' ] : []);
if (count($servers) < 1) {
$servers = [
['127.0.0.1', 11211],
];
}
foreach ($servers as $server) {
try {
if (!$this->instance->addserver($server[ 0 ], $server[ 1 ])) {
$this->fallback = true;
}
if(!empty($server[ 'sasl_user' ]) && !empty($server[ 'sasl_password'])){
$this->instance->setSaslAuthData($server[ 'sasl_user' ], $server[ 'sasl_password']);
}
} catch (\Exception $e) {
$this->fallback = true;
}
}
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
$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($stats[ 'bytes' ]);
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Memcache;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Memcache\Driver as MemcacheDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Apc
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Memcache\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(MemcacheDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof MemcacheDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -0,0 +1,175 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Memcached;
use Memcached as MemcachedSoftware;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\MemcacheDriverCollisionDetectorTrait;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
use MemcacheDriverCollisionDetectorTrait;
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
self::checkCollision('Memcached');
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
} else {
$this->instance = new MemcachedSoftware();
$this->driverConnect();
}
}
/**
* @return bool
*/
public function driverCheck()
{
return class_exists('Memcached');
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
$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);
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
protected function driverRead(CacheItemInterface $item)
{
$val = $this->instance->get($item->getKey());
if ($val === false) {
return null;
} else {
return $val;
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return $this->instance->delete($item->getKey());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
return $this->instance->flush();
}
/**
* @return bool
*/
protected function driverConnect()
{
$servers = (!empty($this->config[ 'memcache' ]) && is_array($this->config[ 'memcache' ]) ? $this->config[ 'memcache' ] : []);
if (count($servers) < 1) {
$servers = [
['127.0.0.1', 11211],
];
}
foreach ($servers as $server) {
try {
if (!$this->instance->addServer($server[ 0 ], $server[ 1 ])) {
$this->fallback = true;
}
if(!empty($server[ 'sasl_user' ]) && !empty($server[ 'sasl_password'])){
$this->instance->setSaslAuthData($server[ 'sasl_user' ], $server[ 'sasl_password']);
}
} catch (\Exception $e) {
$this->fallback = true;
}
}
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
$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($stats[ 'bytes' ]);
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Memcached;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Memcached\Driver as MemcachedDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Apc
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Memcache\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(MemcachedDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof MemcachedDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -0,0 +1,223 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Mongodb;
use LogicException;
use MongoBinData;
use MongoClient as MongodbClient;
use MongoCollection;
use MongoConnectionException;
use MongoCursorException;
use MongoDate;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
/**
* @var MongodbClient
*/
public $instance;
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
} else {
$this->driverConnect();
}
}
/**
* @return bool
*/
public function driverCheck()
{
if(class_exists('MongoDB\Driver\Manager')){
trigger_error('PhpFastCache currently only support the pecl Mongo extension.<br />
The Support for the MongoDB extension will be added coming soon.', E_USER_ERROR);
}
return extension_loaded('Mongodb') && class_exists('MongoClient');
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
try {
$result = (array) $this->getCollection()->update(
['_id' => $item->getKey()],
[
'$set' => [
self::DRIVER_TIME_WRAPPER_INDEX => ($item->getTtl() > 0 ? new MongoDate(time() + $item->getTtl()) : new MongoDate(time())),
self::DRIVER_DATA_WRAPPER_INDEX => new MongoBinData($this->encode($item->get()), MongoBinData::BYTE_ARRAY),
self::DRIVER_TAGS_WRAPPER_INDEX => new MongoBinData($this->encode($item->getTags()), MongoBinData::BYTE_ARRAY),
],
],
['upsert' => true, 'multiple' => false]
);
} catch (MongoCursorException $e) {
return false;
}
return isset($result[ 'ok' ]) ? $result[ 'ok' ] == 1 : true;
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
protected function driverRead(CacheItemInterface $item)
{
$document = $this->getCollection()
->findOne(['_id' => $item->getKey()],
[self::DRIVER_DATA_WRAPPER_INDEX, self::DRIVER_TIME_WRAPPER_INDEX, self::DRIVER_TAGS_WRAPPER_INDEX /*'d', 'e'*/]);
if ($document) {
return [
self::DRIVER_DATA_WRAPPER_INDEX => $this->decode($document[ self::DRIVER_DATA_WRAPPER_INDEX ]->bin),
self::DRIVER_TIME_WRAPPER_INDEX => (new \DateTime())->setTimestamp($document[ self::DRIVER_TIME_WRAPPER_INDEX ]->sec),
self::DRIVER_TAGS_WRAPPER_INDEX => $this->decode($document[ self::DRIVER_TAGS_WRAPPER_INDEX ]->bin),
];
} else {
return null;
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
$deletionResult = (array) $this->getCollection()->remove(['_id' => $item->getKey()], ["w" => 1]);
return (int) $deletionResult[ 'ok' ] === 1 && !$deletionResult[ 'err' ];
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
return (bool) $this->getCollection()->drop()['ok'];
}
/**
* @return bool
* @throws MongoConnectionException
* @throws LogicException
*/
protected function driverConnect()
{
if ($this->instance instanceof MongodbClient) {
throw new LogicException('Already connected to Mongodb server');
} else {
$host = isset($this->config[ 'host' ]) ? $this->config[ 'host' ] : '127.0.0.1';
$port = isset($this->config[ 'port' ]) ? $this->config[ 'port' ] : '27017';
$timeout = isset($this->config[ 'timeout' ]) ? $this->config[ 'timeout' ] : 3;
$password = isset($this->config[ 'password' ]) ? $this->config[ 'password' ] : '';
$username = isset($this->config[ 'username' ]) ? $this->config[ 'username' ] : '';
/**
* @todo make an url builder
*/
$this->instance = $this->instance ?: (new MongodbClient('mongodb://' .
($username ?: '') .
($password ? ":{$password}" : '') .
($username ? '@' : '') . "{$host}" .
($port != '27017' ? ":{$port}" : ''), ['connectTimeoutMS' => $timeout * 1000]))->phpFastCache;
// $this->instance->Cache->createIndex([self::DRIVER_TIME_WRAPPER_INDEX => 1], ['expireAfterSeconds' => 0]);
}
}
/**
* @return \MongoCollection
*/
protected function getCollection()
{
return $this->instance->Cache;
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
$serverStatus = $this->getCollection()->db->command([
'serverStatus' => 1,
'recordStats' => 0,
'repl' => 0,
'metrics' => 0,
]);
$collStats = $this->getCollection()->db->command([
'collStats' => 'Cache',
'verbose' => true,
]);
$stats = (new driverStatistic())
->setInfo('MongoDB version ' . $serverStatus[ 'version' ] . ', Uptime (in days): ' . round($serverStatus[ 'uptime' ] / 86400, 1) . "\n For more information see RawData.")
->setSize((int) @$collStats[ 'size' ])
->setData(implode(', ', array_keys($this->itemInstances)))
->setRawData([
'serverStatus' => $serverStatus,
'collStats' => $collStats,
]);
return $stats;
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Mongodb;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Mongodb\Driver as MongodbDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Apc
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Mongodb\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(MongodbDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof MongodbDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -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 file.
*
* @author Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Predis;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use Predis\Client as PredisClient;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
/**
* @var PredisClient Instance of driver service
*/
public $instance;
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
} else {
$this->driverConnect();
}
}
/**
* @return bool
*/
public function driverCheck()
{
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');
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
$ttl = $item->getExpirationDate()->getTimestamp() - time();
return $this->instance->setex($item->getKey(), $ttl, $this->encode($this->driverPreWrap($item)));
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
protected function driverRead(CacheItemInterface $item)
{
$val = $this->instance->get($item->getKey());
if ($val == false) {
return null;
} else {
return $this->decode($val);
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return $this->instance->del($item->getKey());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
return $this->instance->flushDB();
}
/**
* @return bool
*/
protected function driverConnect()
{
$config = isset($this->config[ 'predis' ]) ? $this->config[ 'predis' ] : [];
$this->instance = new PredisClient(array_merge([
'host' => '127.0.0.1',
'port' => 6379,
'password' => null,
'database' => null,
], $config));
return true;
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
$info = $this->instance->info();
$size = (isset($info['Memory']['used_memory']) ? $info['Memory']['used_memory'] : 0);
$version = (isset($info['Server']['redis_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($this->instance->info())
->setSize($size)
->setInfo(sprintf("The Redis daemon v%s is up since %s.\n For more information see RawData. \n Driver size includes the memory allocation size.", $version, $date->format(DATE_RFC2822)));
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Predis;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Predis\Driver as PredisDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Apc
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Apc\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(PredisDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof PredisDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -0,0 +1,165 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Redis;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use Psr\Cache\CacheItemInterface;
use Redis as RedisClient;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
} else {
$this->driverConnect();
}
}
/**
* @return bool
*/
public function driverCheck()
{
return extension_loaded('Redis');
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
$ttl = $item->getExpirationDate()->getTimestamp() - time();
return $this->instance->setex($item->getKey(), $ttl, $this->encode($this->driverPreWrap($item)));
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
protected function driverRead(CacheItemInterface $item)
{
$val = $this->instance->get($item->getKey());
if ($val == false) {
return null;
} else {
return $this->decode($val);
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return $this->instance->del($item->getKey());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
return $this->instance->flushDB();
}
/**
* @return bool
*/
protected function driverConnect()
{
if ($this->instance instanceof RedisClient) {
throw new \LogicException('Already connected to Redis server');
} else {
$this->instance = $this->instance ?: new RedisClient();
$host = isset($this->config[ 'host' ]) ? $this->config[ 'host' ] : '127.0.0.1';
$port = isset($this->config[ 'port' ]) ? (int) $this->config[ 'port' ] : '6379';
$password = isset($this->config[ 'password' ]) ? $this->config[ 'password' ] : '';
$database = isset($this->config[ 'database' ]) ? $this->config[ 'database' ] : '';
$timeout = isset($this->config[ 'timeout' ]) ? $this->config[ 'timeout' ] : '';
if (!$this->instance->connect($host, (int) $port, (int) $timeout)) {
return false;
} else {
if ($password && !$this->instance->auth($password)) {
return false;
}
if ($database) {
$this->instance->select((int) $database);
}
return true;
}
}
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
// 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($info[ 'used_memory' ])
->setInfo(sprintf("The Redis daemon v%s is up since %s.\n For more information see RawData. \n Driver size includes the memory allocation size.", $info[ 'redis_version' ], $date->format(DATE_RFC2822)));
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Redis;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Redis\Driver as RedisDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Redis
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Redis\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(RedisDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof RedisDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -0,0 +1,431 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Sqlite;
use PDO;
use PDOException;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\PathSeekerTrait;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use phpFastCache\Util\Directory;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
use PathSeekerTrait;
/**
*
*/
const FILE_DIR = 'sqlite';
/**
*
*/
const INDEXING_FILE = 'indexing';
/**
* @var int
*/
protected $maxSize = 10; // 10 mb
/**
* @var int
*/
protected $currentDB = 1;
/**
* @var string
*/
protected $SqliteDir = '';
/**
* @var \PDO
*/
protected $indexing;
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
} else {
if (!file_exists($this->getSqliteDir()) && !@mkdir($this->getSqliteDir(), $this->setChmodAuto(), true)) {
throw new phpFastCacheDriverException(sprintf('Sqlite cannot write in "%s", aborting...', $this->getPath()));
} else {
$this->driverConnect();
}
}
}
/**
* @return string
* @throws \phpFastCache\Exceptions\phpFastCacheCoreException
*/
public function getSqliteDir()
{
return $this->SqliteDir ?: $this->getPath() . DIRECTORY_SEPARATOR . self::FILE_DIR;
}
/**
* @return bool
*/
public function driverCheck()
{
return extension_loaded('pdo_sqlite') && (is_writable($this->getSqliteDir()) || @mkdir($this->getSqliteDir(), $this->setChmodAuto(), true));
}
/**
* INIT NEW DB
* @param \PDO $db
*/
public function initDB(\PDO $db)
{
$db->exec('drop table if exists "caching"');
$db->exec('CREATE TABLE "caching" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "keyword" VARCHAR UNIQUE, "object" BLOB, "exp" INTEGER)');
$db->exec('CREATE UNIQUE INDEX "cleanup" ON "caching" ("keyword","exp")');
$db->exec('CREATE INDEX "exp" ON "caching" ("exp")');
$db->exec('CREATE UNIQUE INDEX "keyword" ON "caching" ("keyword")');
}
/**
* INIT Indexing DB
* @param \PDO $db
*/
public function initIndexing(\PDO $db)
{
// delete everything before reset indexing
$dir = opendir($this->SqliteDir);
while ($file = readdir($dir)) {
if ($file != '.' && $file != '..' && $file != 'indexing' && $file != 'dbfastcache') {
unlink($this->SqliteDir . '/' . $file);
}
}
$db->exec('drop table if exists "balancing"');
$db->exec('CREATE TABLE "balancing" ("keyword" VARCHAR PRIMARY KEY NOT NULL UNIQUE, "db" INTEGER)');
$db->exec('CREATE INDEX "db" ON "balancing" ("db")');
$db->exec('CREATE UNIQUE INDEX "lookup" ON "balancing" ("keyword")');
}
/**
* INIT Instant DB
* Return Database of Keyword
* @param $keyword
* @return int
*/
public function indexing($keyword)
{
if ($this->indexing == null) {
$createTable = false;
if (!file_exists($this->SqliteDir . '/indexing')) {
$createTable = true;
}
$PDO = new PDO("sqlite:" . $this->SqliteDir . '/' . self::INDEXING_FILE);
$PDO->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
if ($createTable == true) {
$this->initIndexing($PDO);
}
$this->indexing = $PDO;
unset($PDO);
$stm = $this->indexing->prepare("SELECT MAX(`db`) as `db` FROM `balancing`");
$stm->execute();
$row = $stm->fetch(PDO::FETCH_ASSOC);
if (!isset($row[ 'db' ])) {
$db = 1;
} elseif ($row[ 'db' ] <= 1) {
$db = 1;
} else {
$db = $row[ 'db' ];
}
// check file size
$size = file_exists($this->SqliteDir . '/db' . $db) ? filesize($this->SqliteDir . '/db' . $db) : 1;
$size = round($size / 1024 / 1024, 1);
if ($size > $this->maxSize) {
$db++;
}
$this->currentDB = $db;
}
// look for keyword
$stm = $this->indexing->prepare("SELECT * FROM `balancing` WHERE `keyword`=:keyword LIMIT 1");
$stm->execute([
':keyword' => $keyword,
]);
$row = $stm->fetch(PDO::FETCH_ASSOC);
if (isset($row[ 'db' ]) && $row[ 'db' ] != '') {
$db = $row[ 'db' ];
} else {
/*
* Insert new to Indexing
*/
$db = $this->currentDB;
$stm = $this->indexing->prepare("INSERT INTO `balancing` (`keyword`,`db`) VALUES(:keyword, :db)");
$stm->execute([
':keyword' => $keyword,
':db' => $db,
]);
}
return $db;
}
/**
* @param $keyword
* @param bool $reset
* @return PDO
*/
public function getDb($keyword, $reset = false)
{
/**
* Default is fastcache
*/
$instant = $this->indexing($keyword);
/**
* init instant
*/
if (!isset($this->instance[ $instant ])) {
// check DB Files ready or not
$createTable = false;
if (!file_exists($this->SqliteDir . '/db' . $instant) || $reset == true) {
$createTable = true;
}
$PDO = new PDO('sqlite:' . $this->SqliteDir . '/db' . $instant);
$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($createTable == true) {
$this->initDB($PDO);
}
$this->instance[ $instant ] = $PDO;
unset($PDO);
}
return $this->instance[ $instant ];
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
$skipExisting = isset($this->config[ 'skipExisting' ]) ? $this->config[ 'skipExisting' ] : false;
$toWrite = true;
// check in cache first
$in_cache = $this->driverRead($item);
if ($skipExisting == true) {
if ($in_cache == null) {
$toWrite = true;
} else {
$toWrite = false;
}
}
if ($toWrite == true) {
try {
$stm = $this->getDb($item->getKey())
->prepare("INSERT OR REPLACE INTO `caching` (`keyword`,`object`,`exp`) values(:keyword,:object,:exp)");
$stm->execute([
':keyword' => $item->getKey(),
':object' => $this->encode($this->driverPreWrap($item)),
':exp' => time() + $item->getTtl(),
]);
return true;
} catch (\PDOException $e) {
try {
$stm = $this->getDb($item->getKey(), true)
->prepare("INSERT OR REPLACE INTO `caching` (`keyword`,`object`,`exp`) values(:keyword,:object,:exp)");
$stm->execute([
':keyword' => $item->getKey(),
':object' => $this->encode($this->driverPreWrap($item)),
':exp' => time() + $item->getTtl(),
]);
} catch (PDOException $e) {
return false;
}
}
}
return false;
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
protected function driverRead(CacheItemInterface $item)
{
try {
$stm = $this->getDb($item->getKey())
->prepare("SELECT * FROM `caching` WHERE `keyword`=:keyword LIMIT 1");
$stm->execute([
':keyword' => $item->getKey(),
]);
$row = $stm->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
try {
$stm = $this->getDb($item->getKey(), true)
->prepare("SELECT * FROM `caching` WHERE `keyword`=:keyword LIMIT 1");
$stm->execute([
':keyword' => $item->getKey(),
]);
$row = $stm->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
return null;
}
}
if (isset($row[ 'object' ])) {
return $this->decode($row[ 'object' ]);
}
return null;
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
try {
$stm = $this->getDb($item->getKey())
->prepare("DELETE FROM `caching` WHERE (`exp` <= :U) OR (`keyword`=:keyword) ");
return $stm->execute([
':keyword' => $item->getKey(),
':U' => time(),
]);
} catch (PDOException $e) {
return false;
}
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
$this->instance = [];
$this->indexing = null;
// delete everything before reset indexing
$dir = opendir($this->getSqliteDir());
while ($file = readdir($dir)) {
if ($file != '.' && $file != '..') {
unlink($this->getSqliteDir() . '/' . $file);
}
}
return true;
}
/**
* @return bool
*/
protected function driverConnect()
{
if (!file_exists($this->getPath() . '/' . self::FILE_DIR)) {
if (!mkdir($this->getPath() . '/' . self::FILE_DIR, $this->setChmodAuto(), true)
) {
$this->fallback = true;
}
}
$this->SqliteDir = $this->getPath() . '/' . self::FILE_DIR;
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
* @throws PDOException
*/
public function getStats()
{
$stat = new driverStatistic();
$path = $this->getFilePath(false);
if (!is_dir($path)) {
throw new phpFastCacheDriverException("Can't read PATH:" . $path, 94);
}
$stat->setData(implode(', ', array_keys($this->itemInstances)))
->setRawData([])
->setSize(Directory::dirSize($path))
->setInfo('Number of files used to build the cache: ' . Directory::getFileCount($path));
return $stat;
}
/**
* @return array
*/
public function __sleep()
{
return array_diff(array_keys(get_object_vars($this)), ['indexing', 'instance']);
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Sqlite;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Sqlite\Driver as SqliteDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Sqlite
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Sqlite\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(SqliteDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof SqliteDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -0,0 +1,181 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Ssdb;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use phpssdb\Core\SimpleSSDB;
use phpssdb\Core\SSDB;
use phpssdb\Core\SSDBException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
/**
* @var SimpleSSDB
*/
public $instance;
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
} elseif (!$this->driverConnect()) {
throw new phpFastCacheDriverException('Ssdb is not connected, cannot continue.');
}
}
/**
* @return bool
*/
public function driverCheck()
{
static $driverCheck;
if ($driverCheck === null) {
return ($driverCheck = class_exists('phpssdb\Core\SSDB'));
}
return $driverCheck;
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return $this->instance->setx($item->getEncodedKey(), $this->encode($this->driverPreWrap($item)), $item->getTtl());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
protected function driverRead(CacheItemInterface $item)
{
$val = $this->instance->get($item->getEncodedKey());
if ($val == false) {
return null;
} else {
return $this->decode($val);
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return $this->instance->del($item->getEncodedKey());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
return $this->instance->flushdb('kv');
}
/**
* @return bool
* @throws phpFastCacheDriverException
*/
protected function driverConnect()
{
try {
$server = isset($this->config[ 'ssdb' ]) ? $this->config[ 'ssdb' ] : [
'host' => "127.0.0.1",
'port' => 8888,
'password' => '',
'timeout' => 2000,
];
$host = $server[ 'host' ];
$port = isset($server[ 'port' ]) ? (int) $server[ 'port' ] : 8888;
$password = isset($server[ 'password' ]) ? $server[ 'password' ] : '';
$timeout = !empty($server[ 'timeout' ]) ? (int) $server[ 'timeout' ] : 2000;
$this->instance = new SimpleSSDB($host, $port, $timeout);
if (!empty($password)) {
$this->instance->auth($password);
}
if (!$this->instance) {
return false;
} else {
return true;
}
} catch (SSDBException $e) {
throw new phpFastCacheDriverCheckException('Ssdb failed to connect with error: ' . $e->getMessage(), 0, $e);
}
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
$stat = new driverStatistic();
$info = $this->instance->info();
/**
* Data returned by Ssdb are very poorly formatted
* using hardcoded offset of pair key-value :-(
*/
$stat->setInfo(sprintf("Ssdb-server v%s with a total of %s call(s).\n For more information see RawData.", $info[ 2 ], $info[ 6 ]))
->setRawData($info)
->setData(implode(', ', array_keys($this->itemInstances)))
->setSize($this->instance->dbsize());
return $stat;
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Ssdb;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Ssdb\Driver as SsdbDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Ssdb
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Ssdb\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(SsdbDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof SsdbDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -0,0 +1,138 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Wincache;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
}
}
/**
* @return bool
*/
public function driverCheck()
{
return extension_loaded('wincache') && function_exists('wincache_ucache_set');
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return wincache_ucache_set($item->getKey(), $this->driverPreWrap($item), $item->getTtl());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
protected function driverRead(CacheItemInterface $item)
{
$val = wincache_ucache_get($item->getKey(), $suc);
if ($suc === false) {
return null;
} else {
return $val;
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return wincache_ucache_delete($item->getKey());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
return wincache_ucache_clear();
}
/**
* @return bool
*/
protected function driverConnect()
{
return true;
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
$memInfo = wincache_ucache_meminfo();
$info = wincache_ucache_info();
$date = (new \DateTime())->setTimestamp(time() - $info[ 'total_cache_uptime' ]);
return (new driverStatistic())
->setInfo(sprintf("The Wincache daemon is up since %s.\n For more information see RawData.", $date->format(DATE_RFC2822)))
->setSize($memInfo[ 'memory_free' ] - $memInfo[ 'memory_total' ])
->setData(implode(', ', array_keys($this->itemInstances)))
->setRawData($memInfo);
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Wincache;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Wincache\Driver as WincacheDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Wincache
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Wincache\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(WincacheDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof WincacheDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -0,0 +1,148 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Xcache;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
}
}
/**
* @return bool
*/
public function driverCheck()
{
return extension_loaded('xcache') && function_exists('xcache_get');
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return xcache_set($item->getKey(), $this->encode($this->driverPreWrap($item)), $item->getTtl());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
protected function driverRead(CacheItemInterface $item)
{
$data = $this->decode(xcache_get($item->getKey()));
if ($data === false || $data === '') {
return null;
}
return $data;
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return xcache_unset($item->getKey());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
$cnt = xcache_count(XC_TYPE_VAR);
for ($i = 0; $i < $cnt; $i++) {
xcache_clear_cache(XC_TYPE_VAR, $i);
}
return true;
}
/**
* @return bool
*/
protected function driverConnect()
{
return true;
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
if (!ini_get('xcache.admin.enable_auth')) {
$info = xcache_info(XC_TYPE_VAR, 0);
return (new driverStatistic())
->setSize(abs($info[ 'size' ] - $info[ 'avail' ]))
->setData(implode(', ', array_keys($this->itemInstances)))
->setInfo(sprintf("Xcache v%s with following modules loaded:\n %s", XCACHE_VERSION, str_replace(' ', ', ', XCACHE_MODULES)))
->setRawData($info);
} else {
throw new \RuntimeException("PhpFastCache is not able to read Xcache configuration. Please put this to your php.ini:\n
[xcache.admin]
xcache.admin.enable_auth = Off\n
Then reboot your webserver and make sure that the native Xcache ini configuration file does not override your setting.");
}
}
}

View File

@ -0,0 +1,63 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Drivers\Xcache;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Xcache\Driver as XcacheDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Apc
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Xcache\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(XcacheDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof XcacheDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -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 file.
*
* @author Lucas Brucksch <support@hammermaps.de>
*
*/
namespace phpFastCache\Drivers\Zenddisk;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver (zend disk cache)
* Requires Zend Data Cache Functions from ZendServer
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
}
}
/**
* @return bool
*/
public function driverCheck()
{
if (extension_loaded('Zend Data Cache') && function_exists('zend_disk_cache_store')) {
return true;
} else {
return false;
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
$ttl = $item->getExpirationDate()->getTimestamp() - time();
return zend_disk_cache_store($item->getKey(), $this->driverPreWrap($item), ($ttl > 0 ? $ttl : 0));
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
protected function driverRead(CacheItemInterface $item)
{
$data = zend_disk_cache_fetch($item->getKey());
if ($data === false) {
return null;
}
return $data;
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return zend_disk_cache_delete($item->getKey());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
return @zend_disk_cache_clear();
}
/**
* @return bool
*/
protected function driverConnect()
{
return true;
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
$stat = new driverStatistic();
$stat->setInfo('[ZendDisk] A void info string')
->setSize(0)
->setData(implode(', ', array_keys($this->itemInstances)))
->setRawData(false);
return $stat;
}
}

View File

@ -0,0 +1,62 @@
<?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 Lucas Brucksch <support@hammermaps.de>
*
*/
namespace phpFastCache\Drivers\Zenddisk;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Zenddisk\Driver as ZendDiskDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Zenddisk
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Zenddisk\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(ZendDiskDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof ZendDiskDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -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 file.
*
* @author Lucas Brucksch <support@hammermaps.de>
*
*/
namespace phpFastCache\Drivers\Zendshm;
use phpFastCache\Core\DriverAbstract;
use phpFastCache\Core\StandardPsr6StructureTrait;
use phpFastCache\Entities\driverStatistic;
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
use phpFastCache\Exceptions\phpFastCacheDriverException;
use Psr\Cache\CacheItemInterface;
/**
* Class Driver (zend memory cache)
* Requires Zend Data Cache Functions from ZendServer
* @package phpFastCache\Drivers
*/
class Driver extends DriverAbstract
{
/**
* Driver constructor.
* @param array $config
* @throws phpFastCacheDriverException
*/
public function __construct(array $config = [])
{
$this->setup($config);
if (!$this->driverCheck()) {
throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
}
}
/**
* @return bool
*/
public function driverCheck()
{
if (extension_loaded('Zend Data Cache') && function_exists('zend_shm_cache_store')) {
return true;
} else {
return false;
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
* @throws \InvalidArgumentException
*/
protected function driverWrite(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
$ttl = $item->getExpirationDate()->getTimestamp() - time();
return zend_shm_cache_store($item->getKey(), $this->driverPreWrap($item), ($ttl > 0 ? $ttl : 0));
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return mixed
*/
protected function driverRead(CacheItemInterface $item)
{
$data = zend_shm_cache_fetch($item->getKey());
if ($data === false) {
return null;
}
return $data;
}
/**
* @param \Psr\Cache\CacheItemInterface $item
* @return bool
* @throws \InvalidArgumentException
*/
protected function driverDelete(CacheItemInterface $item)
{
/**
* Check for Cross-Driver type confusion
*/
if ($item instanceof Item) {
return zend_shm_cache_delete($item->getKey());
} else {
throw new \InvalidArgumentException('Cross-Driver type confusion detected');
}
}
/**
* @return bool
*/
protected function driverClear()
{
return @zend_shm_cache_clear();
}
/**
* @return bool
*/
protected function driverConnect()
{
return true;
}
/********************
*
* PSR-6 Extended Methods
*
*******************/
/**
* @return driverStatistic
*/
public function getStats()
{
if(function_exists('zend_shm_cache_info')) {
$stats = (array)zend_shm_cache_info();
return (new driverStatistic())
->setData(implode(', ', array_keys($this->itemInstances)))
->setInfo(sprintf("The Zend memory have %d item(s) in cache.\n For more information see RawData.", $stats['items_total']))
->setRawData($stats)
->setSize($stats['memory_total']);
} else {
/** zend_shm_cache_info supported V8 or higher */
return (new driverStatistic())
->setData(implode(', ', array_keys($this->itemInstances)))
->setInfo("The Zend memory statistics is only supported by ZendServer V8 or higher")
->setRawData(null)
->setSize(0);
}
}
}

View File

@ -0,0 +1,62 @@
<?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 Lucas Brucksch <support@hammermaps.de>
*
*/
namespace phpFastCache\Drivers\Zendshm;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\Cache\ExtendedCacheItemPoolInterface;
use phpFastCache\Cache\ItemBaseTrait;
use phpFastCache\Drivers\Zendshm\Driver as ZendSHMDriver;
/**
* Class Item
* @package phpFastCache\Drivers\Zendshm
*/
class Item implements ExtendedCacheItemInterface
{
use ItemBaseTrait;
/**
* Item constructor.
* @param \phpFastCache\Drivers\Zendshm\Driver $driver
* @param $key
* @throws \InvalidArgumentException
*/
public function __construct(ZendSHMDriver $driver, $key)
{
if (is_string($key)) {
$this->key = $key;
$this->driver = $driver;
$this->driver->setItem($this);
$this->expirationDate = new \DateTime();
} else {
throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
}
}
/**
* @param ExtendedCacheItemPoolInterface $driver
* @throws \InvalidArgumentException
* @return static
*/
public function setDriver(ExtendedCacheItemPoolInterface $driver)
{
if ($driver instanceof ZendSHMDriver) {
$this->driver = $driver;
return $this;
} else {
throw new \InvalidArgumentException('Invalid driver instance');
}
}
}

View File

@ -0,0 +1,227 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Entities;
use ArrayAccess;
use InvalidArgumentException;
use LogicException;
/**
* Class driverStatistic
* @package phpFastCache\Entities
*/
class driverStatistic implements ArrayAccess
{
/**
* @var string
*/
protected $info = '';
/**
* @var string
*/
protected $size = 0;
/**
* @var string
*/
protected $data = '';
/**
* @var mixed
*/
protected $rawData;
/**
* @return string|bool Return infos or false if no information available
*/
public function getInfo()
{
return $this->info;
}
/**
* @return int|bool Return size in octet or false if no information available
*/
public function getSize()
{
return $this->size;
}
/**
* @return mixed
*/
public function getData()
{
return $this->data;
}
/**
* @param $info
* @return $this
*/
public function setInfo($info)
{
$this->info = ($info ?: '');
return $this;
}
/**
* @param int $size
* @return $this
*/
public function setSize($size)
{
$this->size = ($size ?: 0);
return $this;
}
/**
* @param mixed $data
* @return $this
*/
public function setData($data)
{
$this->data = ($data ?: '');
return $this;
}
/**
* @return mixed
*/
public function getRawData()
{
return $this->rawData;
}
/**
* @param mixed $raw
* @return $this
*/
public function setRawData($raw)
{
$this->rawData = $raw;
return $this;
}
/**
* @return array
*/
public function getPublicDesc()
{
return[
'Info' => 'Cache Information',
'Size' => 'Cache Size',
'Data' => 'Cache items keys',
'RawData' => 'Cache raw data',
];
}
/*****************
* ArrayAccess
*****************/
/**
* @param string $offset
* @param string $value
* @throws InvalidArgumentException
* @throws LogicException
*/
public function offsetSet($offset, $value)
{
trigger_error($this->getDeprecatedMsg(), E_USER_DEPRECATED);
if (!is_string($offset)) {
throw new InvalidArgumentException('$offset must be a string');
} else {
if (property_exists($this, $offset)) {
$this->{$offset} = $value;
} else {
throw new LogicException("Property {$offset} does not exists");
}
}
}
/**
* @param string $offset
* @return bool
* @throws InvalidArgumentException
* @throws LogicException
*/
public function offsetExists($offset)
{
trigger_error($this->getDeprecatedMsg(), E_USER_DEPRECATED);
if (!is_string($offset)) {
throw new InvalidArgumentException('$offset must be a string');
} else {
if (property_exists($this, $offset)) {
return isset($this->{$offset});
} else {
throw new LogicException("Property {$offset} does not exists");
}
}
}
/**
* @param string $offset
* @throws InvalidArgumentException
* @throws LogicException
*/
public function offsetUnset($offset)
{
trigger_error($this->getDeprecatedMsg(), E_USER_DEPRECATED);
if (!is_string($offset)) {
throw new InvalidArgumentException('$offset must be a string');
} else {
if (property_exists($this, $offset)) {
unset($this->{$offset});
} else {
throw new LogicException("Property {$offset} does not exists");
}
}
}
/**
* @param string $offset
* @return string
* @throws InvalidArgumentException
* @throws LogicException
*/
public function offsetGet($offset)
{
trigger_error($this->getDeprecatedMsg(), E_USER_DEPRECATED);
if (!is_string($offset)) {
throw new InvalidArgumentException('$offset must be a string');
} else {
if (property_exists($this, $offset)) {
return isset($this->{$offset}) ? $this->{$offset} : null;
} else {
throw new LogicException("Property {$offset} does not exists");
}
}
}
/**
* @return string
*/
private function getDeprecatedMsg()
{
return 'You should consider upgrading your code and treat the statistic array as an object.
The arrayAccess compatibility will be removed in the next major release';
}
}

View File

@ -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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Exceptions;
use \Exception;
/**
* Class phpFastCacheCoreException
* @package phpFastCache\Exceptions
*/
class phpFastCacheCoreException extends Exception
{
}

View File

@ -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 file.
*
* @author Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Exceptions;
/**
* Class phpFastCacheDriverCheckException
* @package phpFastCache\Exceptions
*/
class phpFastCacheDriverCheckException extends phpFastCacheDriverException
{
}

View File

@ -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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Exceptions;
use \Exception;
/**
* Class phpFastCacheDriverException
* @package phpFastCache\Exceptions
*/
class phpFastCacheDriverException extends Exception
{
}

View File

@ -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 file.
*
* @author Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Proxy;
use phpFastCache\Cache\ExtendedCacheItemInterface;
use phpFastCache\CacheManager;
use phpFastCache\Entities\driverStatistic;
use Psr\Cache\CacheItemInterface;
/**
* Class phpFastCache
*
* Handle methods using annotations for IDE
* because they're handled by __call()
* Check out ExtendedCacheItemInterface to see all
* the drivers methods magically implemented
*
* @method ExtendedCacheItemInterface getItem($key) Retrieve an item and returns an empty item if not found
* @method ExtendedCacheItemInterface[] getItems(array $keys) Retrieve an item and returns an empty item if not found
* @method bool hasItem() hasItem($key) Tests if an item exists
* @method bool deleteItem(string $key) Delete an item
* @method bool deleteItems(array $keys) Delete some items
* @method bool save(CacheItemInterface $item) Save an item
* @method bool saveDeferred(CacheItemInterface $item) Sets a cache item to be persisted later
* @method bool commit() Persists any deferred cache items
* @method bool clear() Allow you to completely empty the cache and restart from the beginning
* @method driverStatistic stats() Returns a driverStatistic object
* @method ExtendedCacheItemInterface getItemsByTag($tagName) Return items by a tag
* @method ExtendedCacheItemInterface[] getItemsByTags(array $tagNames) Return items by some tags
* @method bool deleteItemsByTag($tagName) Delete items by a tag
* @method bool deleteItemsByTags(array $tagNames) // Delete items by some tags
* @method void incrementItemsByTag($tagName, $step = 1) // Increment items by a tag
* @method void incrementItemsByTags(array $tagNames, $step = 1) // Increment items by some tags
* @method void decrementItemsByTag($tagName, $step = 1) // Decrement items by a tag
* @method void decrementItemsByTags(array $tagNames, $step = 1) // Decrement items by some tags
* @method void appendItemsByTag($tagName, $data) // Append items by a tag
* @method void appendItemsByTags(array $tagNames, $data) // Append items by a tags
* @method void prependItemsByTag($tagName, $data) // Prepend items by a tag
* @method void prependItemsByTags(array $tagNames, $data) // Prepend items by a tags
*/
abstract class phpFastCacheAbstractProxy
{
/**
* @var \phpFastCache\Cache\ExtendedCacheItemPoolInterface
*/
protected $instance;
/**
* phpFastCache constructor.
* @param string $driver
* @param array $config
*/
public function __construct($driver = 'auto', array $config = [])
{
$this->instance = CacheManager::getInstance($driver, $config);
}
/**
* @param $name
* @param $args
* @return mixed
* @throws \BadMethodCallException
*/
public function __call($name, $args)
{
if(method_exists($this->instance, $name)){
return call_user_func_array([$this->instance, $name], $args);
}else{
throw new \BadMethodCallException(sprintf('Method %s does not exists', $name));
}
}
}

View File

@ -0,0 +1,143 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Util;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use SplFileInfo;
/**
* Class Directory
* @package phpFastCache\Util
*/
class Directory
{
/**
* Get the directory size
* @param string $directory
* @param bool $includeDirAllocSize
* @return integer
*/
public static function dirSize($directory, $includeDirAllocSize = false)
{
$size = 0;
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
/**
* @var \SplFileInfo $file
*/
if ($file->isFile()) {
$size += filesize($file->getRealPath());
} else if ($includeDirAllocSize) {
$size += $file->getSize();
}
}
return $size;
}
/**
* @param string $path
* @return int
*/
public static function getFileCount($path)
{
$count = 0;
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::SELF_FIRST);
foreach ($objects as $object) {
/**
* @var \SplFileInfo $object
*/
if ($object->isFile()) {
$count++;
}
}
return $count;
}
/**
* Recursively delete a directory and all of it's contents - e.g.the equivalent of `rm -r` on the command-line.
* Consistent with `rmdir()` and `unlink()`, an E_WARNING level error will be generated on failure.
*
* @param string $source absolute path to directory or file to delete.
* @param bool $removeOnlyChildren set to true will only remove content inside directory.
*
* @return bool true on success; false on failure
*/
public static function rrmdir($source, $removeOnlyChildren = false)
{
if (empty($source) || file_exists($source) === false) {
return false;
}
if (is_file($source) || is_link($source)) {
return unlink($source);
}
$files = new RecursiveIteratorIterator
(
new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $fileinfo) {
/**
* @var SplFileInfo $fileinfo
*/
if ($fileinfo->isDir()) {
if (self::rrmdir($fileinfo->getRealPath()) === false) {
return false;
}
} else if(unlink($fileinfo->getRealPath()) === false) {
return false;
}
}
if ($removeOnlyChildren === false) {
return rmdir($source);
}
return true;
}
/**
* Alias of realpath() but work
* on non-existing files
*
* @param $path
* @return string
*/
public static function getAbsolutePath($path)
{
$parts = preg_split('~[/\\\\]+~', $path, 0, PREG_SPLIT_NO_EMPTY);
$absolutes = [];
foreach ($parts as $part) {
if ('.' === $part) {
continue;
}
if ('..' === $part) {
array_pop($absolutes);
} else {
$absolutes[] = $part;
}
}
/**
* Allows to dereference char
*/
$__FILE__ = preg_replace('~^(([a-z0-9\-]+)://)~', '', __FILE__);// remove file protocols such as "phar://" etc.
$prefix = $__FILE__[0] === DIRECTORY_SEPARATOR ? DIRECTORY_SEPARATOR : '';
return $prefix . implode(DIRECTORY_SEPARATOR, $absolutes);
}
}

View File

@ -0,0 +1,47 @@
<?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 Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
namespace phpFastCache\Util;
use phpFastCache\Exceptions\phpFastCacheCoreException;
/**
* Class Languages
* @author Khoa Bui (khoaofgod) <khoaofgod@gmail.com> http://www.phpfastcache.com
* @author Georges.L (Geolim4) <contact@geolim4.com>
*
*/
class Languages
{
public static function setEncoding($encoding = 'UTF-8', $language = null)
{
if ($language === null || !in_array($language, ['uni', 'Japanese', 'ja', 'English', 'en'], true)) {
$language = 'uni';
}
switch (strtoupper($encoding)) {
case 'UTF-8':
if (extension_loaded("mbstring")) {
mb_internal_encoding($encoding);
mb_http_output($encoding);
mb_http_input($encoding);
mb_language($language);
mb_regex_encoding($encoding);
} else {
throw new phpFastCacheCoreException("MB String need to be installed for Unicode Encoding");
}
break;
}
}
}

View File

@ -0,0 +1 @@
<a href="http://www.phpfastcache.com" title="Simple Php Caching Class">Visit www.phpfastcache.com</a>