reinstall dependencies on php 7.4

This commit is contained in:
Attila Jozsef Kerekes
2022-11-14 21:15:40 +01:00
parent 8972a11c0a
commit 98401f20a2
681 changed files with 65697 additions and 9274 deletions

View File

@@ -49,7 +49,15 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg
$item->key = $key;
$item->value = $v = $value;
$item->isHit = $isHit;
$item->unpack();
// Detect wrapped values that encode for their expiry and creation duration
// For compactness, these values are packed in the key of an array using
// magic numbers in the form 9D-..-..-..-..-00-..-..-..-5F
if (\is_array($v) && 1 === \count($v) && 10 === \strlen($k = (string) array_key_first($v)) && "\x9D" === $k[0] && "\0" === $k[5] && "\x5F" === $k[9]) {
$item->value = $v[$k];
$v = unpack('Ve/Nc', substr($k, 1, -1));
$item->metadata[CacheItem::METADATA_EXPIRY] = $v['e'] + CacheItem::METADATA_EXPIRY_OFFSET;
$item->metadata[CacheItem::METADATA_CTIME] = $v['c'];
}
return $item;
},
@@ -72,7 +80,11 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg
$expiredIds[] = $getId($key);
continue;
}
$byLifetime[$ttl][$getId($key)] = $item->pack();
if (isset(($metadata = $item->newMetadata)[CacheItem::METADATA_TAGS])) {
unset($metadata[CacheItem::METADATA_TAGS]);
}
// For compactness, expiry and creation duration are packed in the key of an array, using magic numbers as separators
$byLifetime[$ttl][$getId($key)] = $metadata ? ["\x9D".pack('VN', (int) (0.1 + $metadata[self::METADATA_EXPIRY] - self::METADATA_EXPIRY_OFFSET), $metadata[self::METADATA_CTIME])."\x5F" => $item->value] : $item->value;
}
return $byLifetime;
@@ -86,8 +98,10 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg
* Returns the best possible adapter that your runtime supports.
*
* Using ApcuAdapter makes system caches compatible with read-only filesystems.
*
* @return AdapterInterface
*/
public static function createSystemCache(string $namespace, int $defaultLifetime, string $version, string $directory, LoggerInterface $logger = null): AdapterInterface
public static function createSystemCache(string $namespace, int $defaultLifetime, string $version, string $directory, LoggerInterface $logger = null)
{
$opcache = new PhpFilesAdapter($namespace, $defaultLifetime, $directory, true);
if (null !== $logger) {
@@ -118,7 +132,7 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg
if (str_starts_with($dsn, 'memcached:')) {
return MemcachedAdapter::createConnection($dsn, $options);
}
if (str_starts_with($dsn, 'couchbase:')) {
if (0 === strpos($dsn, 'couchbase:')) {
if (CouchbaseBucketAdapter::isSupported()) {
return CouchbaseBucketAdapter::createConnection($dsn, $options);
}
@@ -131,11 +145,13 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg
/**
* {@inheritdoc}
*
* @return bool
*/
public function commit(): bool
public function commit()
{
$ok = true;
$byLifetime = (self::$mergeByLifetime)($this->deferred, $this->namespace, $expiredIds, $this->getId(...), $this->defaultLifetime);
$byLifetime = (self::$mergeByLifetime)($this->deferred, $this->namespace, $expiredIds, \Closure::fromCallable([$this, 'getId']), $this->defaultLifetime);
$retry = $this->deferred = [];
if ($expiredIds) {

View File

@@ -56,7 +56,7 @@ abstract class AbstractTagAwareAdapter implements TagAwareAdapterInterface, TagA
$item->isHit = $isHit;
// Extract value, tags and meta data from the cache value
$item->value = $value['value'];
$item->metadata[CacheItem::METADATA_TAGS] = isset($value['tags']) ? array_combine($value['tags'], $value['tags']) : [];
$item->metadata[CacheItem::METADATA_TAGS] = $value['tags'] ?? [];
if (isset($value['meta'])) {
// For compactness these values are packed, & expiry is offset to reduce size
$v = unpack('Ve/Nc', $value['meta']);
@@ -95,19 +95,18 @@ abstract class AbstractTagAwareAdapter implements TagAwareAdapterInterface, TagA
if ($metadata) {
// For compactness, expiry and creation duration are packed, using magic numbers as separators
$value['meta'] = pack('VN', (int) (0.1 + $metadata[CacheItem::METADATA_EXPIRY] - CacheItem::METADATA_EXPIRY_OFFSET), $metadata[CacheItem::METADATA_CTIME]);
$value['meta'] = pack('VN', (int) (0.1 + $metadata[self::METADATA_EXPIRY] - self::METADATA_EXPIRY_OFFSET), $metadata[self::METADATA_CTIME]);
}
// Extract tag changes, these should be removed from values in doSave()
$value['tag-operations'] = ['add' => [], 'remove' => []];
$oldTags = $item->metadata[CacheItem::METADATA_TAGS] ?? [];
foreach (array_diff_key($value['tags'], $oldTags) as $addedTag) {
foreach (array_diff($value['tags'], $oldTags) as $addedTag) {
$value['tag-operations']['add'][] = $getId($tagPrefix.$addedTag);
}
foreach (array_diff_key($oldTags, $value['tags']) as $removedTag) {
foreach (array_diff($oldTags, $value['tags']) as $removedTag) {
$value['tag-operations']['remove'][] = $getId($tagPrefix.$removedTag);
}
$value['tags'] = array_keys($value['tags']);
$byLifetime[$ttl][$getId($key)] = $value;
$item->metadata = $item->newMetadata;
@@ -136,8 +135,10 @@ abstract class AbstractTagAwareAdapter implements TagAwareAdapterInterface, TagA
* Removes multiple items from the pool and their corresponding tags.
*
* @param array $ids An array of identifiers that should be removed from the pool
*
* @return bool
*/
abstract protected function doDelete(array $ids): bool;
abstract protected function doDelete(array $ids);
/**
* Removes relations between tags and deleted items.
@@ -171,7 +172,7 @@ abstract class AbstractTagAwareAdapter implements TagAwareAdapterInterface, TagA
public function commit(): bool
{
$ok = true;
$byLifetime = (self::$mergeByLifetime)($this->deferred, $expiredIds, $this->getId(...), self::TAGS_PREFIX, $this->defaultLifetime);
$byLifetime = (self::$mergeByLifetime)($this->deferred, $expiredIds, \Closure::fromCallable([$this, 'getId']), self::TAGS_PREFIX, $this->defaultLifetime);
$retry = $this->deferred = [];
if ($expiredIds) {
@@ -253,7 +254,7 @@ abstract class AbstractTagAwareAdapter implements TagAwareAdapterInterface, TagA
$tagData[$this->getId(self::TAGS_PREFIX.$tag)][] = $id;
}
}
} catch (\Exception) {
} catch (\Exception $e) {
$ok = false;
}
@@ -261,7 +262,7 @@ abstract class AbstractTagAwareAdapter implements TagAwareAdapterInterface, TagA
if ((!$tagData || $this->doDeleteTagRelations($tagData)) && $ok) {
return true;
}
} catch (\Exception) {
} catch (\Exception $e) {
}
// When bulk-delete failed, retry each item individually
@@ -284,7 +285,7 @@ abstract class AbstractTagAwareAdapter implements TagAwareAdapterInterface, TagA
/**
* {@inheritdoc}
*/
public function invalidateTags(array $tags): bool
public function invalidateTags(array $tags)
{
if (empty($tags)) {
return false;

View File

@@ -26,18 +26,22 @@ interface AdapterInterface extends CacheItemPoolInterface
{
/**
* {@inheritdoc}
*
* @return CacheItem
*/
public function getItem(mixed $key): CacheItem;
public function getItem($key);
/**
* {@inheritdoc}
*
* @return iterable<string, CacheItem>
* @return \Traversable<string, CacheItem>
*/
public function getItems(array $keys = []): iterable;
public function getItems(array $keys = []);
/**
* {@inheritdoc}
*
* @return bool
*/
public function clear(string $prefix = ''): bool;
public function clear(string $prefix = '');
}

View File

@@ -20,7 +20,7 @@ use Symfony\Component\Cache\Marshaller\MarshallerInterface;
*/
class ApcuAdapter extends AbstractAdapter
{
private ?MarshallerInterface $marshaller;
private $marshaller;
/**
* @throws CacheException if APCu is not enabled
@@ -55,12 +55,19 @@ class ApcuAdapter extends AbstractAdapter
/**
* {@inheritdoc}
*/
protected function doFetch(array $ids): iterable
protected function doFetch(array $ids)
{
$unserializeCallbackHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback');
try {
$values = [];
foreach (apcu_fetch($ids, $ok) ?: [] as $k => $v) {
$ids = array_flip($ids);
foreach (apcu_fetch(array_keys($ids), $ok) ?: [] as $k => $v) {
if (!isset($ids[$k])) {
// work around https://github.com/krakjoe/apcu/issues/247
$k = key($ids);
}
unset($ids[$k]);
if (null !== $v || $ok) {
$values[$k] = null !== $this->marshaller ? $this->marshaller->unmarshall($v) : $v;
}
@@ -77,7 +84,7 @@ class ApcuAdapter extends AbstractAdapter
/**
* {@inheritdoc}
*/
protected function doHave(string $id): bool
protected function doHave(string $id)
{
return apcu_exists($id);
}
@@ -85,7 +92,7 @@ class ApcuAdapter extends AbstractAdapter
/**
* {@inheritdoc}
*/
protected function doClear(string $namespace): bool
protected function doClear(string $namespace)
{
return isset($namespace[0]) && class_exists(\APCUIterator::class, false) && ('cli' !== \PHP_SAPI || filter_var(\ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOLEAN))
? apcu_delete(new \APCUIterator(sprintf('/^%s/', preg_quote($namespace, '/')), \APC_ITER_KEY))
@@ -95,7 +102,7 @@ class ApcuAdapter extends AbstractAdapter
/**
* {@inheritdoc}
*/
protected function doDelete(array $ids): bool
protected function doDelete(array $ids)
{
foreach ($ids as $id) {
apcu_delete($id);
@@ -107,7 +114,7 @@ class ApcuAdapter extends AbstractAdapter
/**
* {@inheritdoc}
*/
protected function doSave(array $values, int $lifetime): array|bool
protected function doSave(array $values, int $lifetime)
{
if (null !== $this->marshaller && (!$values = $this->marshaller->marshall($values, $failed))) {
return $failed;

View File

@@ -30,15 +30,14 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
{
use LoggerAwareTrait;
private bool $storeSerialized;
private array $values = [];
private array $tags = [];
private array $expiries = [];
private int $defaultLifetime;
private float $maxLifetime;
private int $maxItems;
private $storeSerialized;
private $values = [];
private $expiries = [];
private $defaultLifetime;
private $maxLifetime;
private $maxItems;
private static \Closure $createCacheItem;
private static $createCacheItem;
/**
* @param bool $storeSerialized Disabling serialization can lead to cache corruptions when storing mutable values but increases performance otherwise
@@ -58,14 +57,11 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
$this->maxLifetime = $maxLifetime;
$this->maxItems = $maxItems;
self::$createCacheItem ?? self::$createCacheItem = \Closure::bind(
static function ($key, $value, $isHit, $tags) {
static function ($key, $value, $isHit) {
$item = new CacheItem();
$item->key = $key;
$item->value = $value;
$item->isHit = $isHit;
if (null !== $tags) {
$item->metadata[CacheItem::METADATA_TAGS] = $tags;
}
return $item;
},
@@ -77,7 +73,7 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
/**
* {@inheritdoc}
*/
public function get(string $key, callable $callback, float $beta = null, array &$metadata = null): mixed
public function get(string $key, callable $callback, float $beta = null, array &$metadata = null)
{
$item = $this->getItem($key);
$metadata = $item->getMetadata();
@@ -104,8 +100,10 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
/**
* {@inheritdoc}
*
* @return bool
*/
public function hasItem(mixed $key): bool
public function hasItem($key)
{
if (\is_string($key) && isset($this->expiries[$key]) && $this->expiries[$key] > microtime(true)) {
if ($this->maxItems) {
@@ -125,7 +123,7 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
/**
* {@inheritdoc}
*/
public function getItem(mixed $key): CacheItem
public function getItem($key)
{
if (!$isHit = $this->hasItem($key)) {
$value = null;
@@ -138,13 +136,13 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
$value = $this->storeSerialized ? $this->unfreeze($key, $isHit) : $this->values[$key];
}
return (self::$createCacheItem)($key, $value, $isHit, $this->tags[$key] ?? null);
return (self::$createCacheItem)($key, $value, $isHit);
}
/**
* {@inheritdoc}
*/
public function getItems(array $keys = []): iterable
public function getItems(array $keys = [])
{
\assert(self::validateKeys($keys));
@@ -153,19 +151,23 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteItem(mixed $key): bool
public function deleteItem($key)
{
\assert('' !== CacheItem::validateKey($key));
unset($this->values[$key], $this->tags[$key], $this->expiries[$key]);
unset($this->values[$key], $this->expiries[$key]);
return true;
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteItems(array $keys): bool
public function deleteItems(array $keys)
{
foreach ($keys as $key) {
$this->deleteItem($key);
@@ -176,8 +178,10 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
/**
* {@inheritdoc}
*
* @return bool
*/
public function save(CacheItemInterface $item): bool
public function save(CacheItemInterface $item)
{
if (!$item instanceof CacheItem) {
return false;
@@ -209,7 +213,7 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
}
if ($this->maxItems) {
unset($this->values[$key], $this->tags[$key]);
unset($this->values[$key]);
// Iterate items and vacuum expired ones while we are at it
foreach ($this->values as $k => $v) {
@@ -217,47 +221,49 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
break;
}
unset($this->values[$k], $this->tags[$k], $this->expiries[$k]);
unset($this->values[$k], $this->expiries[$k]);
}
}
$this->values[$key] = $value;
$this->expiries[$key] = $expiry ?? \PHP_INT_MAX;
if (null === $this->tags[$key] = $item["\0*\0newMetadata"][CacheItem::METADATA_TAGS] ?? null) {
unset($this->tags[$key]);
}
return true;
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function saveDeferred(CacheItemInterface $item): bool
public function saveDeferred(CacheItemInterface $item)
{
return $this->save($item);
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function commit(): bool
public function commit()
{
return true;
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function clear(string $prefix = ''): bool
public function clear(string $prefix = '')
{
if ('' !== $prefix) {
$now = microtime(true);
foreach ($this->values as $key => $value) {
if (!isset($this->expiries[$key]) || $this->expiries[$key] <= $now || str_starts_with($key, $prefix)) {
unset($this->values[$key], $this->tags[$key], $this->expiries[$key]);
if (!isset($this->expiries[$key]) || $this->expiries[$key] <= $now || 0 === strpos($key, $prefix)) {
unset($this->values[$key], $this->expiries[$key]);
}
}
@@ -266,15 +272,17 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
}
}
$this->values = $this->tags = $this->expiries = [];
$this->values = $this->expiries = [];
return true;
}
/**
* Returns all cached values, with cache miss as null.
*
* @return array
*/
public function getValues(): array
public function getValues()
{
if (!$this->storeSerialized) {
return $this->values;
@@ -323,7 +331,7 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
}
unset($keys[$i]);
yield $key => $f($key, $value, $isHit, $this->tags[$key] ?? null);
yield $key => $f($key, $value, $isHit);
}
foreach ($keys as $key) {
@@ -345,7 +353,7 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
try {
$serialized = serialize($value);
} catch (\Exception $e) {
unset($this->values[$key], $this->tags[$key]);
unset($this->values[$key]);
$type = get_debug_type($value);
$message = sprintf('Failed to save key "{key}" of type %s: %s', $type, $e->getMessage());
CacheItem::log($this->logger, $message, ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);

View File

@@ -33,11 +33,11 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
{
use ContractsTrait;
private array $adapters = [];
private int $adapterCount;
private int $defaultLifetime;
private $adapters = [];
private $adapterCount;
private $defaultLifetime;
private static \Closure $syncItem;
private static $syncItem;
/**
* @param CacheItemPoolInterface[] $adapters The ordered list of adapters used to fetch cached items
@@ -66,10 +66,11 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
$this->adapterCount = \count($this->adapters);
$this->defaultLifetime = $defaultLifetime;
self::$syncItem ??= \Closure::bind(
self::$syncItem ?? self::$syncItem = \Closure::bind(
static function ($sourceItem, $item, $defaultLifetime, $sourceMetadata = null) {
$sourceItem->isTaggable = false;
$sourceMetadata ??= $sourceItem->metadata;
$sourceMetadata = $sourceMetadata ?? $sourceItem->metadata;
unset($sourceMetadata[CacheItem::METADATA_TAGS]);
$item->value = $sourceItem->value;
$item->isHit = $sourceItem->isHit;
@@ -91,7 +92,7 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*/
public function get(string $key, callable $callback, float $beta = null, array &$metadata = null): mixed
public function get(string $key, callable $callback, float $beta = null, array &$metadata = null)
{
$doSave = true;
$callback = static function (CacheItem $item, bool &$save) use ($callback, &$doSave) {
@@ -115,7 +116,7 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
$value = $this->doGet($adapter, $key, $callback, $beta, $metadata);
}
if (null !== $item) {
(self::$syncItem)($lastItem ??= $item, $item, $this->defaultLifetime, $metadata);
(self::$syncItem)($lastItem = $lastItem ?? $item, $item, $this->defaultLifetime, $metadata);
}
$save = $doSave;
@@ -128,7 +129,7 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*/
public function getItem(mixed $key): CacheItem
public function getItem($key)
{
$syncItem = self::$syncItem;
$misses = [];
@@ -153,7 +154,7 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*/
public function getItems(array $keys = []): iterable
public function getItems(array $keys = [])
{
return $this->generateItems($this->adapters[0]->getItems($keys), 0);
}
@@ -191,8 +192,10 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*
* @return bool
*/
public function hasItem(mixed $key): bool
public function hasItem($key)
{
foreach ($this->adapters as $adapter) {
if ($adapter->hasItem($key)) {
@@ -205,8 +208,10 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*
* @return bool
*/
public function clear(string $prefix = ''): bool
public function clear(string $prefix = '')
{
$cleared = true;
$i = $this->adapterCount;
@@ -224,8 +229,10 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteItem(mixed $key): bool
public function deleteItem($key)
{
$deleted = true;
$i = $this->adapterCount;
@@ -239,8 +246,10 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteItems(array $keys): bool
public function deleteItems(array $keys)
{
$deleted = true;
$i = $this->adapterCount;
@@ -254,8 +263,10 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*
* @return bool
*/
public function save(CacheItemInterface $item): bool
public function save(CacheItemInterface $item)
{
$saved = true;
$i = $this->adapterCount;
@@ -269,8 +280,10 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*
* @return bool
*/
public function saveDeferred(CacheItemInterface $item): bool
public function saveDeferred(CacheItemInterface $item)
{
$saved = true;
$i = $this->adapterCount;
@@ -284,8 +297,10 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*
* @return bool
*/
public function commit(): bool
public function commit()
{
$committed = true;
$i = $this->adapterCount;
@@ -300,7 +315,7 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*/
public function prune(): bool
public function prune()
{
$pruned = true;

View File

@@ -36,8 +36,8 @@ class CouchbaseBucketAdapter extends AbstractAdapter
'durabilityTimeout',
];
private \CouchbaseBucket $bucket;
private MarshallerInterface $marshaller;
private $bucket;
private $marshaller;
public function __construct(\CouchbaseBucket $bucket, string $namespace = '', int $defaultLifetime = 0, MarshallerInterface $marshaller = null)
{
@@ -54,10 +54,15 @@ class CouchbaseBucketAdapter extends AbstractAdapter
$this->marshaller = $marshaller ?? new DefaultMarshaller();
}
public static function createConnection(array|string $servers, array $options = []): \CouchbaseBucket
/**
* @param array|string $servers
*/
public static function createConnection($servers, array $options = []): \CouchbaseBucket
{
if (\is_string($servers)) {
$servers = [$servers];
} elseif (!\is_array($servers)) {
throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be array or string, "%s" given.', __METHOD__, get_debug_type($servers)));
}
if (!static::isSupported()) {
@@ -77,7 +82,7 @@ class CouchbaseBucketAdapter extends AbstractAdapter
$password = $options['password'];
foreach ($servers as $dsn) {
if (!str_starts_with($dsn, 'couchbase:')) {
if (0 !== strpos($dsn, 'couchbase:')) {
throw new InvalidArgumentException(sprintf('Invalid Couchbase DSN: "%s" does not start with "couchbase:".', $dsn));
}
@@ -159,7 +164,7 @@ class CouchbaseBucketAdapter extends AbstractAdapter
/**
* {@inheritdoc}
*/
protected function doFetch(array $ids): iterable
protected function doFetch(array $ids)
{
$resultsCouchbase = $this->bucket->get($ids);
@@ -216,7 +221,7 @@ class CouchbaseBucketAdapter extends AbstractAdapter
/**
* {@inheritdoc}
*/
protected function doSave(array $values, int $lifetime): array|bool
protected function doSave(array $values, int $lifetime)
{
if (!$values = $this->marshaller->marshall($values, $failed)) {
return $failed;

View File

@@ -29,8 +29,9 @@ class CouchbaseCollectionAdapter extends AbstractAdapter
{
private const MAX_KEY_LENGTH = 250;
private Collection $connection;
private MarshallerInterface $marshaller;
/** @var Collection */
private $connection;
private $marshaller;
public function __construct(Collection $connection, string $namespace = '', int $defaultLifetime = 0, MarshallerInterface $marshaller = null)
{
@@ -47,10 +48,17 @@ class CouchbaseCollectionAdapter extends AbstractAdapter
$this->marshaller = $marshaller ?? new DefaultMarshaller();
}
public static function createConnection(array|string $dsn, array $options = []): Bucket|Collection
/**
* @param array|string $dsn
*
* @return Bucket|Collection
*/
public static function createConnection($dsn, array $options = [])
{
if (\is_string($dsn)) {
$dsn = [$dsn];
} elseif (!\is_array($dsn)) {
throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be array or string, "%s" given.', __METHOD__, get_debug_type($dsn)));
}
if (!static::isSupported()) {
@@ -70,7 +78,7 @@ class CouchbaseCollectionAdapter extends AbstractAdapter
$password = $options['password'] ?? '';
foreach ($dsn as $server) {
if (!str_starts_with($server, 'couchbase:')) {
if (0 !== strpos($server, 'couchbase:')) {
throw new InvalidArgumentException(sprintf('Invalid Couchbase DSN: "%s" does not start with "couchbase:".', $server));
}
@@ -140,7 +148,7 @@ class CouchbaseCollectionAdapter extends AbstractAdapter
foreach ($ids as $id) {
try {
$resultCouchbase = $this->connection->get($id);
} catch (DocumentNotFoundException) {
} catch (DocumentNotFoundException $exception) {
continue;
}
@@ -181,7 +189,7 @@ class CouchbaseCollectionAdapter extends AbstractAdapter
if (null === $result->mutationToken()) {
$idsErrors[] = $id;
}
} catch (DocumentNotFoundException) {
} catch (DocumentNotFoundException $exception) {
}
}
@@ -191,7 +199,7 @@ class CouchbaseCollectionAdapter extends AbstractAdapter
/**
* {@inheritdoc}
*/
protected function doSave(array $values, $lifetime): array|bool
protected function doSave(array $values, $lifetime)
{
if (!$values = $this->marshaller->marshall($values, $failed)) {
return $failed;
@@ -204,7 +212,7 @@ class CouchbaseCollectionAdapter extends AbstractAdapter
foreach ($values as $key => $value) {
try {
$this->connection->upsert($key, $value, $upsertOptions);
} catch (\Exception) {
} catch (\Exception $exception) {
$ko[$key] = '';
}
}

View File

@@ -0,0 +1,110 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Cache\Adapter;
use Doctrine\Common\Cache\CacheProvider;
use Doctrine\Common\Cache\Psr6\CacheAdapter;
/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @deprecated Since Symfony 5.4, use Doctrine\Common\Cache\Psr6\CacheAdapter instead
*/
class DoctrineAdapter extends AbstractAdapter
{
private $provider;
public function __construct(CacheProvider $provider, string $namespace = '', int $defaultLifetime = 0)
{
trigger_deprecation('symfony/cache', '5.4', '"%s" is deprecated, use "%s" instead.', __CLASS__, CacheAdapter::class);
parent::__construct('', $defaultLifetime);
$this->provider = $provider;
$provider->setNamespace($namespace);
}
/**
* {@inheritdoc}
*/
public function reset()
{
parent::reset();
$this->provider->setNamespace($this->provider->getNamespace());
}
/**
* {@inheritdoc}
*/
protected function doFetch(array $ids)
{
$unserializeCallbackHandler = ini_set('unserialize_callback_func', parent::class.'::handleUnserializeCallback');
try {
return $this->provider->fetchMultiple($ids);
} catch (\Error $e) {
$trace = $e->getTrace();
if (isset($trace[0]['function']) && !isset($trace[0]['class'])) {
switch ($trace[0]['function']) {
case 'unserialize':
case 'apcu_fetch':
case 'apc_fetch':
throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine());
}
}
throw $e;
} finally {
ini_set('unserialize_callback_func', $unserializeCallbackHandler);
}
}
/**
* {@inheritdoc}
*/
protected function doHave(string $id)
{
return $this->provider->contains($id);
}
/**
* {@inheritdoc}
*/
protected function doClear(string $namespace)
{
$namespace = $this->provider->getNamespace();
return isset($namespace[0])
? $this->provider->deleteAll()
: $this->provider->flushAll();
}
/**
* {@inheritdoc}
*/
protected function doDelete(array $ids)
{
$ok = true;
foreach ($ids as $id) {
$ok = $this->provider->delete($id) && $ok;
}
return $ok;
}
/**
* {@inheritdoc}
*/
protected function doSave(array $values, int $lifetime)
{
return $this->provider->saveMultiple($values, $lifetime);
}
}

View File

@@ -27,16 +27,16 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
{
protected $maxIdLength = 255;
private MarshallerInterface $marshaller;
private Connection $conn;
private string $platformName;
private string $serverVersion;
private string $table = 'cache_items';
private string $idCol = 'item_id';
private string $dataCol = 'item_data';
private string $lifetimeCol = 'item_lifetime';
private string $timeCol = 'item_time';
private string $namespace;
private $marshaller;
private $conn;
private $platformName;
private $serverVersion;
private $table = 'cache_items';
private $idCol = 'item_id';
private $dataCol = 'item_data';
private $lifetimeCol = 'item_lifetime';
private $timeCol = 'item_time';
private $namespace;
/**
* You can either pass an existing database Doctrine DBAL Connection or
@@ -52,9 +52,11 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
* * db_lifetime_col: The column where to store the lifetime [default: item_lifetime]
* * db_time_col: The column where to store the timestamp [default: item_time]
*
* @param Connection|string $connOrDsn
*
* @throws InvalidArgumentException When namespace contains invalid characters
*/
public function __construct(Connection|string $connOrDsn, string $namespace = '', int $defaultLifetime = 0, array $options = [], MarshallerInterface $marshaller = null)
public function __construct($connOrDsn, string $namespace = '', int $defaultLifetime = 0, array $options = [], MarshallerInterface $marshaller = null)
{
if (isset($namespace[0]) && preg_match('#[^-+.A-Za-z0-9]#', $namespace, $match)) {
throw new InvalidArgumentException(sprintf('Namespace contains "%s" but only characters in [-+.A-Za-z0-9] are allowed.', $match[0]));
@@ -62,11 +64,13 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
if ($connOrDsn instanceof Connection) {
$this->conn = $connOrDsn;
} else {
} elseif (\is_string($connOrDsn)) {
if (!class_exists(DriverManager::class)) {
throw new InvalidArgumentException(sprintf('Failed to parse the DSN "%s". Try running "composer require doctrine/dbal".', $connOrDsn));
}
$this->conn = DriverManager::getConnection(['url' => $connOrDsn]);
} else {
throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be "%s" or string, "%s" given.', __METHOD__, Connection::class, get_debug_type($connOrDsn)));
}
$this->table = $options['db_table'] ?? $this->table;
@@ -88,7 +92,7 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
*
* @throws DBALException When the table already exists
*/
public function createTable(): void
public function createTable()
{
$schema = new Schema();
$this->addTableToSchema($schema);
@@ -132,7 +136,7 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
try {
$this->conn->executeStatement($deleteSql, $params, $paramTypes);
} catch (TableNotFoundException) {
} catch (TableNotFoundException $e) {
}
return true;
@@ -209,7 +213,7 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
try {
$this->conn->executeStatement($sql);
} catch (TableNotFoundException) {
} catch (TableNotFoundException $e) {
}
return true;
@@ -223,7 +227,7 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
$sql = "DELETE FROM $this->table WHERE $this->idCol IN (?)";
try {
$this->conn->executeStatement($sql, [array_values($ids)], [Connection::PARAM_STR_ARRAY]);
} catch (TableNotFoundException) {
} catch (TableNotFoundException $e) {
}
return true;
@@ -232,7 +236,7 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
/**
* {@inheritdoc}
*/
protected function doSave(array $values, int $lifetime): array|bool
protected function doSave(array $values, int $lifetime)
{
if (!$values = $this->marshaller->marshall($values, $failed)) {
return $failed;
@@ -274,7 +278,7 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
$lifetime = $lifetime ?: null;
try {
$stmt = $this->conn->prepare($sql);
} catch (TableNotFoundException) {
} catch (TableNotFoundException $e) {
if (!$this->conn->isTransactionActive() || \in_array($platformName, ['pgsql', 'sqlite', 'sqlsrv'], true)) {
$this->createTable();
}
@@ -312,7 +316,7 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
foreach ($values as $id => $data) {
try {
$rowCount = $stmt->executeStatement();
} catch (TableNotFoundException) {
} catch (TableNotFoundException $e) {
if (!$this->conn->isTransactionActive() || \in_array($platformName, ['pgsql', 'sqlite', 'sqlsrv'], true)) {
$this->createTable();
}
@@ -321,7 +325,7 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
if (null === $platformName && 0 === $rowCount) {
try {
$insertStmt->executeStatement();
} catch (DBALException) {
} catch (DBALException $e) {
// A concurrent write won, let it be
}
}
@@ -338,17 +342,28 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
$platform = $this->conn->getDatabasePlatform();
return match (true) {
$platform instanceof \Doctrine\DBAL\Platforms\MySQLPlatform,
$platform instanceof \Doctrine\DBAL\Platforms\MySQL57Platform => $this->platformName = 'mysql',
$platform instanceof \Doctrine\DBAL\Platforms\SqlitePlatform => $this->platformName = 'sqlite',
$platform instanceof \Doctrine\DBAL\Platforms\PostgreSQLPlatform,
$platform instanceof \Doctrine\DBAL\Platforms\PostgreSQL94Platform => $this->platformName = 'pgsql',
$platform instanceof \Doctrine\DBAL\Platforms\OraclePlatform => $this->platformName = 'oci',
$platform instanceof \Doctrine\DBAL\Platforms\SQLServerPlatform,
$platform instanceof \Doctrine\DBAL\Platforms\SQLServer2012Platform => $this->platformName = 'sqlsrv',
default => $this->platformName = \get_class($platform),
};
switch (true) {
case $platform instanceof \Doctrine\DBAL\Platforms\MySQLPlatform:
case $platform instanceof \Doctrine\DBAL\Platforms\MySQL57Platform:
return $this->platformName = 'mysql';
case $platform instanceof \Doctrine\DBAL\Platforms\SqlitePlatform:
return $this->platformName = 'sqlite';
case $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQLPlatform:
case $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQL94Platform:
return $this->platformName = 'pgsql';
case $platform instanceof \Doctrine\DBAL\Platforms\OraclePlatform:
return $this->platformName = 'oci';
case $platform instanceof \Doctrine\DBAL\Platforms\SQLServerPlatform:
case $platform instanceof \Doctrine\DBAL\Platforms\SQLServer2012Platform:
return $this->platformName = 'sqlsrv';
default:
return $this->platformName = \get_class($platform);
}
}
private function getServerVersion(): string

View File

@@ -44,7 +44,7 @@ class FilesystemTagAwareAdapter extends AbstractTagAwareAdapter implements Prune
/**
* {@inheritdoc}
*/
protected function doClear(string $namespace): bool
protected function doClear(string $namespace)
{
$ok = $this->doClearCache($namespace);
@@ -140,7 +140,7 @@ class FilesystemTagAwareAdapter extends AbstractTagAwareAdapter implements Prune
continue;
}
if (!@unlink($file)) {
if ((\PHP_VERSION_ID >= 70300 || '\\' !== \DIRECTORY_SEPARATOR) && !@unlink($file)) {
fclose($h);
continue;
}
@@ -159,12 +159,16 @@ class FilesystemTagAwareAdapter extends AbstractTagAwareAdapter implements Prune
try {
yield $id => '' === $meta ? [] : $this->marshaller->unmarshall($meta);
} catch (\Exception) {
} catch (\Exception $e) {
yield $id => [];
}
}
fclose($h);
if (\PHP_VERSION_ID < 70300 && '\\' === \DIRECTORY_SEPARATOR) {
@unlink($file);
}
}
}

View File

@@ -39,9 +39,9 @@ class MemcachedAdapter extends AbstractAdapter
\Memcached::OPT_SERIALIZER => \Memcached::SERIALIZER_PHP,
];
private MarshallerInterface $marshaller;
private \Memcached $client;
private \Memcached $lazyClient;
private $marshaller;
private $client;
private $lazyClient;
/**
* Using a MemcachedAdapter with a TagAwareAdapter for storing tags is discouraged.
@@ -90,9 +90,11 @@ class MemcachedAdapter extends AbstractAdapter
*
* @param array[]|string|string[] $servers An array of servers, a DSN, or an array of DSNs
*
* @return \Memcached
*
* @throws \ErrorException When invalid options or servers are provided
*/
public static function createConnection(array|string $servers, array $options = []): \Memcached
public static function createConnection($servers, array $options = [])
{
if (\is_string($servers)) {
$servers = [$servers];
@@ -240,7 +242,7 @@ class MemcachedAdapter extends AbstractAdapter
/**
* {@inheritdoc}
*/
protected function doSave(array $values, int $lifetime): array|bool
protected function doSave(array $values, int $lifetime)
{
if (!$values = $this->marshaller->marshall($values, $failed)) {
return $failed;
@@ -261,7 +263,7 @@ class MemcachedAdapter extends AbstractAdapter
/**
* {@inheritdoc}
*/
protected function doFetch(array $ids): iterable
protected function doFetch(array $ids)
{
try {
$encodedIds = array_map([__CLASS__, 'encodeKey'], $ids);
@@ -282,7 +284,7 @@ class MemcachedAdapter extends AbstractAdapter
/**
* {@inheritdoc}
*/
protected function doHave(string $id): bool
protected function doHave(string $id)
{
return false !== $this->getClient()->get(self::encodeKey($id)) || $this->checkResultCode(\Memcached::RES_SUCCESS === $this->client->getResultCode());
}
@@ -290,7 +292,7 @@ class MemcachedAdapter extends AbstractAdapter
/**
* {@inheritdoc}
*/
protected function doDelete(array $ids): bool
protected function doDelete(array $ids)
{
$ok = true;
$encodedIds = array_map([__CLASS__, 'encodeKey'], $ids);
@@ -306,12 +308,12 @@ class MemcachedAdapter extends AbstractAdapter
/**
* {@inheritdoc}
*/
protected function doClear(string $namespace): bool
protected function doClear(string $namespace)
{
return '' === $namespace && $this->getClient()->flush();
}
private function checkResultCode(mixed $result)
private function checkResultCode($result)
{
$code = $this->client->getResultCode();
@@ -324,7 +326,7 @@ class MemcachedAdapter extends AbstractAdapter
private function getClient(): \Memcached
{
if (isset($this->client)) {
if ($this->client) {
return $this->client;
}

View File

@@ -40,7 +40,7 @@ class NullAdapter implements AdapterInterface, CacheInterface
/**
* {@inheritdoc}
*/
public function get(string $key, callable $callback, float $beta = null, array &$metadata = null): mixed
public function get(string $key, callable $callback, float $beta = null, array &$metadata = null)
{
$save = true;
@@ -50,7 +50,7 @@ class NullAdapter implements AdapterInterface, CacheInterface
/**
* {@inheritdoc}
*/
public function getItem(mixed $key): CacheItem
public function getItem($key)
{
return (self::$createCacheItem)($key);
}
@@ -58,63 +58,77 @@ class NullAdapter implements AdapterInterface, CacheInterface
/**
* {@inheritdoc}
*/
public function getItems(array $keys = []): iterable
public function getItems(array $keys = [])
{
return $this->generateItems($keys);
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function hasItem(mixed $key): bool
public function hasItem($key)
{
return false;
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function clear(string $prefix = ''): bool
public function clear(string $prefix = '')
{
return true;
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteItem(mixed $key): bool
public function deleteItem($key)
{
return true;
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteItems(array $keys): bool
public function deleteItems(array $keys)
{
return true;
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function save(CacheItemInterface $item): bool
public function save(CacheItemInterface $item)
{
return true;
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function saveDeferred(CacheItemInterface $item): bool
public function saveDeferred(CacheItemInterface $item)
{
return true;
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function commit(): bool
public function commit()
{
return true;
}

View File

@@ -12,6 +12,9 @@
namespace Symfony\Component\Cache\Adapter;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema\Schema;
use Psr\Cache\CacheItemInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
use Symfony\Component\Cache\Marshaller\MarshallerInterface;
@@ -21,20 +24,22 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
{
protected $maxIdLength = 255;
private MarshallerInterface $marshaller;
private \PDO|Connection $conn;
private string $dsn;
private string $driver;
private string $serverVersion;
private mixed $table = 'cache_items';
private mixed $idCol = 'item_id';
private mixed $dataCol = 'item_data';
private mixed $lifetimeCol = 'item_lifetime';
private mixed $timeCol = 'item_time';
private mixed $username = '';
private mixed $password = '';
private mixed $connectionOptions = [];
private string $namespace;
private $marshaller;
private $conn;
private $dsn;
private $driver;
private $serverVersion;
private $table = 'cache_items';
private $idCol = 'item_id';
private $dataCol = 'item_data';
private $lifetimeCol = 'item_lifetime';
private $timeCol = 'item_time';
private $username = '';
private $password = '';
private $connectionOptions = [];
private $namespace;
private $dbalAdapter;
/**
* You can either pass an existing database connection as PDO instance or
@@ -51,14 +56,19 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
* * db_password: The password when lazy-connect [default: '']
* * db_connection_options: An array of driver-specific connection options [default: []]
*
* @param \PDO|string $connOrDsn
*
* @throws InvalidArgumentException When first argument is not PDO nor Connection nor string
* @throws InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION
* @throws InvalidArgumentException When namespace contains invalid characters
*/
public function __construct(\PDO|string $connOrDsn, string $namespace = '', int $defaultLifetime = 0, array $options = [], MarshallerInterface $marshaller = null)
public function __construct($connOrDsn, string $namespace = '', int $defaultLifetime = 0, array $options = [], MarshallerInterface $marshaller = null)
{
if (\is_string($connOrDsn) && str_contains($connOrDsn, '://')) {
throw new InvalidArgumentException(sprintf('Usage of Doctrine DBAL URL with "%s" is not supported. Use a PDO DSN or "%s" instead. Got "%s".', __CLASS__, DoctrineDbalAdapter::class, $connOrDsn));
if ($connOrDsn instanceof Connection || (\is_string($connOrDsn) && str_contains($connOrDsn, '://'))) {
trigger_deprecation('symfony/cache', '5.4', 'Usage of a DBAL Connection with "%s" is deprecated and will be removed in symfony 6.0. Use "%s" instead.', __CLASS__, DoctrineDbalAdapter::class);
$this->dbalAdapter = new DoctrineDbalAdapter($connOrDsn, $namespace, $defaultLifetime, $options, $marshaller);
return;
}
if (isset($namespace[0]) && preg_match('#[^-+.A-Za-z0-9]#', $namespace, $match)) {
@@ -71,8 +81,10 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
}
$this->conn = $connOrDsn;
} else {
} elseif (\is_string($connOrDsn)) {
$this->dsn = $connOrDsn;
} else {
throw new InvalidArgumentException(sprintf('"%s" requires PDO or Doctrine\DBAL\Connection instance or DSN string as first argument, "%s" given.', __CLASS__, get_debug_type($connOrDsn)));
}
$this->table = $options['db_table'] ?? $this->table;
@@ -89,6 +101,166 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
parent::__construct($namespace, $defaultLifetime);
}
/**
* {@inheritDoc}
*/
public function getItem($key)
{
if (isset($this->dbalAdapter)) {
return $this->dbalAdapter->getItem($key);
}
return parent::getItem($key);
}
/**
* {@inheritDoc}
*/
public function getItems(array $keys = [])
{
if (isset($this->dbalAdapter)) {
return $this->dbalAdapter->getItems($keys);
}
return parent::getItems($keys);
}
/**
* {@inheritDoc}
*/
public function hasItem($key)
{
if (isset($this->dbalAdapter)) {
return $this->dbalAdapter->hasItem($key);
}
return parent::hasItem($key);
}
/**
* {@inheritDoc}
*/
public function deleteItem($key)
{
if (isset($this->dbalAdapter)) {
return $this->dbalAdapter->deleteItem($key);
}
return parent::deleteItem($key);
}
/**
* {@inheritDoc}
*/
public function deleteItems(array $keys)
{
if (isset($this->dbalAdapter)) {
return $this->dbalAdapter->deleteItems($keys);
}
return parent::deleteItems($keys);
}
/**
* {@inheritDoc}
*/
public function clear(string $prefix = '')
{
if (isset($this->dbalAdapter)) {
return $this->dbalAdapter->clear($prefix);
}
return parent::clear($prefix);
}
/**
* {@inheritDoc}
*/
public function get(string $key, callable $callback, float $beta = null, array &$metadata = null)
{
if (isset($this->dbalAdapter)) {
return $this->dbalAdapter->get($key, $callback, $beta, $metadata);
}
return parent::get($key, $callback, $beta, $metadata);
}
/**
* {@inheritDoc}
*/
public function delete(string $key): bool
{
if (isset($this->dbalAdapter)) {
return $this->dbalAdapter->delete($key);
}
return parent::delete($key);
}
/**
* {@inheritDoc}
*/
public function save(CacheItemInterface $item)
{
if (isset($this->dbalAdapter)) {
return $this->dbalAdapter->save($item);
}
return parent::save($item);
}
/**
* {@inheritDoc}
*/
public function saveDeferred(CacheItemInterface $item)
{
if (isset($this->dbalAdapter)) {
return $this->dbalAdapter->saveDeferred($item);
}
return parent::saveDeferred($item);
}
/**
* {@inheritDoc}
*/
public function setLogger(LoggerInterface $logger): void
{
if (isset($this->dbalAdapter)) {
$this->dbalAdapter->setLogger($logger);
return;
}
parent::setLogger($logger);
}
/**
* {@inheritDoc}
*/
public function commit()
{
if (isset($this->dbalAdapter)) {
return $this->dbalAdapter->commit();
}
return parent::commit();
}
/**
* {@inheritDoc}
*/
public function reset()
{
if (isset($this->dbalAdapter)) {
$this->dbalAdapter->reset();
return;
}
parent::reset();
}
/**
* Creates the table to store cache items which can be called once for setup.
*
@@ -100,31 +272,64 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
*/
public function createTable()
{
if (isset($this->dbalAdapter)) {
$this->dbalAdapter->createTable();
return;
}
// connect if we are not yet
$conn = $this->getConnection();
$sql = match ($this->driver) {
// We use varbinary for the ID column because it prevents unwanted conversions:
// - character set conversions between server and client
// - trailing space removal
// - case-insensitivity
// - language processing like é == e
'mysql' => "CREATE TABLE $this->table ($this->idCol VARBINARY(255) NOT NULL PRIMARY KEY, $this->dataCol MEDIUMBLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB",
'sqlite' => "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)",
'pgsql' => "CREATE TABLE $this->table ($this->idCol VARCHAR(255) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)",
'oci' => "CREATE TABLE $this->table ($this->idCol VARCHAR2(255) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)",
'sqlsrv' => "CREATE TABLE $this->table ($this->idCol VARCHAR(255) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)",
default => throw new \DomainException(sprintf('Creating the cache table is currently not implemented for PDO driver "%s".', $this->driver)),
};
switch ($this->driver) {
case 'mysql':
// We use varbinary for the ID column because it prevents unwanted conversions:
// - character set conversions between server and client
// - trailing space removal
// - case-insensitivity
// - language processing like é == e
$sql = "CREATE TABLE $this->table ($this->idCol VARBINARY(255) NOT NULL PRIMARY KEY, $this->dataCol MEDIUMBLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB";
break;
case 'sqlite':
$sql = "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)";
break;
case 'pgsql':
$sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(255) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)";
break;
case 'oci':
$sql = "CREATE TABLE $this->table ($this->idCol VARCHAR2(255) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)";
break;
case 'sqlsrv':
$sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(255) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)";
break;
default:
throw new \DomainException(sprintf('Creating the cache table is currently not implemented for PDO driver "%s".', $this->driver));
}
$conn->exec($sql);
}
/**
* Adds the Table to the Schema if the adapter uses this Connection.
*
* @deprecated since symfony/cache 5.4 use DoctrineDbalAdapter instead
*/
public function configureSchema(Schema $schema, Connection $forConnection): void
{
if (isset($this->dbalAdapter)) {
$this->dbalAdapter->configureSchema($schema, $forConnection);
}
}
/**
* {@inheritdoc}
*/
public function prune(): bool
public function prune()
{
if (isset($this->dbalAdapter)) {
return $this->dbalAdapter->prune();
}
$deleteSql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol <= :time";
if ('' !== $this->namespace) {
@@ -135,7 +340,7 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
try {
$delete = $connection->prepare($deleteSql);
} catch (\PDOException) {
} catch (\PDOException $e) {
return true;
}
$delete->bindValue(':time', time(), \PDO::PARAM_INT);
@@ -145,7 +350,7 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
}
try {
return $delete->execute();
} catch (\PDOException) {
} catch (\PDOException $e) {
return true;
}
}
@@ -153,7 +358,7 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
/**
* {@inheritdoc}
*/
protected function doFetch(array $ids): iterable
protected function doFetch(array $ids)
{
$connection = $this->getConnection();
@@ -199,7 +404,7 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
/**
* {@inheritdoc}
*/
protected function doHave(string $id): bool
protected function doHave(string $id)
{
$connection = $this->getConnection();
@@ -216,7 +421,7 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
/**
* {@inheritdoc}
*/
protected function doClear(string $namespace): bool
protected function doClear(string $namespace)
{
$conn = $this->getConnection();
@@ -232,7 +437,7 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
try {
$conn->exec($sql);
} catch (\PDOException) {
} catch (\PDOException $e) {
}
return true;
@@ -241,14 +446,14 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
/**
* {@inheritdoc}
*/
protected function doDelete(array $ids): bool
protected function doDelete(array $ids)
{
$sql = str_pad('', (\count($ids) << 1) - 1, '?,');
$sql = "DELETE FROM $this->table WHERE $this->idCol IN ($sql)";
try {
$stmt = $this->getConnection()->prepare($sql);
$stmt->execute(array_values($ids));
} catch (\PDOException) {
} catch (\PDOException $e) {
}
return true;
@@ -257,7 +462,7 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
/**
* {@inheritdoc}
*/
protected function doSave(array $values, int $lifetime): array|bool
protected function doSave(array $values, int $lifetime)
{
if (!$values = $this->marshaller->marshall($values, $failed)) {
return $failed;
@@ -301,7 +506,7 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
$lifetime = $lifetime ?: null;
try {
$stmt = $conn->prepare($sql);
} catch (\PDOException) {
} catch (\PDOException $e) {
if (!$conn->inTransaction() || \in_array($this->driver, ['pgsql', 'sqlite', 'sqlsrv'], true)) {
$this->createTable();
}
@@ -336,7 +541,7 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
foreach ($values as $id => $data) {
try {
$stmt->execute();
} catch (\PDOException) {
} catch (\PDOException $e) {
if (!$conn->inTransaction() || \in_array($this->driver, ['pgsql', 'sqlite', 'sqlsrv'], true)) {
$this->createTable();
}
@@ -345,7 +550,7 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
if (null === $driver && !$stmt->rowCount()) {
try {
$insertStmt->execute();
} catch (\PDOException) {
} catch (\PDOException $e) {
// A concurrent write won, let it be
}
}
@@ -356,17 +561,23 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
private function getConnection(): \PDO
{
if (!isset($this->conn)) {
if (null === $this->conn) {
$this->conn = new \PDO($this->dsn, $this->username, $this->password, $this->connectionOptions);
$this->conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
}
$this->driver ??= $this->conn->getAttribute(\PDO::ATTR_DRIVER_NAME);
if (null === $this->driver) {
$this->driver = $this->conn->getAttribute(\PDO::ATTR_DRIVER_NAME);
}
return $this->conn;
}
private function getServerVersion(): string
{
return $this->serverVersion ??= $this->conn->getAttribute(\PDO::ATTR_SERVER_VERSION);
if (null === $this->serverVersion) {
$this->serverVersion = $this->conn->getAttribute(\PDO::ATTR_SERVER_VERSION);
}
return $this->serverVersion;
}
}

View File

@@ -34,12 +34,12 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
use ContractsTrait;
use ProxyTrait;
private string $file;
private array $keys;
private array $values;
private $file;
private $keys;
private $values;
private static \Closure $createCacheItem;
private static array $valuesCache = [];
private static $createCacheItem;
private static $valuesCache = [];
/**
* @param string $file The PHP file were values are cached
@@ -68,8 +68,10 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
*
* @param string $file The PHP file were values are cached
* @param CacheItemPoolInterface $fallbackPool A pool to fallback on when an item is not hit
*
* @return CacheItemPoolInterface
*/
public static function create(string $file, CacheItemPoolInterface $fallbackPool): CacheItemPoolInterface
public static function create(string $file, CacheItemPoolInterface $fallbackPool)
{
if (!$fallbackPool instanceof AdapterInterface) {
$fallbackPool = new ProxyAdapter($fallbackPool);
@@ -81,9 +83,9 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
/**
* {@inheritdoc}
*/
public function get(string $key, callable $callback, float $beta = null, array &$metadata = null): mixed
public function get(string $key, callable $callback, float $beta = null, array &$metadata = null)
{
if (!isset($this->values)) {
if (null === $this->values) {
$this->initialize();
}
if (!isset($this->keys[$key])) {
@@ -103,7 +105,7 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
if ($value instanceof \Closure) {
return $value();
}
} catch (\Throwable) {
} catch (\Throwable $e) {
unset($this->keys[$key]);
goto get_from_pool;
}
@@ -114,12 +116,12 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
/**
* {@inheritdoc}
*/
public function getItem(mixed $key): CacheItem
public function getItem($key)
{
if (!\is_string($key)) {
throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', get_debug_type($key)));
}
if (!isset($this->values)) {
if (null === $this->values) {
$this->initialize();
}
if (!isset($this->keys[$key])) {
@@ -134,7 +136,7 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
} elseif ($value instanceof \Closure) {
try {
$value = $value();
} catch (\Throwable) {
} catch (\Throwable $e) {
$value = null;
$isHit = false;
}
@@ -146,14 +148,14 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
/**
* {@inheritdoc}
*/
public function getItems(array $keys = []): iterable
public function getItems(array $keys = [])
{
foreach ($keys as $key) {
if (!\is_string($key)) {
throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', get_debug_type($key)));
}
}
if (!isset($this->values)) {
if (null === $this->values) {
$this->initialize();
}
@@ -162,13 +164,15 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
/**
* {@inheritdoc}
*
* @return bool
*/
public function hasItem(mixed $key): bool
public function hasItem($key)
{
if (!\is_string($key)) {
throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', get_debug_type($key)));
}
if (!isset($this->values)) {
if (null === $this->values) {
$this->initialize();
}
@@ -177,13 +181,15 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteItem(mixed $key): bool
public function deleteItem($key)
{
if (!\is_string($key)) {
throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', get_debug_type($key)));
}
if (!isset($this->values)) {
if (null === $this->values) {
$this->initialize();
}
@@ -192,8 +198,10 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteItems(array $keys): bool
public function deleteItems(array $keys)
{
$deleted = true;
$fallbackKeys = [];
@@ -209,7 +217,7 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
$fallbackKeys[] = $key;
}
}
if (!isset($this->values)) {
if (null === $this->values) {
$this->initialize();
}
@@ -222,10 +230,12 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
/**
* {@inheritdoc}
*
* @return bool
*/
public function save(CacheItemInterface $item): bool
public function save(CacheItemInterface $item)
{
if (!isset($this->values)) {
if (null === $this->values) {
$this->initialize();
}
@@ -234,10 +244,12 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
/**
* {@inheritdoc}
*
* @return bool
*/
public function saveDeferred(CacheItemInterface $item): bool
public function saveDeferred(CacheItemInterface $item)
{
if (!isset($this->values)) {
if (null === $this->values) {
$this->initialize();
}
@@ -246,16 +258,20 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
/**
* {@inheritdoc}
*
* @return bool
*/
public function commit(): bool
public function commit()
{
return $this->pool->commit();
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function clear(string $prefix = ''): bool
public function clear(string $prefix = '')
{
$this->keys = $this->values = [];
@@ -276,7 +292,7 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
*
* @return string[] A list of classes to preload on PHP 7.4+
*/
public function warmUp(array $values): array
public function warmUp(array $values)
{
if (file_exists($this->file)) {
if (!is_file($this->file)) {
@@ -401,7 +417,7 @@ EOF;
} elseif ($value instanceof \Closure) {
try {
yield $key => $f($key, $value(), true);
} catch (\Throwable) {
} catch (\Throwable $e) {
yield $key => $f($key, null, false);
}
} else {

View File

@@ -29,13 +29,13 @@ class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
doDelete as private doCommonDelete;
}
private \Closure $includeHandler;
private bool $appendOnly;
private array $values = [];
private array $files = [];
private $includeHandler;
private $appendOnly;
private $values = [];
private $files = [];
private static int $startTime;
private static array $valuesCache = [];
private static $startTime;
private static $valuesCache = [];
/**
* @param $appendOnly Set to `true` to gain extra performance when the items stored in this pool never expire.
@@ -61,7 +61,10 @@ class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
return \function_exists('opcache_invalidate') && filter_var(\ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN) && (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) || filter_var(\ini_get('opcache.enable_cli'), \FILTER_VALIDATE_BOOLEAN));
}
public function prune(): bool
/**
* @return bool
*/
public function prune()
{
$time = time();
$pruned = true;
@@ -92,7 +95,7 @@ class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
/**
* {@inheritdoc}
*/
protected function doFetch(array $ids): iterable
protected function doFetch(array $ids)
{
if ($this->appendOnly) {
$now = 0;
@@ -135,7 +138,7 @@ class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
foreach ($missingIds as $k => $id) {
try {
$file = $this->files[$id] ??= $this->getFile($id);
$file = $this->files[$id] ?? $this->files[$id] = $this->getFile($id);
if (isset(self::$valuesCache[$file])) {
[$expiresAt, $this->values[$id]] = self::$valuesCache[$file];
@@ -168,7 +171,7 @@ class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
/**
* {@inheritdoc}
*/
protected function doHave(string $id): bool
protected function doHave(string $id)
{
if ($this->appendOnly && isset($this->values[$id])) {
return true;
@@ -176,7 +179,7 @@ class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
set_error_handler($this->includeHandler);
try {
$file = $this->files[$id] ??= $this->getFile($id);
$file = $this->files[$id] ?? $this->files[$id] = $this->getFile($id);
$getExpiry = true;
if (isset(self::$valuesCache[$file])) {
@@ -190,7 +193,7 @@ class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
} elseif ($this->appendOnly) {
$value = new LazyValue($file);
}
} catch (\ErrorException) {
} catch (\ErrorException $e) {
return false;
} finally {
restore_error_handler();
@@ -208,7 +211,7 @@ class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
/**
* {@inheritdoc}
*/
protected function doSave(array $values, int $lifetime): array|bool
protected function doSave(array $values, int $lifetime)
{
$ok = true;
$expiry = $lifetime ? time() + $lifetime : 'PHP_INT_MAX';
@@ -270,7 +273,7 @@ class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
/**
* {@inheritdoc}
*/
protected function doClear(string $namespace): bool
protected function doClear(string $namespace)
{
$this->values = [];
@@ -280,7 +283,7 @@ class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
/**
* {@inheritdoc}
*/
protected function doDelete(array $ids): bool
protected function doDelete(array $ids)
{
foreach ($ids as $id) {
unset($this->values[$id]);
@@ -318,7 +321,7 @@ class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
*/
class LazyValue
{
public string $file;
public $file;
public function __construct(string $file)
{

View File

@@ -28,25 +28,25 @@ class ProxyAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
use ContractsTrait;
use ProxyTrait;
private string $namespace = '';
private int $namespaceLen;
private string $poolHash;
private int $defaultLifetime;
private $namespace = '';
private $namespaceLen;
private $poolHash;
private $defaultLifetime;
private static \Closure $createCacheItem;
private static \Closure $setInnerItem;
private static $createCacheItem;
private static $setInnerItem;
public function __construct(CacheItemPoolInterface $pool, string $namespace = '', int $defaultLifetime = 0)
{
$this->pool = $pool;
$this->poolHash = spl_object_hash($pool);
$this->poolHash = $poolHash = spl_object_hash($pool);
if ('' !== $namespace) {
\assert('' !== CacheItem::validateKey($namespace));
$this->namespace = $namespace;
}
$this->namespaceLen = \strlen($namespace);
$this->defaultLifetime = $defaultLifetime;
self::$createCacheItem ??= \Closure::bind(
self::$createCacheItem ?? self::$createCacheItem = \Closure::bind(
static function ($key, $innerItem, $poolHash) {
$item = new CacheItem();
$item->key = $key;
@@ -55,12 +55,20 @@ class ProxyAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
return $item;
}
$item->value = $innerItem->get();
$item->value = $v = $innerItem->get();
$item->isHit = $innerItem->isHit();
$item->innerItem = $innerItem;
$item->poolHash = $poolHash;
if (!$item->unpack() && $innerItem instanceof CacheItem) {
// Detect wrapped values that encode for their expiry and creation duration
// For compactness, these values are packed in the key of an array using
// magic numbers in the form 9D-..-..-..-..-00-..-..-..-5F
if (\is_array($v) && 1 === \count($v) && 10 === \strlen($k = (string) array_key_first($v)) && "\x9D" === $k[0] && "\0" === $k[5] && "\x5F" === $k[9]) {
$item->value = $v[$k];
$v = unpack('Ve/Nc', substr($k, 1, -1));
$item->metadata[CacheItem::METADATA_EXPIRY] = $v['e'] + CacheItem::METADATA_EXPIRY_OFFSET;
$item->metadata[CacheItem::METADATA_CTIME] = $v['c'];
} elseif ($innerItem instanceof CacheItem) {
$item->metadata = $innerItem->metadata;
}
$innerItem->set(null);
@@ -70,10 +78,21 @@ class ProxyAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
null,
CacheItem::class
);
self::$setInnerItem ??= \Closure::bind(
static function (CacheItemInterface $innerItem, CacheItem $item, $expiry = null) {
$innerItem->set($item->pack());
$innerItem->expiresAt(($expiry ?? $item->expiry) ? \DateTime::createFromFormat('U.u', sprintf('%.6F', $expiry ?? $item->expiry)) : null);
self::$setInnerItem ?? self::$setInnerItem = \Closure::bind(
/**
* @param array $item A CacheItem cast to (array); accessing protected properties requires adding the "\0*\0" PHP prefix
*/
static function (CacheItemInterface $innerItem, array $item) {
// Tags are stored separately, no need to account for them when considering this item's newly set metadata
if (isset(($metadata = $item["\0*\0newMetadata"])[CacheItem::METADATA_TAGS])) {
unset($metadata[CacheItem::METADATA_TAGS]);
}
if ($metadata) {
// For compactness, expiry and creation duration are packed in the key of an array, using magic numbers as separators
$item["\0*\0value"] = ["\x9D".pack('VN', (int) (0.1 + $metadata[self::METADATA_EXPIRY] - self::METADATA_EXPIRY_OFFSET), $metadata[self::METADATA_CTIME])."\x5F" => $item["\0*\0value"]];
}
$innerItem->set($item["\0*\0value"]);
$innerItem->expiresAt(null !== $item["\0*\0expiry"] ? \DateTime::createFromFormat('U.u', sprintf('%.6F', $item["\0*\0expiry"])) : null);
},
null,
CacheItem::class
@@ -83,7 +102,7 @@ class ProxyAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*/
public function get(string $key, callable $callback, float $beta = null, array &$metadata = null): mixed
public function get(string $key, callable $callback, float $beta = null, array &$metadata = null)
{
if (!$this->pool instanceof CacheInterface) {
return $this->doGet($this, $key, $callback, $beta, $metadata);
@@ -92,7 +111,7 @@ class ProxyAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
return $this->pool->get($this->getId($key), function ($innerItem, bool &$save) use ($key, $callback) {
$item = (self::$createCacheItem)($key, $innerItem, $this->poolHash);
$item->set($value = $callback($item, $save));
(self::$setInnerItem)($innerItem, $item);
(self::$setInnerItem)($innerItem, (array) $item);
return $value;
}, $beta, $metadata);
@@ -101,7 +120,7 @@ class ProxyAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*/
public function getItem(mixed $key): CacheItem
public function getItem($key)
{
$item = $this->pool->getItem($this->getId($key));
@@ -111,7 +130,7 @@ class ProxyAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*/
public function getItems(array $keys = []): iterable
public function getItems(array $keys = [])
{
if ($this->namespaceLen) {
foreach ($keys as $i => $key) {
@@ -124,16 +143,20 @@ class ProxyAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*
* @return bool
*/
public function hasItem(mixed $key): bool
public function hasItem($key)
{
return $this->pool->hasItem($this->getId($key));
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function clear(string $prefix = ''): bool
public function clear(string $prefix = '')
{
if ($this->pool instanceof AdapterInterface) {
return $this->pool->clear($this->namespace.$prefix);
@@ -144,16 +167,20 @@ class ProxyAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteItem(mixed $key): bool
public function deleteItem($key)
{
return $this->pool->deleteItem($this->getId($key));
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteItems(array $keys): bool
public function deleteItems(array $keys)
{
if ($this->namespaceLen) {
foreach ($keys as $i => $key) {
@@ -166,50 +193,55 @@ class ProxyAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
/**
* {@inheritdoc}
*
* @return bool
*/
public function save(CacheItemInterface $item): bool
public function save(CacheItemInterface $item)
{
return $this->doSave($item, __FUNCTION__);
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function saveDeferred(CacheItemInterface $item): bool
public function saveDeferred(CacheItemInterface $item)
{
return $this->doSave($item, __FUNCTION__);
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function commit(): bool
public function commit()
{
return $this->pool->commit();
}
private function doSave(CacheItemInterface $item, string $method): bool
private function doSave(CacheItemInterface $item, string $method)
{
if (!$item instanceof CacheItem) {
return false;
}
$castItem = (array) $item;
if (null === $castItem["\0*\0expiry"] && 0 < $this->defaultLifetime) {
$castItem["\0*\0expiry"] = microtime(true) + $this->defaultLifetime;
$item = (array) $item;
if (null === $item["\0*\0expiry"] && 0 < $this->defaultLifetime) {
$item["\0*\0expiry"] = microtime(true) + $this->defaultLifetime;
}
if ($castItem["\0*\0poolHash"] === $this->poolHash && $castItem["\0*\0innerItem"]) {
$innerItem = $castItem["\0*\0innerItem"];
if ($item["\0*\0poolHash"] === $this->poolHash && $item["\0*\0innerItem"]) {
$innerItem = $item["\0*\0innerItem"];
} elseif ($this->pool instanceof AdapterInterface) {
// this is an optimization specific for AdapterInterface implementations
// so we can save a round-trip to the backend by just creating a new item
$innerItem = (self::$createCacheItem)($this->namespace.$castItem["\0*\0key"], null, $this->poolHash);
$innerItem = (self::$createCacheItem)($this->namespace.$item["\0*\0key"], null, $this->poolHash);
} else {
$innerItem = $this->pool->getItem($this->namespace.$castItem["\0*\0key"]);
$innerItem = $this->pool->getItem($this->namespace.$item["\0*\0key"]);
}
(self::$setInnerItem)($innerItem, $item, $castItem["\0*\0expiry"]);
(self::$setInnerItem)($innerItem, $item);
return $this->pool->$method($innerItem);
}
@@ -227,7 +259,7 @@ class ProxyAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
}
}
private function getId(mixed $key): string
private function getId($key): string
{
\assert('' !== CacheItem::validateKey($key));

View File

@@ -30,7 +30,7 @@ class Psr16Adapter extends AbstractAdapter implements PruneableInterface, Resett
*/
protected const NS_SEPARATOR = '_';
private object $miss;
private $miss;
public function __construct(CacheInterface $pool, string $namespace = '', int $defaultLifetime = 0)
{
@@ -43,7 +43,7 @@ class Psr16Adapter extends AbstractAdapter implements PruneableInterface, Resett
/**
* {@inheritdoc}
*/
protected function doFetch(array $ids): iterable
protected function doFetch(array $ids)
{
foreach ($this->pool->getMultiple($ids, $this->miss) as $key => $value) {
if ($this->miss !== $value) {
@@ -55,7 +55,7 @@ class Psr16Adapter extends AbstractAdapter implements PruneableInterface, Resett
/**
* {@inheritdoc}
*/
protected function doHave(string $id): bool
protected function doHave(string $id)
{
return $this->pool->has($id);
}
@@ -63,7 +63,7 @@ class Psr16Adapter extends AbstractAdapter implements PruneableInterface, Resett
/**
* {@inheritdoc}
*/
protected function doClear(string $namespace): bool
protected function doClear(string $namespace)
{
return $this->pool->clear();
}
@@ -71,7 +71,7 @@ class Psr16Adapter extends AbstractAdapter implements PruneableInterface, Resett
/**
* {@inheritdoc}
*/
protected function doDelete(array $ids): bool
protected function doDelete(array $ids)
{
return $this->pool->deleteMultiple($ids);
}
@@ -79,7 +79,7 @@ class Psr16Adapter extends AbstractAdapter implements PruneableInterface, Resett
/**
* {@inheritdoc}
*/
protected function doSave(array $values, int $lifetime): array|bool
protected function doSave(array $values, int $lifetime)
{
return $this->pool->setMultiple($values, 0 === $lifetime ? null : $lifetime);
}

View File

@@ -20,7 +20,12 @@ class RedisAdapter extends AbstractAdapter
{
use RedisTrait;
public function __construct(\Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy $redis, string $namespace = '', int $defaultLifetime = 0, MarshallerInterface $marshaller = null)
/**
* @param \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy $redis The redis client
* @param string $namespace The default namespace
* @param int $defaultLifetime The default lifetime
*/
public function __construct($redis, string $namespace = '', int $defaultLifetime = 0, MarshallerInterface $marshaller = null)
{
$this->init($redis, $namespace, $defaultLifetime, $marshaller);
}

View File

@@ -56,12 +56,17 @@ class RedisTagAwareAdapter extends AbstractTagAwareAdapter
private const DEFAULT_CACHE_TTL = 8640000;
/**
* detected eviction policy used on Redis server.
* @var string|null detected eviction policy used on Redis server
*/
private string $redisEvictionPolicy;
private string $namespace;
private $redisEvictionPolicy;
private $namespace;
public function __construct(\Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy $redis, string $namespace = '', int $defaultLifetime = 0, MarshallerInterface $marshaller = null)
/**
* @param \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy $redis The redis client
* @param string $namespace The default namespace
* @param int $defaultLifetime The default lifetime
*/
public function __construct($redis, string $namespace = '', int $defaultLifetime = 0, MarshallerInterface $marshaller = null)
{
if ($redis instanceof \Predis\ClientInterface && $redis->getConnection() instanceof ClusterInterface && !$redis->getConnection() instanceof PredisCluster) {
throw new InvalidArgumentException(sprintf('Unsupported Predis cluster connection: only "%s" is, "%s" given.', PredisCluster::class, get_debug_type($redis->getConnection())));
@@ -170,7 +175,7 @@ EOLUA;
try {
yield $id => !\is_string($result) || '' === $result ? [] : $this->marshaller->unmarshall($result);
} catch (\Exception) {
} catch (\Exception $e) {
yield $id => [];
}
}
@@ -292,7 +297,7 @@ EOLUA;
private function getRedisEvictionPolicy(): string
{
if (isset($this->redisEvictionPolicy)) {
if (null !== $this->redisEvictionPolicy) {
return $this->redisEvictionPolicy;
}

View File

@@ -19,73 +19,70 @@ use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\PruneableInterface;
use Symfony\Component\Cache\ResettableInterface;
use Symfony\Component\Cache\Traits\ContractsTrait;
use Symfony\Component\Cache\Traits\ProxyTrait;
use Symfony\Contracts\Cache\TagAwareCacheInterface;
/**
* Implements simple and robust tag-based invalidation suitable for use with volatile caches.
*
* This adapter works by storing a version for each tags. When saving an item, it is stored together with its tags and
* their corresponding versions. When retrieving an item, those tag versions are compared to the current version of
* each tags. Invalidation is achieved by deleting tags, thereby ensuring that their versions change even when the
* storage is out of space. When versions of non-existing tags are requested for item commits, this adapter assigns a
* new random version to them.
*
* @author Nicolas Grekas <p@tchwork.com>
* @author Sergey Belyshkin <sbelyshkin@gmail.com>
*/
class TagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterface, PruneableInterface, ResettableInterface, LoggerAwareInterface
{
use ContractsTrait;
use LoggerAwareTrait;
use ProxyTrait;
public const TAGS_PREFIX = "\0tags\0";
private array $deferred = [];
private AdapterInterface $pool;
private AdapterInterface $tags;
private array $knownTagVersions = [];
private float $knownTagVersionsTtl;
private $deferred = [];
private $tags;
private $knownTagVersions = [];
private $knownTagVersionsTtl;
private static \Closure $setCacheItemTags;
private static \Closure $setTagVersions;
private static \Closure $getTagsByKey;
private static \Closure $saveTags;
private static $createCacheItem;
private static $setCacheItemTags;
private static $getTagsByKey;
private static $saveTags;
public function __construct(AdapterInterface $itemsPool, AdapterInterface $tagsPool = null, float $knownTagVersionsTtl = 0.15)
{
$this->pool = $itemsPool;
$this->tags = $tagsPool ?? $itemsPool;
$this->tags = $tagsPool ?: $itemsPool;
$this->knownTagVersionsTtl = $knownTagVersionsTtl;
self::$setCacheItemTags ??= \Closure::bind(
static function (array $items, array $itemTags) {
foreach ($items as $key => $item) {
$item->isTaggable = true;
self::$createCacheItem ?? self::$createCacheItem = \Closure::bind(
static function ($key, $value, CacheItem $protoItem) {
$item = new CacheItem();
$item->key = $key;
$item->value = $value;
$item->expiry = $protoItem->expiry;
$item->poolHash = $protoItem->poolHash;
if (isset($itemTags[$key])) {
$tags = array_keys($itemTags[$key]);
$item->metadata[CacheItem::METADATA_TAGS] = array_combine($tags, $tags);
} else {
$item->value = null;
$item->isHit = false;
$item->metadata = [];
return $item;
},
null,
CacheItem::class
);
self::$setCacheItemTags ?? self::$setCacheItemTags = \Closure::bind(
static function (CacheItem $item, $key, array &$itemTags) {
$item->isTaggable = true;
if (!$item->isHit) {
return $item;
}
if (isset($itemTags[$key])) {
foreach ($itemTags[$key] as $tag => $version) {
$item->metadata[CacheItem::METADATA_TAGS][$tag] = $tag;
}
unset($itemTags[$key]);
} else {
$item->value = null;
$item->isHit = false;
}
return $items;
return $item;
},
null,
CacheItem::class
);
self::$setTagVersions ??= \Closure::bind(
static function (array $items, array $tagVersions) {
foreach ($items as $item) {
$item->newMetadata[CacheItem::METADATA_TAGS] = array_intersect_key($tagVersions, $item->newMetadata[CacheItem::METADATA_TAGS] ?? []);
}
},
null,
CacheItem::class
);
self::$getTagsByKey ??= \Closure::bind(
self::$getTagsByKey ?? self::$getTagsByKey = \Closure::bind(
static function ($deferred) {
$tagsByKey = [];
foreach ($deferred as $key => $item) {
@@ -98,7 +95,7 @@ class TagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterfac
null,
CacheItem::class
);
self::$saveTags ??= \Closure::bind(
self::$saveTags ?? self::$saveTags = \Closure::bind(
static function (AdapterInterface $tagsAdapter, array $tags) {
ksort($tags);
@@ -117,7 +114,7 @@ class TagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterfac
/**
* {@inheritdoc}
*/
public function invalidateTags(array $tags): bool
public function invalidateTags(array $tags)
{
$ids = [];
foreach ($tags as $tag) {
@@ -131,26 +128,54 @@ class TagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterfac
/**
* {@inheritdoc}
*
* @return bool
*/
public function hasItem(mixed $key): bool
public function hasItem($key)
{
return $this->getItem($key)->isHit();
if (\is_string($key) && isset($this->deferred[$key])) {
$this->commit();
}
if (!$this->pool->hasItem($key)) {
return false;
}
$itemTags = $this->pool->getItem(static::TAGS_PREFIX.$key);
if (!$itemTags->isHit()) {
return false;
}
if (!$itemTags = $itemTags->get()) {
return true;
}
foreach ($this->getTagVersions([$itemTags]) as $tag => $version) {
if ($itemTags[$tag] !== $version) {
return false;
}
}
return true;
}
/**
* {@inheritdoc}
*/
public function getItem(mixed $key): CacheItem
public function getItem($key)
{
foreach ($this->getItems([$key]) as $item) {
return $item;
}
return null;
}
/**
* {@inheritdoc}
*/
public function getItems(array $keys = []): iterable
public function getItems(array $keys = [])
{
$tagKeys = [];
$commit = false;
@@ -159,7 +184,7 @@ class TagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterfac
if ('' !== $key && \is_string($key)) {
$commit = $commit || isset($this->deferred[$key]);
$key = static::TAGS_PREFIX.$key;
$tagKeys[$key] = $key; // BC with pools populated before v6.1
$tagKeys[$key] = $key;
}
}
@@ -175,41 +200,15 @@ class TagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterfac
throw $e;
}
$bufferedItems = $itemTags = [];
foreach ($items as $key => $item) {
if (isset($tagKeys[$key])) { // BC with pools populated before v6.1
if ($item->isHit()) {
$itemTags[substr($key, \strlen(static::TAGS_PREFIX))] = $item->get() ?: [];
}
continue;
}
if (null !== $tags = $item->getMetadata()[CacheItem::METADATA_TAGS] ?? null) {
$itemTags[$key] = $tags;
}
$bufferedItems[$key] = $item;
}
$tagVersions = $this->getTagVersions($itemTags, false);
foreach ($itemTags as $key => $tags) {
foreach ($tags as $tag => $version) {
if ($tagVersions[$tag] !== $version) {
unset($itemTags[$key]);
continue 2;
}
}
}
$tagVersions = null;
return (self::$setCacheItemTags)($bufferedItems, $itemTags);
return $this->generateItems($items, $tagKeys);
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function clear(string $prefix = ''): bool
public function clear(string $prefix = '')
{
if ('' !== $prefix) {
foreach ($this->deferred as $key => $item) {
@@ -230,20 +229,24 @@ class TagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterfac
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteItem(mixed $key): bool
public function deleteItem($key)
{
return $this->deleteItems([$key]);
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteItems(array $keys): bool
public function deleteItems(array $keys)
{
foreach ($keys as $key) {
if ('' !== $key && \is_string($key)) {
$keys[] = static::TAGS_PREFIX.$key; // BC with pools populated before v6.1
$keys[] = static::TAGS_PREFIX.$key;
}
}
@@ -252,8 +255,10 @@ class TagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterfac
/**
* {@inheritdoc}
*
* @return bool
*/
public function save(CacheItemInterface $item): bool
public function save(CacheItemInterface $item)
{
if (!$item instanceof CacheItem) {
return false;
@@ -265,8 +270,10 @@ class TagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterfac
/**
* {@inheritdoc}
*
* @return bool
*/
public function saveDeferred(CacheItemInterface $item): bool
public function saveDeferred(CacheItemInterface $item)
{
if (!$item instanceof CacheItem) {
return false;
@@ -278,52 +285,41 @@ class TagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterfac
/**
* {@inheritdoc}
*
* @return bool
*/
public function commit(): bool
public function commit()
{
if (!$items = $this->deferred) {
if (!$this->deferred) {
return true;
}
$tagVersions = $this->getTagVersions((self::$getTagsByKey)($items), true);
(self::$setTagVersions)($items, $tagVersions);
$ok = true;
foreach ($items as $key => $item) {
if ($this->pool->saveDeferred($item)) {
foreach ($this->deferred as $key => $item) {
if (!$this->pool->saveDeferred($item)) {
unset($this->deferred[$key]);
} else {
$ok = false;
}
}
$ok = $this->pool->commit() && $ok;
$tagVersions = array_keys($tagVersions);
(self::$setTagVersions)($items, array_combine($tagVersions, $tagVersions));
$items = $this->deferred;
$tagsByKey = (self::$getTagsByKey)($items);
$this->deferred = [];
return $ok;
$tagVersions = $this->getTagVersions($tagsByKey);
$f = self::$createCacheItem;
foreach ($tagsByKey as $key => $tags) {
$this->pool->saveDeferred($f(static::TAGS_PREFIX.$key, array_intersect_key($tagVersions, $tags), $items[$key]));
}
return $this->pool->commit() && $ok;
}
/**
* {@inheritdoc}
* @return array
*/
public function prune(): bool
{
return $this->pool instanceof PruneableInterface && $this->pool->prune();
}
/**
* {@inheritdoc}
*/
public function reset()
{
$this->commit();
$this->knownTagVersions = [];
$this->pool instanceof ResettableInterface && $this->pool->reset();
$this->tags instanceof ResettableInterface && $this->tags->reset();
}
public function __sleep(): array
public function __sleep()
{
throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
}
@@ -338,19 +334,59 @@ class TagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterfac
$this->commit();
}
private function getTagVersions(array $tagsByKey, bool $persistTags): array
private function generateItems(iterable $items, array $tagKeys): \Generator
{
$bufferedItems = $itemTags = [];
$f = self::$setCacheItemTags;
foreach ($items as $key => $item) {
if (!$tagKeys) {
yield $key => $f($item, static::TAGS_PREFIX.$key, $itemTags);
continue;
}
if (!isset($tagKeys[$key])) {
$bufferedItems[$key] = $item;
continue;
}
unset($tagKeys[$key]);
if ($item->isHit()) {
$itemTags[$key] = $item->get() ?: [];
}
if (!$tagKeys) {
$tagVersions = $this->getTagVersions($itemTags);
foreach ($itemTags as $key => $tags) {
foreach ($tags as $tag => $version) {
if ($tagVersions[$tag] !== $version) {
unset($itemTags[$key]);
continue 2;
}
}
}
$tagVersions = $tagKeys = null;
foreach ($bufferedItems as $key => $item) {
yield $key => $f($item, static::TAGS_PREFIX.$key, $itemTags);
}
$bufferedItems = null;
}
}
}
private function getTagVersions(array $tagsByKey)
{
$tagVersions = [];
$fetchTagVersions = $persistTags;
$fetchTagVersions = false;
foreach ($tagsByKey as $tags) {
$tagVersions += $tags;
if ($fetchTagVersions) {
continue;
}
foreach ($tags as $tag => $version) {
if ($tagVersions[$tag] !== $version) {
$fetchTagVersions = true;
unset($this->knownTagVersions[$tag]);
}
}
}
@@ -363,9 +399,8 @@ class TagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterfac
$tags = [];
foreach ($tagVersions as $tag => $version) {
$tags[$tag.static::TAGS_PREFIX] = $tag;
$knownTagVersion = $this->knownTagVersions[$tag] ?? [0, null];
if ($fetchTagVersions || $now > $knownTagVersion[0] || $knownTagVersion[1] !== $version) {
// reuse previously fetched tag versions until the expiration
if ($fetchTagVersions || ($this->knownTagVersions[$tag][1] ?? null) !== $version || $now - $this->knownTagVersions[$tag][0] >= $this->knownTagVersionsTtl) {
// reuse previously fetched tag versions up to the ttl
$fetchTagVersions = true;
}
}
@@ -376,26 +411,18 @@ class TagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterfac
$newTags = [];
$newVersion = null;
$expiration = $now + $this->knownTagVersionsTtl;
foreach ($this->tags->getItems(array_keys($tags)) as $tag => $version) {
unset($this->knownTagVersions[$tag = $tags[$tag]]); // update FIFO
if (null !== $tagVersions[$tag] = $version->get()) {
$this->knownTagVersions[$tag] = [$expiration, $tagVersions[$tag]];
} elseif ($persistTags) {
$newTags[$tag] = $version->set($newVersion ??= random_bytes(6));
$tagVersions[$tag] = $newVersion;
$this->knownTagVersions[$tag] = [$expiration, $newVersion];
if (!$version->isHit()) {
$newTags[$tag] = $version->set($newVersion ?? $newVersion = random_int(\PHP_INT_MIN, \PHP_INT_MAX));
}
$tagVersions[$tag = $tags[$tag]] = $version->get();
$this->knownTagVersions[$tag] = [$now, $tagVersions[$tag]];
}
if ($newTags) {
(self::$saveTags)($this->tags, $newTags);
}
while ($now > ($this->knownTagVersions[$tag = array_key_first($this->knownTagVersions)][0] ?? \INF)) {
unset($this->knownTagVersions[$tag]);
}
return $tagVersions;
}
}

View File

@@ -25,7 +25,9 @@ interface TagAwareAdapterInterface extends AdapterInterface
*
* @param string[] $tags An array of tags to invalidate
*
* @return bool
*
* @throws InvalidArgumentException When $tags is not valid
*/
public function invalidateTags(array $tags): bool;
public function invalidateTags(array $tags);
}

View File

@@ -28,7 +28,7 @@ use Symfony\Contracts\Service\ResetInterface;
class TraceableAdapter implements AdapterInterface, CacheInterface, PruneableInterface, ResettableInterface
{
protected $pool;
private array $calls = [];
private $calls = [];
public function __construct(AdapterInterface $pool)
{
@@ -38,7 +38,7 @@ class TraceableAdapter implements AdapterInterface, CacheInterface, PruneableInt
/**
* {@inheritdoc}
*/
public function get(string $key, callable $callback, float $beta = null, array &$metadata = null): mixed
public function get(string $key, callable $callback, float $beta = null, array &$metadata = null)
{
if (!$this->pool instanceof CacheInterface) {
throw new \BadMethodCallException(sprintf('Cannot call "%s::get()": this class doesn\'t implement "%s".', get_debug_type($this->pool), CacheInterface::class));
@@ -70,7 +70,7 @@ class TraceableAdapter implements AdapterInterface, CacheInterface, PruneableInt
/**
* {@inheritdoc}
*/
public function getItem(mixed $key): CacheItem
public function getItem($key)
{
$event = $this->start(__FUNCTION__);
try {
@@ -89,8 +89,10 @@ class TraceableAdapter implements AdapterInterface, CacheInterface, PruneableInt
/**
* {@inheritdoc}
*
* @return bool
*/
public function hasItem(mixed $key): bool
public function hasItem($key)
{
$event = $this->start(__FUNCTION__);
try {
@@ -102,8 +104,10 @@ class TraceableAdapter implements AdapterInterface, CacheInterface, PruneableInt
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteItem(mixed $key): bool
public function deleteItem($key)
{
$event = $this->start(__FUNCTION__);
try {
@@ -115,8 +119,10 @@ class TraceableAdapter implements AdapterInterface, CacheInterface, PruneableInt
/**
* {@inheritdoc}
*
* @return bool
*/
public function save(CacheItemInterface $item): bool
public function save(CacheItemInterface $item)
{
$event = $this->start(__FUNCTION__);
try {
@@ -128,8 +134,10 @@ class TraceableAdapter implements AdapterInterface, CacheInterface, PruneableInt
/**
* {@inheritdoc}
*
* @return bool
*/
public function saveDeferred(CacheItemInterface $item): bool
public function saveDeferred(CacheItemInterface $item)
{
$event = $this->start(__FUNCTION__);
try {
@@ -142,7 +150,7 @@ class TraceableAdapter implements AdapterInterface, CacheInterface, PruneableInt
/**
* {@inheritdoc}
*/
public function getItems(array $keys = []): iterable
public function getItems(array $keys = [])
{
$event = $this->start(__FUNCTION__);
try {
@@ -167,8 +175,10 @@ class TraceableAdapter implements AdapterInterface, CacheInterface, PruneableInt
/**
* {@inheritdoc}
*
* @return bool
*/
public function clear(string $prefix = ''): bool
public function clear(string $prefix = '')
{
$event = $this->start(__FUNCTION__);
try {
@@ -184,8 +194,10 @@ class TraceableAdapter implements AdapterInterface, CacheInterface, PruneableInt
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteItems(array $keys): bool
public function deleteItems(array $keys)
{
$event = $this->start(__FUNCTION__);
$event->result['keys'] = $keys;
@@ -198,8 +210,10 @@ class TraceableAdapter implements AdapterInterface, CacheInterface, PruneableInt
/**
* {@inheritdoc}
*
* @return bool
*/
public function commit(): bool
public function commit()
{
$event = $this->start(__FUNCTION__);
try {
@@ -212,7 +226,7 @@ class TraceableAdapter implements AdapterInterface, CacheInterface, PruneableInt
/**
* {@inheritdoc}
*/
public function prune(): bool
public function prune()
{
if (!$this->pool instanceof PruneableInterface) {
return false;
@@ -270,15 +284,12 @@ class TraceableAdapter implements AdapterInterface, CacheInterface, PruneableInt
}
}
/**
* @internal
*/
class TraceableAdapterEvent
{
public string $name;
public float $start;
public float $end;
public array|bool $result;
public int $hits = 0;
public int $misses = 0;
public $name;
public $start;
public $end;
public $result;
public $hits = 0;
public $misses = 0;
}

View File

@@ -26,7 +26,7 @@ class TraceableTagAwareAdapter extends TraceableAdapter implements TagAwareAdapt
/**
* {@inheritdoc}
*/
public function invalidateTags(array $tags): bool
public function invalidateTags(array $tags)
{
$event = $this->start(__FUNCTION__);
try {

View File

@@ -1,18 +1,6 @@
CHANGELOG
=========
6.1
---
* Add support for ACL auth in RedisAdapter
* Improve reliability and performance of `TagAwareAdapter` by making tag versions an integral part of item value
6.0
---
* Remove `DoctrineProvider` and `DoctrineAdapter`
* Remove support of Doctrine DBAL in `PdoAdapter`
5.4
---

View File

@@ -22,17 +22,16 @@ use Symfony\Contracts\Cache\ItemInterface;
final class CacheItem implements ItemInterface
{
private const METADATA_EXPIRY_OFFSET = 1527506807;
private const VALUE_WRAPPER = "\xA9";
protected string $key;
protected mixed $value = null;
protected bool $isHit = false;
protected float|int|null $expiry = null;
protected array $metadata = [];
protected array $newMetadata = [];
protected ?ItemInterface $innerItem = null;
protected ?string $poolHash = null;
protected bool $isTaggable = false;
protected $key;
protected $value;
protected $isHit = false;
protected $expiry;
protected $metadata = [];
protected $newMetadata = [];
protected $innerItem;
protected $poolHash;
protected $isTaggable = false;
/**
* {@inheritdoc}
@@ -44,8 +43,10 @@ final class CacheItem implements ItemInterface
/**
* {@inheritdoc}
*
* @return mixed
*/
public function get(): mixed
public function get()
{
return $this->value;
}
@@ -63,7 +64,7 @@ final class CacheItem implements ItemInterface
*
* @return $this
*/
public function set($value): static
public function set($value): self
{
$this->value = $value;
@@ -75,9 +76,15 @@ final class CacheItem implements ItemInterface
*
* @return $this
*/
public function expiresAt(?\DateTimeInterface $expiration): static
public function expiresAt($expiration): self
{
$this->expiry = null !== $expiration ? (float) $expiration->format('U.u') : null;
if (null === $expiration) {
$this->expiry = null;
} elseif ($expiration instanceof \DateTimeInterface) {
$this->expiry = (float) $expiration->format('U.u');
} else {
throw new InvalidArgumentException(sprintf('Expiration date must implement DateTimeInterface or be null, "%s" given.', get_debug_type($expiration)));
}
return $this;
}
@@ -87,7 +94,7 @@ final class CacheItem implements ItemInterface
*
* @return $this
*/
public function expiresAfter(mixed $time): static
public function expiresAfter($time): self
{
if (null === $time) {
$this->expiry = null;
@@ -105,17 +112,17 @@ final class CacheItem implements ItemInterface
/**
* {@inheritdoc}
*/
public function tag(mixed $tags): static
public function tag($tags): ItemInterface
{
if (!$this->isTaggable) {
throw new LogicException(sprintf('Cache item "%s" comes from a non tag-aware pool: you cannot tag it.', $this->key));
}
if (!\is_array($tags) && !$tags instanceof \Traversable) { // don't use is_iterable(), it's slow
if (!is_iterable($tags)) {
$tags = [$tags];
}
foreach ($tags as $tag) {
if (!\is_string($tag) && !$tag instanceof \Stringable) {
throw new InvalidArgumentException(sprintf('Cache tag must be string or object that implements __toString(), "%s" given.', get_debug_type($tag)));
if (!\is_string($tag) && !(\is_object($tag) && method_exists($tag, '__toString'))) {
throw new InvalidArgumentException(sprintf('Cache tag must be string or object that implements __toString(), "%s" given.', \is_object($tag) ? \get_class($tag) : \gettype($tag)));
}
$tag = (string) $tag;
if (isset($this->newMetadata[self::METADATA_TAGS][$tag])) {
@@ -182,38 +189,4 @@ final class CacheItem implements ItemInterface
@trigger_error(strtr($message, $replace), \E_USER_WARNING);
}
}
private function pack(): mixed
{
if (!$m = $this->newMetadata) {
return $this->value;
}
$valueWrapper = self::VALUE_WRAPPER;
return new $valueWrapper($this->value, $m + ['expiry' => $this->expiry]);
}
private function unpack(): bool
{
$v = $this->value;
$valueWrapper = self::VALUE_WRAPPER;
if ($v instanceof $valueWrapper) {
$this->value = $v->value;
$this->metadata = $v->metadata;
return true;
}
if (!\is_array($v) || 1 !== \count($v) || 10 !== \strlen($k = (string) array_key_first($v)) || "\x9D" !== $k[0] || "\0" !== $k[5] || "\x5F" !== $k[9]) {
return false;
}
// BC with pools populated before v6.1
$this->value = $v[$k];
$this->metadata = unpack('Vexpiry/Nctime', substr($k, 1, -1));
$this->metadata['expiry'] += self::METADATA_EXPIRY_OFFSET;
return true;
}
}

View File

@@ -29,7 +29,7 @@ class CacheDataCollector extends DataCollector implements LateDataCollectorInter
/**
* @var TraceableAdapter[]
*/
private array $instances = [];
private $instances = [];
public function addInstance(string $name, TraceableAdapter $instance)
{
@@ -90,8 +90,10 @@ class CacheDataCollector extends DataCollector implements LateDataCollectorInter
/**
* Method returns all logged Cache call objects.
*
* @return mixed
*/
public function getCalls(): mixed
public function getCalls()
{
return $this->data['instances']['calls'];
}

View File

@@ -26,16 +26,31 @@ use Symfony\Component\DependencyInjection\Reference;
*/
class CacheCollectorPass implements CompilerPassInterface
{
private $dataCollectorCacheId;
private $cachePoolTag;
private $cachePoolRecorderInnerSuffix;
public function __construct(string $dataCollectorCacheId = 'data_collector.cache', string $cachePoolTag = 'cache.pool', string $cachePoolRecorderInnerSuffix = '.recorder_inner')
{
if (0 < \func_num_args()) {
trigger_deprecation('symfony/cache', '5.3', 'Configuring "%s" is deprecated.', __CLASS__);
}
$this->dataCollectorCacheId = $dataCollectorCacheId;
$this->cachePoolTag = $cachePoolTag;
$this->cachePoolRecorderInnerSuffix = $cachePoolRecorderInnerSuffix;
}
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('data_collector.cache')) {
if (!$container->hasDefinition($this->dataCollectorCacheId)) {
return;
}
foreach ($container->findTaggedServiceIds('cache.pool') as $id => $attributes) {
foreach ($container->findTaggedServiceIds($this->cachePoolTag) as $id => $attributes) {
$poolName = $attributes[0]['name'] ?? $id;
$this->addToCollector($id, $poolName, $container);
@@ -49,13 +64,13 @@ class CacheCollectorPass implements CompilerPassInterface
return;
}
$collectorDefinition = $container->getDefinition('data_collector.cache');
$collectorDefinition = $container->getDefinition($this->dataCollectorCacheId);
$recorder = new Definition(is_subclass_of($definition->getClass(), TagAwareAdapterInterface::class) ? TraceableTagAwareAdapter::class : TraceableAdapter::class);
$recorder->setTags($definition->getTags());
if (!$definition->isPublic() || !$definition->isPrivate()) {
$recorder->setPublic($definition->isPublic());
}
$recorder->setArguments([new Reference($innerId = $id.'.recorder_inner')]);
$recorder->setArguments([new Reference($innerId = $id.$this->cachePoolRecorderInnerSuffix)]);
foreach ($definition->getMethodCalls() as [$method, $args]) {
if ('setCallbackWrapper' !== $method || !$args[0] instanceof Definition || !($args[0]->getArguments()[2] ?? null) instanceof Definition) {

View File

@@ -20,6 +20,17 @@ use Symfony\Component\DependencyInjection\Reference;
*/
class CachePoolClearerPass implements CompilerPassInterface
{
private $cachePoolClearerTag;
public function __construct(string $cachePoolClearerTag = 'cache.pool.clearer')
{
if (0 < \func_num_args()) {
trigger_deprecation('symfony/cache', '5.3', 'Configuring "%s" is deprecated.', __CLASS__);
}
$this->cachePoolClearerTag = $cachePoolClearerTag;
}
/**
* {@inheritdoc}
*/
@@ -27,7 +38,7 @@ class CachePoolClearerPass implements CompilerPassInterface
{
$container->getParameterBag()->remove('cache.prefix.seed');
foreach ($container->findTaggedServiceIds('cache.pool.clearer') as $id => $attr) {
foreach ($container->findTaggedServiceIds($this->cachePoolClearerTag) as $id => $attr) {
$clearer = $container->getDefinition($id);
$pools = [];
foreach ($clearer->getArgument(0) as $name => $ref) {

View File

@@ -29,6 +29,33 @@ use Symfony\Component\DependencyInjection\Reference;
*/
class CachePoolPass implements CompilerPassInterface
{
private $cachePoolTag;
private $kernelResetTag;
private $cacheClearerId;
private $cachePoolClearerTag;
private $cacheSystemClearerId;
private $cacheSystemClearerTag;
private $reverseContainerId;
private $reversibleTag;
private $messageHandlerId;
public function __construct(string $cachePoolTag = 'cache.pool', string $kernelResetTag = 'kernel.reset', string $cacheClearerId = 'cache.global_clearer', string $cachePoolClearerTag = 'cache.pool.clearer', string $cacheSystemClearerId = 'cache.system_clearer', string $cacheSystemClearerTag = 'kernel.cache_clearer', string $reverseContainerId = 'reverse_container', string $reversibleTag = 'container.reversible', string $messageHandlerId = 'cache.early_expiration_handler')
{
if (0 < \func_num_args()) {
trigger_deprecation('symfony/cache', '5.3', 'Configuring "%s" is deprecated.', __CLASS__);
}
$this->cachePoolTag = $cachePoolTag;
$this->kernelResetTag = $kernelResetTag;
$this->cacheClearerId = $cacheClearerId;
$this->cachePoolClearerTag = $cachePoolClearerTag;
$this->cacheSystemClearerId = $cacheSystemClearerId;
$this->cacheSystemClearerTag = $cacheSystemClearerTag;
$this->reverseContainerId = $reverseContainerId;
$this->reversibleTag = $reversibleTag;
$this->messageHandlerId = $messageHandlerId;
}
/**
* {@inheritdoc}
*/
@@ -52,7 +79,7 @@ class CachePoolPass implements CompilerPassInterface
'early_expiration_message_bus',
'reset',
];
foreach ($container->findTaggedServiceIds('cache.pool') as $id => $tags) {
foreach ($container->findTaggedServiceIds($this->cachePoolTag) as $id => $tags) {
$adapter = $pool = $container->getDefinition($id);
if ($pool->isAbstract()) {
continue;
@@ -61,7 +88,7 @@ class CachePoolPass implements CompilerPassInterface
while ($adapter instanceof ChildDefinition) {
$adapter = $container->findDefinition($adapter->getParent());
$class = $class ?: $adapter->getClass();
if ($t = $adapter->getTag('cache.pool')) {
if ($t = $adapter->getTag($this->cachePoolTag)) {
$tags[0] += $t[0];
}
}
@@ -103,7 +130,7 @@ class CachePoolPass implements CompilerPassInterface
while ($adapter instanceof ChildDefinition) {
$adapter = $container->findDefinition($adapter->getParent());
$chainedClass = $chainedClass ?: $adapter->getClass();
if ($t = $adapter->getTag('cache.pool')) {
if ($t = $adapter->getTag($this->cachePoolTag)) {
$chainedTags[0] += $t[0];
}
}
@@ -141,19 +168,19 @@ class CachePoolPass implements CompilerPassInterface
// no-op
} elseif ('reset' === $attr) {
if ($tags[0][$attr]) {
$pool->addTag('kernel.reset', ['method' => $tags[0][$attr]]);
$pool->addTag($this->kernelResetTag, ['method' => $tags[0][$attr]]);
}
} elseif ('early_expiration_message_bus' === $attr) {
$needsMessageHandler = true;
$pool->addMethodCall('setCallbackWrapper', [(new Definition(EarlyExpirationDispatcher::class))
->addArgument(new Reference($tags[0]['early_expiration_message_bus']))
->addArgument(new Reference('reverse_container'))
->addArgument(new Reference($this->reverseContainerId))
->addArgument((new Definition('callable'))
->setFactory([new Reference($id), 'setCallbackWrapper'])
->addArgument(null)
),
]);
$pool->addTag('container.reversible');
$pool->addTag($this->reversibleTag);
} elseif ('namespace' !== $attr || !\in_array($class, [ArrayAdapter::class, NullAdapter::class], true)) {
$argument = $tags[0][$attr];
@@ -167,7 +194,7 @@ class CachePoolPass implements CompilerPassInterface
unset($tags[0][$attr]);
}
if (!empty($tags[0])) {
throw new InvalidArgumentException(sprintf('Invalid "cache.pool" tag for service "%s": accepted attributes are "clearer", "provider", "name", "namespace", "default_lifetime", "early_expiration_message_bus" and "reset", found "%s".', $id, implode('", "', array_keys($tags[0]))));
throw new InvalidArgumentException(sprintf('Invalid "%s" tag for service "%s": accepted attributes are "clearer", "provider", "name", "namespace", "default_lifetime", "early_expiration_message_bus" and "reset", found "%s".', $this->cachePoolTag, $id, implode('", "', array_keys($tags[0]))));
}
if (null !== $clearer) {
@@ -178,14 +205,14 @@ class CachePoolPass implements CompilerPassInterface
}
if (!$needsMessageHandler) {
$container->removeDefinition('cache.early_expiration_handler');
$container->removeDefinition($this->messageHandlerId);
}
$notAliasedCacheClearerId = $aliasedCacheClearerId = 'cache.global_clearer';
while ($container->hasAlias('cache.global_clearer')) {
$aliasedCacheClearerId = (string) $container->getAlias('cache.global_clearer');
$notAliasedCacheClearerId = $this->cacheClearerId;
while ($container->hasAlias($this->cacheClearerId)) {
$this->cacheClearerId = (string) $container->getAlias($this->cacheClearerId);
}
if ($container->hasDefinition($aliasedCacheClearerId)) {
if ($container->hasDefinition($this->cacheClearerId)) {
$clearers[$notAliasedCacheClearerId] = $allPools;
}
@@ -196,10 +223,10 @@ class CachePoolPass implements CompilerPassInterface
} else {
$clearer->setArgument(0, $pools);
}
$clearer->addTag('cache.pool.clearer');
$clearer->addTag($this->cachePoolClearerTag);
if ('cache.system_clearer' === $id) {
$clearer->addTag('kernel.cache_clearer');
if ($this->cacheSystemClearerId === $id) {
$clearer->addTag($this->cacheSystemClearerTag);
}
}

View File

@@ -23,18 +23,31 @@ use Symfony\Component\DependencyInjection\Reference;
*/
class CachePoolPrunerPass implements CompilerPassInterface
{
private $cacheCommandServiceId;
private $cachePoolTag;
public function __construct(string $cacheCommandServiceId = 'console.command.cache_pool_prune', string $cachePoolTag = 'cache.pool')
{
if (0 < \func_num_args()) {
trigger_deprecation('symfony/cache', '5.3', 'Configuring "%s" is deprecated.', __CLASS__);
}
$this->cacheCommandServiceId = $cacheCommandServiceId;
$this->cachePoolTag = $cachePoolTag;
}
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('console.command.cache_pool_prune')) {
if (!$container->hasDefinition($this->cacheCommandServiceId)) {
return;
}
$services = [];
foreach ($container->findTaggedServiceIds('cache.pool') as $id => $tags) {
foreach ($container->findTaggedServiceIds($this->cachePoolTag) as $id => $tags) {
$class = $container->getParameterBag()->resolveValue($container->getDefinition($id)->getClass());
if (!$reflection = $container->getReflectionClass($class)) {
@@ -46,6 +59,6 @@ class CachePoolPrunerPass implements CompilerPassInterface
}
}
$container->getDefinition('console.command.cache_pool_prune')->replaceArgument(0, new IteratorArgument($services));
$container->getDefinition($this->cacheCommandServiceId)->replaceArgument(0, new IteratorArgument($services));
}
}

View File

@@ -0,0 +1,124 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Cache;
use Doctrine\Common\Cache\CacheProvider;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Contracts\Service\ResetInterface;
if (!class_exists(CacheProvider::class)) {
return;
}
/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @deprecated Use Doctrine\Common\Cache\Psr6\DoctrineProvider instead
*/
class DoctrineProvider extends CacheProvider implements PruneableInterface, ResettableInterface
{
private $pool;
public function __construct(CacheItemPoolInterface $pool)
{
trigger_deprecation('symfony/cache', '5.4', '"%s" is deprecated, use "Doctrine\Common\Cache\Psr6\DoctrineProvider" instead.', __CLASS__);
$this->pool = $pool;
}
/**
* {@inheritdoc}
*/
public function prune()
{
return $this->pool instanceof PruneableInterface && $this->pool->prune();
}
/**
* {@inheritdoc}
*/
public function reset()
{
if ($this->pool instanceof ResetInterface) {
$this->pool->reset();
}
$this->setNamespace($this->getNamespace());
}
/**
* {@inheritdoc}
*
* @return mixed
*/
protected function doFetch($id)
{
$item = $this->pool->getItem(rawurlencode($id));
return $item->isHit() ? $item->get() : false;
}
/**
* {@inheritdoc}
*
* @return bool
*/
protected function doContains($id)
{
return $this->pool->hasItem(rawurlencode($id));
}
/**
* {@inheritdoc}
*
* @return bool
*/
protected function doSave($id, $data, $lifeTime = 0)
{
$item = $this->pool->getItem(rawurlencode($id));
if (0 < $lifeTime) {
$item->expiresAfter($lifeTime);
}
return $this->pool->save($item->set($data));
}
/**
* {@inheritdoc}
*
* @return bool
*/
protected function doDelete($id)
{
return $this->pool->deleteItem(rawurlencode($id));
}
/**
* {@inheritdoc}
*
* @return bool
*/
protected function doFlush()
{
return $this->pool->clear();
}
/**
* {@inheritdoc}
*
* @return array|null
*/
protected function doGetStats()
{
return null;
}
}

View File

@@ -43,6 +43,7 @@ final class LockRegistry
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ChainAdapter.php',
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'CouchbaseBucketAdapter.php',
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'CouchbaseCollectionAdapter.php',
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'DoctrineAdapter.php',
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'DoctrineDbalAdapter.php',
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'FilesystemAdapter.php',
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'FilesystemTagAwareAdapter.php',
@@ -96,8 +97,8 @@ final class LockRegistry
return $callback($item, $save);
}
self::$signalingException ??= unserialize("O:9:\"Exception\":1:{s:16:\"\0Exception\0trace\";a:0:{}}");
self::$signalingCallback ??= function () { throw self::$signalingException; };
self::$signalingException ?? self::$signalingException = unserialize("O:9:\"Exception\":1:{s:16:\"\0Exception\0trace\";a:0:{}}");
self::$signalingCallback ?? self::$signalingCallback = function () { throw self::$signalingException; };
while (true) {
try {
@@ -106,7 +107,7 @@ final class LockRegistry
$locked = flock($lock, \LOCK_EX | \LOCK_NB, $wouldBlock);
if ($locked || !$wouldBlock) {
$logger?->info(sprintf('Lock %s, now computing item "{key}"', $locked ? 'acquired' : 'not supported'), ['key' => $item->getKey()]);
$logger && $logger->info(sprintf('Lock %s, now computing item "{key}"', $locked ? 'acquired' : 'not supported'), ['key' => $item->getKey()]);
self::$lockedFiles[$key] = true;
$value = $callback($item, $save);
@@ -123,7 +124,7 @@ final class LockRegistry
return $value;
}
// if we failed the race, retry locking in blocking mode to wait for the winner
$logger?->info('Item "{key}" is locked, waiting for it to be released', ['key' => $item->getKey()]);
$logger && $logger->info('Item "{key}" is locked, waiting for it to be released', ['key' => $item->getKey()]);
flock($lock, \LOCK_SH);
} finally {
flock($lock, \LOCK_UN);
@@ -132,7 +133,7 @@ final class LockRegistry
try {
$value = $pool->get($item->getKey(), self::$signalingCallback, 0);
$logger?->info('Item "{key}" retrieved after lock was released', ['key' => $item->getKey()]);
$logger && $logger->info('Item "{key}" retrieved after lock was released', ['key' => $item->getKey()]);
$save = false;
return $value;
@@ -140,7 +141,7 @@ final class LockRegistry
if (self::$signalingException !== $e) {
throw $e;
}
$logger?->info('Item "{key}" not found while lock was released, now retrying', ['key' => $item->getKey()]);
$logger && $logger->info('Item "{key}" not found while lock was released, now retrying', ['key' => $item->getKey()]);
}
}

View File

@@ -20,15 +20,15 @@ use Symfony\Component\Cache\Exception\CacheException;
*/
class DefaultMarshaller implements MarshallerInterface
{
private bool $useIgbinarySerialize = true;
private bool $throwOnSerializationFailure = false;
private $useIgbinarySerialize = true;
private $throwOnSerializationFailure;
public function __construct(bool $useIgbinarySerialize = null, bool $throwOnSerializationFailure = false)
{
if (null === $useIgbinarySerialize) {
$useIgbinarySerialize = \extension_loaded('igbinary') && version_compare('3.1.6', phpversion('igbinary'), '<=');
} elseif ($useIgbinarySerialize && (!\extension_loaded('igbinary') || version_compare('3.1.6', phpversion('igbinary'), '>'))) {
throw new CacheException(\extension_loaded('igbinary') ? 'Please upgrade the "igbinary" PHP extension to v3.1.6 or higher.' : 'The "igbinary" PHP extension is not loaded.');
$useIgbinarySerialize = \extension_loaded('igbinary') && (\PHP_VERSION_ID < 70400 || version_compare('3.1.6', phpversion('igbinary'), '<='));
} elseif ($useIgbinarySerialize && (!\extension_loaded('igbinary') || (\PHP_VERSION_ID >= 70400 && version_compare('3.1.6', phpversion('igbinary'), '>')))) {
throw new CacheException(\extension_loaded('igbinary') && \PHP_VERSION_ID >= 70400 ? 'Please upgrade the "igbinary" PHP extension to v3.1.6 or higher.' : 'The "igbinary" PHP extension is not loaded.');
}
$this->useIgbinarySerialize = $useIgbinarySerialize;
$this->throwOnSerializationFailure = $throwOnSerializationFailure;
@@ -62,7 +62,7 @@ class DefaultMarshaller implements MarshallerInterface
/**
* {@inheritdoc}
*/
public function unmarshall(string $value): mixed
public function unmarshall(string $value)
{
if ('b:0;' === $value) {
return false;
@@ -71,7 +71,7 @@ class DefaultMarshaller implements MarshallerInterface
return null;
}
static $igbinaryNull;
if ($value === $igbinaryNull ??= \extension_loaded('igbinary') ? igbinary_serialize(null) : false) {
if ($value === ($igbinaryNull ?? $igbinaryNull = \extension_loaded('igbinary') ? igbinary_serialize(null) : false)) {
return null;
}
$unserializeCallbackHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback');

View File

@@ -20,7 +20,7 @@ use Symfony\Component\Cache\Exception\CacheException;
*/
class DeflateMarshaller implements MarshallerInterface
{
private MarshallerInterface $marshaller;
private $marshaller;
public function __construct(MarshallerInterface $marshaller)
{
@@ -42,7 +42,7 @@ class DeflateMarshaller implements MarshallerInterface
/**
* {@inheritdoc}
*/
public function unmarshall(string $value): mixed
public function unmarshall(string $value)
{
if (false !== $inflatedValue = @gzinflate($value)) {
$value = $inflatedValue;

View File

@@ -32,7 +32,9 @@ interface MarshallerInterface
/**
* Unserializes a single value and throws an exception if anything goes wrong.
*
* @return mixed
*
* @throws \Exception Whenever unserialization fails
*/
public function unmarshall(string $value): mixed;
public function unmarshall(string $value);
}

View File

@@ -21,8 +21,8 @@ use Symfony\Component\Cache\Exception\InvalidArgumentException;
*/
class SodiumMarshaller implements MarshallerInterface
{
private MarshallerInterface $marshaller;
private array $decryptionKeys;
private $marshaller;
private $decryptionKeys;
/**
* @param string[] $decryptionKeys The key at index "0" is required and is used to decrypt and encrypt values;
@@ -66,7 +66,7 @@ class SodiumMarshaller implements MarshallerInterface
/**
* {@inheritdoc}
*/
public function unmarshall(string $value): mixed
public function unmarshall(string $value)
{
foreach ($this->decryptionKeys as $k) {
if (false !== $decryptedValue = @sodium_crypto_box_seal_open($value, $k)) {

View File

@@ -18,7 +18,7 @@ namespace Symfony\Component\Cache\Marshaller;
*/
class TagAwareMarshaller implements MarshallerInterface
{
private MarshallerInterface $marshaller;
private $marshaller;
public function __construct(MarshallerInterface $marshaller = null)
{
@@ -67,7 +67,7 @@ class TagAwareMarshaller implements MarshallerInterface
/**
* {@inheritdoc}
*/
public function unmarshall(string $value): mixed
public function unmarshall(string $value)
{
// detect the compact format used in marshall() using magic numbers in the form 9D-..-..-..-..-00-..-..-..-5F
if (13 >= \strlen($value) || "\x9D" !== $value[0] || "\0" !== $value[5] || "\x5F" !== $value[9]) {

View File

@@ -23,22 +23,22 @@ use Symfony\Component\Messenger\Stamp\HandledStamp;
*/
class EarlyExpirationDispatcher
{
private MessageBusInterface $bus;
private ReverseContainer $reverseContainer;
private ?\Closure $callbackWrapper;
private $bus;
private $reverseContainer;
private $callbackWrapper;
public function __construct(MessageBusInterface $bus, ReverseContainer $reverseContainer, callable $callbackWrapper = null)
{
$this->bus = $bus;
$this->reverseContainer = $reverseContainer;
$this->callbackWrapper = null === $callbackWrapper ? null : $callbackWrapper(...);
$this->callbackWrapper = $callbackWrapper;
}
public function __invoke(callable $callback, CacheItem $item, bool &$save, AdapterInterface $pool, \Closure $setMetadata, LoggerInterface $logger = null)
{
if (!$item->isHit() || null === $message = EarlyExpirationMessage::create($this->reverseContainer, $callback, $item, $pool)) {
// The item is stale or the callback cannot be reversed: we must compute the value now
$logger?->info('Computing item "{key}" online: '.($item->isHit() ? 'callback cannot be reversed' : 'item is stale'), ['key' => $item->getKey()]);
$logger && $logger->info('Computing item "{key}" online: '.($item->isHit() ? 'callback cannot be reversed' : 'item is stale'), ['key' => $item->getKey()]);
return null !== $this->callbackWrapper ? ($this->callbackWrapper)($callback, $item, $save, $pool, $setMetadata, $logger) : $callback($item, $save);
}

View File

@@ -20,8 +20,8 @@ use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
*/
class EarlyExpirationHandler implements MessageHandlerInterface
{
private ReverseContainer $reverseContainer;
private array $processedNonces = [];
private $reverseContainer;
private $processedNonces = [];
public function __construct(ReverseContainer $reverseContainer)
{
@@ -59,7 +59,7 @@ class EarlyExpirationHandler implements MessageHandlerInterface
static $setMetadata;
$setMetadata ??= \Closure::bind(
$setMetadata ?? $setMetadata = \Closure::bind(
function (CacheItem $item, float $startTime) {
if ($item->expiry > $endTime = microtime(true)) {
$item->newMetadata[CacheItem::METADATA_EXPIRY] = $item->expiry;

View File

@@ -20,16 +20,16 @@ use Symfony\Component\DependencyInjection\ReverseContainer;
*/
final class EarlyExpirationMessage
{
private CacheItem $item;
private string $pool;
private string|array $callback;
private $item;
private $pool;
private $callback;
public static function create(ReverseContainer $reverseContainer, callable $callback, CacheItem $item, AdapterInterface $pool): ?self
{
try {
$item = clone $item;
$item->set(null);
} catch (\Exception) {
} catch (\Exception $e) {
return null;
}
@@ -66,10 +66,7 @@ final class EarlyExpirationMessage
return $this->pool;
}
/**
* @return string|string[]
*/
public function getCallback(): string|array
public function getCallback()
{
return $this->callback;
}
@@ -91,7 +88,7 @@ final class EarlyExpirationMessage
return $callback;
}
private function __construct(CacheItem $item, string $pool, string|array $callback)
private function __construct(CacheItem $item, string $pool, $callback)
{
$this->item = $item;
$this->pool = $pool;

View File

@@ -16,5 +16,8 @@ namespace Symfony\Component\Cache;
*/
interface PruneableInterface
{
public function prune(): bool;
/**
* @return bool
*/
public function prune();
}

View File

@@ -19,6 +19,10 @@ use Symfony\Component\Cache\Adapter\AdapterInterface;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
use Symfony\Component\Cache\Traits\ProxyTrait;
if (null !== (new \ReflectionMethod(CacheInterface::class, 'get'))->getReturnType()) {
throw new \LogicException('psr/simple-cache 3.0+ is not compatible with this version of symfony/cache. Please upgrade symfony/cache to 6.0+ or downgrade psr/simple-cache to 1.x or 2.x.');
}
/**
* Turns a PSR-6 cache into a PSR-16 one.
*
@@ -28,9 +32,10 @@ class Psr16Cache implements CacheInterface, PruneableInterface, ResettableInterf
{
use ProxyTrait;
private ?\Closure $createCacheItem = null;
private ?CacheItem $cacheItemPrototype = null;
private static \Closure $packCacheItem;
private const METADATA_EXPIRY_OFFSET = 1527506807;
private $createCacheItem;
private $cacheItemPrototype;
public function __construct(CacheItemPoolInterface $pool)
{
@@ -66,21 +71,14 @@ class Psr16Cache implements CacheInterface, PruneableInterface, ResettableInterf
return $createCacheItem($key, null, $allowInt)->set($value);
};
self::$packCacheItem ??= \Closure::bind(
static function (CacheItem $item) {
$item->newMetadata = $item->metadata;
return $item->pack();
},
null,
CacheItem::class
);
}
/**
* {@inheritdoc}
*
* @return mixed
*/
public function get($key, $default = null): mixed
public function get($key, $default = null)
{
try {
$item = $this->pool->getItem($key);
@@ -99,8 +97,10 @@ class Psr16Cache implements CacheInterface, PruneableInterface, ResettableInterf
/**
* {@inheritdoc}
*
* @return bool
*/
public function set($key, $value, $ttl = null): bool
public function set($key, $value, $ttl = null)
{
try {
if (null !== $f = $this->createCacheItem) {
@@ -122,8 +122,10 @@ class Psr16Cache implements CacheInterface, PruneableInterface, ResettableInterf
/**
* {@inheritdoc}
*
* @return bool
*/
public function delete($key): bool
public function delete($key)
{
try {
return $this->pool->deleteItem($key);
@@ -136,16 +138,20 @@ class Psr16Cache implements CacheInterface, PruneableInterface, ResettableInterf
/**
* {@inheritdoc}
*
* @return bool
*/
public function clear(): bool
public function clear()
{
return $this->pool->clear();
}
/**
* {@inheritdoc}
*
* @return iterable
*/
public function getMultiple($keys, $default = null): iterable
public function getMultiple($keys, $default = null)
{
if ($keys instanceof \Traversable) {
$keys = iterator_to_array($keys, false);
@@ -171,7 +177,20 @@ class Psr16Cache implements CacheInterface, PruneableInterface, ResettableInterf
}
foreach ($items as $key => $item) {
$values[$key] = $item->isHit() ? (self::$packCacheItem)($item) : $default;
if (!$item->isHit()) {
$values[$key] = $default;
continue;
}
$values[$key] = $item->get();
if (!$metadata = $item->getMetadata()) {
continue;
}
unset($metadata[CacheItem::METADATA_TAGS]);
if ($metadata) {
$values[$key] = ["\x9D".pack('VN', (int) (0.1 + $metadata[CacheItem::METADATA_EXPIRY] - self::METADATA_EXPIRY_OFFSET), $metadata[CacheItem::METADATA_CTIME])."\x5F" => $values[$key]];
}
}
return $values;
@@ -179,8 +198,10 @@ class Psr16Cache implements CacheInterface, PruneableInterface, ResettableInterf
/**
* {@inheritdoc}
*
* @return bool
*/
public function setMultiple($values, $ttl = null): bool
public function setMultiple($values, $ttl = null)
{
$valuesIsArray = \is_array($values);
if (!$valuesIsArray && !$values instanceof \Traversable) {
@@ -230,8 +251,10 @@ class Psr16Cache implements CacheInterface, PruneableInterface, ResettableInterf
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteMultiple($keys): bool
public function deleteMultiple($keys)
{
if ($keys instanceof \Traversable) {
$keys = iterator_to_array($keys, false);
@@ -250,8 +273,10 @@ class Psr16Cache implements CacheInterface, PruneableInterface, ResettableInterf
/**
* {@inheritdoc}
*
* @return bool
*/
public function has($key): bool
public function has($key)
{
try {
return $this->pool->hasItem($key);

View File

@@ -26,21 +26,21 @@ trait AbstractAdapterTrait
use LoggerAwareTrait;
/**
* needs to be set by class, signature is function(string <key>, mixed <value>, bool <isHit>).
* @var \Closure needs to be set by class, signature is function(string <key>, mixed <value>, bool <isHit>)
*/
private static \Closure $createCacheItem;
private static $createCacheItem;
/**
* needs to be set by class, signature is function(array <deferred>, string <namespace>, array <&expiredIds>).
* @var \Closure needs to be set by class, signature is function(array <deferred>, string <namespace>, array <&expiredIds>)
*/
private static \Closure $mergeByLifetime;
private static $mergeByLifetime;
private string $namespace = '';
private int $defaultLifetime;
private string $namespaceVersion = '';
private bool $versioningIsEnabled = false;
private array $deferred = [];
private array $ids = [];
private $namespace = '';
private $defaultLifetime;
private $namespaceVersion = '';
private $versioningIsEnabled = false;
private $deferred = [];
private $ids = [];
/**
* @var int|null The maximum length to enforce for identifiers or null when no limit applies
@@ -54,28 +54,34 @@ trait AbstractAdapterTrait
*
* @return array|\Traversable
*/
abstract protected function doFetch(array $ids): iterable;
abstract protected function doFetch(array $ids);
/**
* Confirms if the cache contains specified cache item.
*
* @param string $id The identifier for which to check existence
*
* @return bool
*/
abstract protected function doHave(string $id): bool;
abstract protected function doHave(string $id);
/**
* Deletes all items in the pool.
*
* @param string $namespace The prefix used for all identifiers managed by this pool
*
* @return bool
*/
abstract protected function doClear(string $namespace): bool;
abstract protected function doClear(string $namespace);
/**
* Removes multiple items from the pool.
*
* @param array $ids An array of identifiers that should be removed from the pool
*
* @return bool
*/
abstract protected function doDelete(array $ids): bool;
abstract protected function doDelete(array $ids);
/**
* Persists several cache items immediately.
@@ -85,12 +91,14 @@ trait AbstractAdapterTrait
*
* @return array|bool The identifiers that failed to be cached or a boolean stating if caching succeeded or not
*/
abstract protected function doSave(array $values, int $lifetime): array|bool;
abstract protected function doSave(array $values, int $lifetime);
/**
* {@inheritdoc}
*
* @return bool
*/
public function hasItem(mixed $key): bool
public function hasItem($key)
{
$id = $this->getId($key);
@@ -109,8 +117,10 @@ trait AbstractAdapterTrait
/**
* {@inheritdoc}
*
* @return bool
*/
public function clear(string $prefix = ''): bool
public function clear(string $prefix = '')
{
$this->deferred = [];
if ($cleared = $this->versioningIsEnabled) {
@@ -148,16 +158,20 @@ trait AbstractAdapterTrait
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteItem(mixed $key): bool
public function deleteItem($key)
{
return $this->deleteItems([$key]);
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteItems(array $keys): bool
public function deleteItems(array $keys)
{
$ids = [];
@@ -170,7 +184,7 @@ trait AbstractAdapterTrait
if ($this->doDelete($ids)) {
return true;
}
} catch (\Exception) {
} catch (\Exception $e) {
}
$ok = true;
@@ -195,7 +209,7 @@ trait AbstractAdapterTrait
/**
* {@inheritdoc}
*/
public function getItem(mixed $key): CacheItem
public function getItem($key)
{
$id = $this->getId($key);
@@ -222,7 +236,7 @@ trait AbstractAdapterTrait
/**
* {@inheritdoc}
*/
public function getItems(array $keys = []): iterable
public function getItems(array $keys = [])
{
$ids = [];
$commit = false;
@@ -249,8 +263,10 @@ trait AbstractAdapterTrait
/**
* {@inheritdoc}
*
* @return bool
*/
public function save(CacheItemInterface $item): bool
public function save(CacheItemInterface $item)
{
if (!$item instanceof CacheItem) {
return false;
@@ -262,8 +278,10 @@ trait AbstractAdapterTrait
/**
* {@inheritdoc}
*
* @return bool
*/
public function saveDeferred(CacheItemInterface $item): bool
public function saveDeferred(CacheItemInterface $item)
{
if (!$item instanceof CacheItem) {
return false;
@@ -283,7 +301,7 @@ trait AbstractAdapterTrait
*
* @return bool the previous state of versioning
*/
public function enableVersioning(bool $enable = true): bool
public function enableVersioning(bool $enable = true)
{
$wasEnabled = $this->versioningIsEnabled;
$this->versioningIsEnabled = $enable;
@@ -305,7 +323,10 @@ trait AbstractAdapterTrait
$this->ids = [];
}
public function __sleep(): array
/**
* @return array
*/
public function __sleep()
{
throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
}
@@ -344,7 +365,7 @@ trait AbstractAdapterTrait
}
}
private function getId(mixed $key)
private function getId($key)
{
if ($this->versioningIsEnabled && '' === $this->namespaceVersion) {
$this->ids = [];

View File

@@ -31,8 +31,8 @@ trait ContractsTrait
doGet as private contractsGet;
}
private \Closure $callbackWrapper;
private array $computing = [];
private $callbackWrapper;
private $computing = [];
/**
* Wraps the callback passed to ->get() in a callable.
@@ -42,17 +42,13 @@ trait ContractsTrait
public function setCallbackWrapper(?callable $callbackWrapper): callable
{
if (!isset($this->callbackWrapper)) {
$this->callbackWrapper = LockRegistry::compute(...);
$this->callbackWrapper = \Closure::fromCallable([LockRegistry::class, 'compute']);
if (\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) {
$this->setCallbackWrapper(null);
}
}
if (null !== $callbackWrapper && !$callbackWrapper instanceof \Closure) {
$callbackWrapper = $callbackWrapper(...);
}
$previousWrapper = $this->callbackWrapper;
$this->callbackWrapper = $callbackWrapper ?? static function (callable $callback, ItemInterface $item, bool &$save, CacheInterface $pool, \Closure $setMetadata, ?LoggerInterface $logger) {
return $callback($item, $save);
@@ -63,27 +59,25 @@ trait ContractsTrait
private function doGet(AdapterInterface $pool, string $key, callable $callback, ?float $beta, array &$metadata = null)
{
if (0 > $beta ??= 1.0) {
if (0 > $beta = $beta ?? 1.0) {
throw new InvalidArgumentException(sprintf('Argument "$beta" provided to "%s::get()" must be a positive number, %f given.', static::class, $beta));
}
static $setMetadata;
$setMetadata ??= \Closure::bind(
$setMetadata ?? $setMetadata = \Closure::bind(
static function (CacheItem $item, float $startTime, ?array &$metadata) {
if ($item->expiry > $endTime = microtime(true)) {
$item->newMetadata[CacheItem::METADATA_EXPIRY] = $metadata[CacheItem::METADATA_EXPIRY] = $item->expiry;
$item->newMetadata[CacheItem::METADATA_CTIME] = $metadata[CacheItem::METADATA_CTIME] = (int) ceil(1000 * ($endTime - $startTime));
} else {
unset($metadata[CacheItem::METADATA_EXPIRY], $metadata[CacheItem::METADATA_CTIME], $metadata[CacheItem::METADATA_TAGS]);
unset($metadata[CacheItem::METADATA_EXPIRY], $metadata[CacheItem::METADATA_CTIME]);
}
},
null,
CacheItem::class
);
$this->callbackWrapper ??= LockRegistry::compute(...);
return $this->contractsGet($pool, $key, function (CacheItem $item, bool &$save) use ($pool, $callback, $setMetadata, &$metadata, $key) {
// don't wrap nor save recursive calls
if (isset($this->computing[$key])) {

View File

@@ -20,8 +20,8 @@ use Symfony\Component\Cache\Exception\InvalidArgumentException;
*/
trait FilesystemCommonTrait
{
private string $directory;
private string $tmp;
private $directory;
private $tmp;
private function init(string $namespace, ?string $directory)
{
@@ -53,7 +53,7 @@ trait FilesystemCommonTrait
/**
* {@inheritdoc}
*/
protected function doClear(string $namespace): bool
protected function doClear(string $namespace)
{
$ok = true;
@@ -71,7 +71,7 @@ trait FilesystemCommonTrait
/**
* {@inheritdoc}
*/
protected function doDelete(array $ids): bool
protected function doDelete(array $ids)
{
$ok = true;
@@ -92,7 +92,7 @@ trait FilesystemCommonTrait
{
set_error_handler(__CLASS__.'::throwError');
try {
if (!isset($this->tmp)) {
if (null === $this->tmp) {
$this->tmp = $this->directory.bin2hex(random_bytes(6));
}
try {
@@ -171,7 +171,10 @@ trait FilesystemCommonTrait
throw new \ErrorException($message, 0, $type, $file, $line);
}
public function __sleep(): array
/**
* @return array
*/
public function __sleep()
{
throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
}
@@ -186,7 +189,7 @@ trait FilesystemCommonTrait
if (method_exists(parent::class, '__destruct')) {
parent::__destruct();
}
if (isset($this->tmp) && is_file($this->tmp)) {
if (null !== $this->tmp && is_file($this->tmp)) {
unlink($this->tmp);
}
}

View File

@@ -12,7 +12,6 @@
namespace Symfony\Component\Cache\Traits;
use Symfony\Component\Cache\Exception\CacheException;
use Symfony\Component\Cache\Marshaller\MarshallerInterface;
/**
* @author Nicolas Grekas <p@tchwork.com>
@@ -24,9 +23,12 @@ trait FilesystemTrait
{
use FilesystemCommonTrait;
private MarshallerInterface $marshaller;
private $marshaller;
public function prune(): bool
/**
* @return bool
*/
public function prune()
{
$time = time();
$pruned = true;
@@ -50,7 +52,7 @@ trait FilesystemTrait
/**
* {@inheritdoc}
*/
protected function doFetch(array $ids): iterable
protected function doFetch(array $ids)
{
$values = [];
$now = time();
@@ -79,7 +81,7 @@ trait FilesystemTrait
/**
* {@inheritdoc}
*/
protected function doHave(string $id): bool
protected function doHave(string $id)
{
$file = $this->getFile($id);
@@ -89,7 +91,7 @@ trait FilesystemTrait
/**
* {@inheritdoc}
*/
protected function doSave(array $values, int $lifetime): array|bool
protected function doSave(array $values, int $lifetime)
{
$expiresAt = $lifetime ? (time() + $lifetime) : 0;
$values = $this->marshaller->marshall($values, $failed);

View File

@@ -21,12 +21,12 @@ use Symfony\Contracts\Service\ResetInterface;
*/
trait ProxyTrait
{
private object $pool;
private $pool;
/**
* {@inheritdoc}
*/
public function prune(): bool
public function prune()
{
return $this->pool instanceof PruneableInterface && $this->pool->prune();
}

View File

@@ -24,10 +24,13 @@ namespace Symfony\Component\Cache\Traits;
*/
class RedisClusterNodeProxy
{
private array $host;
private \RedisCluster|RedisClusterProxy $redis;
private $host;
private $redis;
public function __construct(array $host, \RedisCluster|RedisClusterProxy $redis)
/**
* @param \RedisCluster|RedisClusterProxy $redis
*/
public function __construct(array $host, $redis)
{
$this->host = $host;
$this->redis = $redis;

View File

@@ -18,8 +18,8 @@ namespace Symfony\Component\Cache\Traits;
*/
class RedisClusterProxy
{
private \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy $redis;
private \Closure $initializer;
private $redis;
private $initializer;
public function __construct(\Closure $initializer)
{
@@ -28,35 +28,35 @@ class RedisClusterProxy
public function __call(string $method, array $args)
{
$this->redis ??= ($this->initializer)();
$this->redis ?: $this->redis = $this->initializer->__invoke();
return $this->redis->{$method}(...$args);
}
public function hscan($strKey, &$iIterator, $strPattern = null, $iCount = null)
{
$this->redis ??= ($this->initializer)();
$this->redis ?: $this->redis = $this->initializer->__invoke();
return $this->redis->hscan($strKey, $iIterator, $strPattern, $iCount);
}
public function scan(&$iIterator, $strPattern = null, $iCount = null)
{
$this->redis ??= ($this->initializer)();
$this->redis ?: $this->redis = $this->initializer->__invoke();
return $this->redis->scan($iIterator, $strPattern, $iCount);
}
public function sscan($strKey, &$iIterator, $strPattern = null, $iCount = null)
{
$this->redis ??= ($this->initializer)();
$this->redis ?: $this->redis = $this->initializer->__invoke();
return $this->redis->sscan($strKey, $iIterator, $strPattern, $iCount);
}
public function zscan($strKey, &$iIterator, $strPattern = null, $iCount = null)
{
$this->redis ??= ($this->initializer)();
$this->redis ?: $this->redis = $this->initializer->__invoke();
return $this->redis->zscan($strKey, $iIterator, $strPattern, $iCount);
}

View File

@@ -18,9 +18,9 @@ namespace Symfony\Component\Cache\Traits;
*/
class RedisProxy
{
private \Redis $redis;
private \Closure $initializer;
private bool $ready = false;
private $redis;
private $initializer;
private $ready = false;
public function __construct(\Redis $redis, \Closure $initializer)
{

View File

@@ -30,7 +30,7 @@ use Symfony\Component\Cache\Marshaller\MarshallerInterface;
*/
trait RedisTrait
{
private static array $defaultConnectionOptions = [
private static $defaultConnectionOptions = [
'class' => null,
'persistent' => 0,
'persistent_id' => null,
@@ -45,10 +45,13 @@ trait RedisTrait
'failover' => 'none',
'ssl' => null, // see https://php.net/context.ssl
];
private \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy $redis;
private MarshallerInterface $marshaller;
private $redis;
private $marshaller;
private function init(\Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy $redis, string $namespace, int $defaultLifetime, ?MarshallerInterface $marshaller)
/**
* @param \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy $redis
*/
private function init($redis, string $namespace, int $defaultLifetime, ?MarshallerInterface $marshaller)
{
parent::__construct($namespace, $defaultLifetime);
@@ -56,6 +59,10 @@ trait RedisTrait
throw new InvalidArgumentException(sprintf('RedisAdapter namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
}
if (!$redis instanceof \Redis && !$redis instanceof \RedisArray && !$redis instanceof \RedisCluster && !$redis instanceof \Predis\ClientInterface && !$redis instanceof RedisProxy && !$redis instanceof RedisClusterProxy) {
throw new InvalidArgumentException(sprintf('"%s()" expects parameter 1 to be Redis, RedisArray, RedisCluster or Predis\ClientInterface, "%s" given.', __METHOD__, get_debug_type($redis)));
}
if ($redis instanceof \Predis\ClientInterface && $redis->getOptions()->exceptions) {
$options = clone $redis->getOptions();
\Closure::bind(function () { $this->options['exceptions'] = false; }, $options, $options)();
@@ -78,9 +85,11 @@ trait RedisTrait
*
* @param array $options See self::$defaultConnectionOptions
*
* @return \Redis|\RedisArray|\RedisCluster|RedisClusterProxy|RedisProxy|\Predis\ClientInterface According to the "class" option
*
* @throws InvalidArgumentException when the DSN is invalid
*/
public static function createConnection(string $dsn, array $options = []): \Redis|\RedisArray|\RedisCluster|RedisClusterProxy|RedisProxy|\Predis\ClientInterface
public static function createConnection(string $dsn, array $options = [])
{
if (str_starts_with($dsn, 'redis:')) {
$scheme = 'redis';
@@ -94,13 +103,9 @@ trait RedisTrait
throw new CacheException(sprintf('Cannot find the "redis" extension nor the "predis/predis" package: "%s".', $dsn));
}
$params = preg_replace_callback('#^'.$scheme.':(//)?(?:(?:(?<user>[^:@]*+):)?(?<password>[^@]*+)@)?#', function ($m) use (&$auth) {
if (isset($m['password'])) {
if (\in_array($m['user'], ['', 'default'], true)) {
$auth = $m['password'];
} else {
$auth = [$m['user'], $m['password']];
}
$params = preg_replace_callback('#^'.$scheme.':(//)?(?:(?:[^:@]*+:)?([^@]*+)@)?#', function ($m) use (&$auth) {
if (isset($m[2])) {
$auth = $m[2];
if ('' === $auth) {
$auth = null;
@@ -251,11 +256,11 @@ trait RedisTrait
}
} elseif (is_a($class, \RedisArray::class, true)) {
foreach ($hosts as $i => $host) {
$hosts[$i] = match ($host['scheme']) {
'tcp' => $host['host'].':'.$host['port'],
'tls' => 'tls://'.$host['host'].':'.$host['port'],
default => $host['path'],
};
switch ($host['scheme']) {
case 'tcp': $hosts[$i] = $host['host'].':'.$host['port']; break;
case 'tls': $hosts[$i] = 'tls://'.$host['host'].':'.$host['port']; break;
default: $hosts[$i] = $host['path'];
}
}
$params['lazy_connect'] = $params['lazy'] ?? true;
$params['connect_timeout'] = $params['timeout'];
@@ -272,11 +277,11 @@ trait RedisTrait
} elseif (is_a($class, \RedisCluster::class, true)) {
$initializer = static function () use ($class, $params, $dsn, $hosts) {
foreach ($hosts as $i => $host) {
$hosts[$i] = match ($host['scheme']) {
'tcp' => $host['host'].':'.$host['port'],
'tls' => 'tls://'.$host['host'].':'.$host['port'],
default => $host['path'],
};
switch ($host['scheme']) {
case 'tcp': $hosts[$i] = $host['host'].':'.$host['port']; break;
case 'tls': $hosts[$i] = 'tls://'.$host['host'].':'.$host['port']; break;
default: $hosts[$i] = $host['path'];
}
}
try {
@@ -316,13 +321,7 @@ trait RedisTrait
$params['parameters']['database'] = $params['dbindex'];
}
if (null !== $auth) {
if (\is_array($auth)) {
// ACL
$params['parameters']['username'] = $auth[0];
$params['parameters']['password'] = $auth[1];
} else {
$params['parameters']['password'] = $auth;
}
$params['parameters']['password'] = $auth;
}
if (1 === \count($hosts) && !($params['redis_cluster'] || $params['redis_sentinel'])) {
$hosts = $hosts[0];
@@ -348,7 +347,7 @@ trait RedisTrait
/**
* {@inheritdoc}
*/
protected function doFetch(array $ids): iterable
protected function doFetch(array $ids)
{
if (!$ids) {
return [];
@@ -384,7 +383,7 @@ trait RedisTrait
/**
* {@inheritdoc}
*/
protected function doHave(string $id): bool
protected function doHave(string $id)
{
return (bool) $this->redis->exists($id);
}
@@ -392,7 +391,7 @@ trait RedisTrait
/**
* {@inheritdoc}
*/
protected function doClear(string $namespace): bool
protected function doClear(string $namespace)
{
if ($this->redis instanceof \Predis\ClientInterface) {
$prefix = $this->redis->getOptions()->prefix ? $this->redis->getOptions()->prefix->getPrefix() : '';
@@ -456,7 +455,7 @@ trait RedisTrait
/**
* {@inheritdoc}
*/
protected function doDelete(array $ids): bool
protected function doDelete(array $ids)
{
if (!$ids) {
return true;
@@ -464,7 +463,7 @@ trait RedisTrait
if ($this->redis instanceof \Predis\ClientInterface && $this->redis->getConnection() instanceof ClusterInterface) {
static $del;
$del ??= (class_exists(UNLINK::class) ? 'unlink' : 'del');
$del = $del ?? (class_exists(UNLINK::class) ? 'unlink' : 'del');
$this->pipeline(function () use ($ids, $del) {
foreach ($ids as $id) {
@@ -477,7 +476,7 @@ trait RedisTrait
if ($unlink) {
try {
$unlink = false !== $this->redis->unlink($ids);
} catch (\Throwable) {
} catch (\Throwable $e) {
$unlink = false;
}
}
@@ -493,7 +492,7 @@ trait RedisTrait
/**
* {@inheritdoc}
*/
protected function doSave(array $values, int $lifetime): array|bool
protected function doSave(array $values, int $lifetime)
{
if (!$values = $this->marshaller->marshall($values, $failed)) {
return $failed;
@@ -521,7 +520,7 @@ trait RedisTrait
private function pipeline(\Closure $generator, object $redis = null): \Generator
{
$ids = [];
$redis ??= $this->redis;
$redis = $redis ?? $this->redis;
if ($redis instanceof RedisClusterProxy || $redis instanceof \RedisCluster || ($redis instanceof \Predis\ClientInterface && $redis->getConnection() instanceof RedisCluster)) {
// phpredis & predis don't support pipelining with RedisCluster

View File

@@ -1,81 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A short namespace-less class to serialize items with metadata.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
class <EFBFBD>
{
private const EXPIRY_OFFSET = 1648206727;
private const INT32_MAX = 2147483647;
public readonly mixed $value;
public readonly array $metadata;
public function __construct(mixed $value, array $metadata)
{
$this->value = $value;
$this->metadata = $metadata;
}
public function __serialize(): array
{
// pack 31-bits ctime into 14bits
$c = $this->metadata['ctime'] ?? 0;
$c = match (true) {
$c > self::INT32_MAX - 2 => self::INT32_MAX,
$c > 0 => 1 + $c,
default => 1,
};
$e = 0;
while (!(0x40000000 & $c)) {
$c <<= 1;
++$e;
}
$c = (0x7FE0 & ($c >> 16)) | $e;
$pack = pack('Vn', (int) (0.1 + ($this->metadata['expiry'] ?: self::INT32_MAX + self::EXPIRY_OFFSET) - self::EXPIRY_OFFSET), $c);
if (isset($this->metadata['tags'])) {
$pack[4] = $pack[4] | "\x80";
}
return [$pack => $this->value] + ($this->metadata['tags'] ?? []);
}
public function __unserialize(array $data)
{
$pack = array_key_first($data);
$this->value = $data[$pack];
if ($hasTags = "\x80" === ($pack[4] & "\x80")) {
unset($data[$pack]);
$pack[4] = $pack[4] & "\x7F";
}
$metadata = unpack('Vexpiry/nctime', $pack);
$metadata['expiry'] += self::EXPIRY_OFFSET;
if (!$metadata['ctime'] = ((0x4000 | $metadata['ctime']) << 16 >> (0x1F & $metadata['ctime'])) - 1) {
unset($metadata['ctime']);
}
if ($hasTags) {
$metadata['tags'] = $data;
}
$this->metadata = $metadata;
}
}

View File

@@ -16,41 +16,42 @@
}
],
"provide": {
"psr/cache-implementation": "2.0|3.0",
"psr/simple-cache-implementation": "1.0|2.0|3.0",
"symfony/cache-implementation": "1.1|2.0|3.0"
"psr/cache-implementation": "1.0|2.0",
"psr/simple-cache-implementation": "1.0|2.0",
"symfony/cache-implementation": "1.0|2.0"
},
"require": {
"php": ">=8.1",
"psr/cache": "^2.0|^3.0",
"php": ">=7.2.5",
"psr/cache": "^1.0|^2.0",
"psr/log": "^1.1|^2|^3",
"symfony/cache-contracts": "^1.1.7|^2|^3",
"symfony/cache-contracts": "^1.1.7|^2",
"symfony/deprecation-contracts": "^2.1|^3",
"symfony/polyfill-php73": "^1.9",
"symfony/polyfill-php80": "^1.16",
"symfony/service-contracts": "^1.1|^2|^3",
"symfony/var-exporter": "^5.4|^6.0"
"symfony/var-exporter": "^4.4|^5.0|^6.0"
},
"require-dev": {
"cache/integration-tests": "dev-master",
"doctrine/cache": "^1.6|^2.0",
"doctrine/dbal": "^2.13.1|^3.0",
"predis/predis": "^1.1",
"psr/simple-cache": "^1.0|^2.0|^3.0",
"symfony/config": "^5.4|^6.0",
"symfony/dependency-injection": "^5.4|^6.0",
"symfony/filesystem": "^5.4|^6.0",
"symfony/http-kernel": "^5.4|^6.0",
"symfony/messenger": "^5.4|^6.0",
"symfony/var-dumper": "^5.4|^6.0"
"psr/simple-cache": "^1.0|^2.0",
"symfony/config": "^4.4|^5.0|^6.0",
"symfony/dependency-injection": "^4.4|^5.0|^6.0",
"symfony/filesystem": "^4.4|^5.0|^6.0",
"symfony/http-kernel": "^4.4|^5.0|^6.0",
"symfony/messenger": "^4.4|^5.0|^6.0",
"symfony/var-dumper": "^4.4|^5.0|^6.0"
},
"conflict": {
"doctrine/dbal": "<2.13.1",
"symfony/dependency-injection": "<5.4",
"symfony/http-kernel": "<5.4",
"symfony/var-dumper": "<5.4"
"symfony/dependency-injection": "<4.4",
"symfony/http-kernel": "<4.4",
"symfony/var-dumper": "<4.4"
},
"autoload": {
"psr-4": { "Symfony\\Component\\Cache\\": "" },
"classmap": [
"Traits/ValueWrapper.php"
],
"exclude-from-classmap": [
"/Tests/"
]