This commit is contained in:
Marek
2026-03-24 00:04:55 +01:00
commit c5229e48ed
4225 changed files with 511461 additions and 0 deletions

View File

@@ -0,0 +1,403 @@
<?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\Traits;
use Psr\Cache\CacheItemInterface;
use Psr\Log\LoggerAwareTrait;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
trait AbstractAdapterTrait
{
use LoggerAwareTrait;
/**
* needs to be set by class, signature is function(string <key>, mixed <value>, bool <isHit>).
*/
private static \Closure $createCacheItem;
/**
* needs to be set by class, signature is function(array <deferred>, string <namespace>, array <&expiredIds>).
*/
private static \Closure $mergeByLifetime;
private readonly string $rootNamespace;
private string $namespace = '';
private int $defaultLifetime;
private string $namespaceVersion = '';
private bool $versioningIsEnabled = false;
private array $deferred = [];
private array $ids = [];
/**
* The maximum length to enforce for identifiers or null when no limit applies.
*/
protected ?int $maxIdLength = null;
/**
* Fetches several cache items.
*
* @param array $ids The cache identifiers to fetch
*/
abstract protected function doFetch(array $ids): iterable;
/**
* Confirms if the cache contains specified cache item.
*
* @param string $id The identifier for which to check existence
*/
abstract protected function doHave(string $id): bool;
/**
* Deletes all items in the pool.
*
* @param string $namespace The prefix used for all identifiers managed by this pool
*/
abstract protected function doClear(string $namespace): bool;
/**
* Removes multiple items from the pool.
*
* @param array $ids An array of identifiers that should be removed from the pool
*/
abstract protected function doDelete(array $ids): bool;
/**
* Persists several cache items immediately.
*
* @param array $values The values to cache, indexed by their cache identifier
* @param int $lifetime The lifetime of the cached values, 0 for persisting until manual cleaning
*
* @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;
public function hasItem(mixed $key): bool
{
$id = $this->getId($key);
if (isset($this->deferred[$key])) {
$this->commit();
}
try {
return $this->doHave($id);
} catch (\Exception $e) {
CacheItem::log($this->logger, 'Failed to check if key "{key}" is cached: '.$e->getMessage(), ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
return false;
}
}
public function clear(string $prefix = ''): bool
{
$this->deferred = [];
if ($cleared = $this->versioningIsEnabled) {
$rootNamespace = $this->rootNamespace ??= $this->namespace;
if ('' === $namespaceVersionToClear = $this->namespaceVersion) {
foreach ($this->doFetch([static::NS_SEPARATOR.$rootNamespace]) as $v) {
$namespaceVersionToClear = $v;
}
}
$namespaceToClear = $rootNamespace.$namespaceVersionToClear;
$namespaceVersion = self::formatNamespaceVersion(mt_rand());
try {
$e = $this->doSave([static::NS_SEPARATOR.$rootNamespace => $namespaceVersion], 0);
} catch (\Exception $e) {
}
if (true !== $e && [] !== $e) {
$cleared = false;
$message = 'Failed to save the new namespace'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
CacheItem::log($this->logger, $message, ['exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
} else {
$this->namespaceVersion = $namespaceVersion;
$this->ids = [];
}
} else {
$namespaceToClear = $this->namespace.$prefix;
}
try {
return $this->doClear($namespaceToClear) || $cleared;
} catch (\Exception $e) {
CacheItem::log($this->logger, 'Failed to clear the cache: '.$e->getMessage(), ['exception' => $e, 'cache-adapter' => get_debug_type($this)]);
return false;
}
}
public function deleteItem(mixed $key): bool
{
return $this->deleteItems([$key]);
}
public function deleteItems(array $keys): bool
{
$ids = [];
foreach ($keys as $key) {
$ids[$key] = $this->getId($key);
unset($this->deferred[$key]);
}
try {
if ($this->doDelete($ids)) {
return true;
}
} catch (\Exception) {
}
$ok = true;
// When bulk-delete failed, retry each item individually
foreach ($ids as $key => $id) {
try {
$e = null;
if ($this->doDelete([$id])) {
continue;
}
} catch (\Exception $e) {
}
$message = 'Failed to delete key "{key}"'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
CacheItem::log($this->logger, $message, ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
$ok = false;
}
return $ok;
}
public function getItem(mixed $key): CacheItem
{
$id = $this->getId($key);
if (isset($this->deferred[$key])) {
$this->commit();
}
$isHit = false;
$value = null;
try {
foreach ($this->doFetch([$id]) as $value) {
$isHit = true;
}
return (self::$createCacheItem)($key, $value, $isHit);
} catch (\Exception $e) {
CacheItem::log($this->logger, 'Failed to fetch key "{key}": '.$e->getMessage(), ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
}
return (self::$createCacheItem)($key, null, false);
}
public function getItems(array $keys = []): iterable
{
$ids = [];
$commit = false;
foreach ($keys as $key) {
$ids[] = $this->getId($key);
$commit = $commit || isset($this->deferred[$key]);
}
if ($commit) {
$this->commit();
}
try {
$items = $this->doFetch($ids);
} catch (\Exception $e) {
CacheItem::log($this->logger, 'Failed to fetch items: '.$e->getMessage(), ['keys' => $keys, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
$items = [];
}
$ids = array_combine($ids, $keys);
return $this->generateItems($items, $ids);
}
public function save(CacheItemInterface $item): bool
{
if (!$item instanceof CacheItem) {
return false;
}
$this->deferred[$item->getKey()] = $item;
return $this->commit();
}
public function saveDeferred(CacheItemInterface $item): bool
{
if (!$item instanceof CacheItem) {
return false;
}
$this->deferred[$item->getKey()] = $item;
return true;
}
public function withSubNamespace(string $namespace): static
{
$this->rootNamespace ??= $this->namespace;
$clone = clone $this;
$clone->namespace .= CacheItem::validateKey($namespace).static::NS_SEPARATOR;
return $clone;
}
/**
* Enables/disables versioning of items.
*
* When versioning is enabled, clearing the cache is atomic and doesn't require listing existing keys to proceed,
* but old keys may need garbage collection and extra round-trips to the back-end are required.
*
* Calling this method also clears the memoized namespace version and thus forces a resynchronization of it.
*
* @return bool the previous state of versioning
*/
public function enableVersioning(bool $enable = true): bool
{
$wasEnabled = $this->versioningIsEnabled;
$this->versioningIsEnabled = $enable;
$this->namespaceVersion = '';
$this->ids = [];
return $wasEnabled;
}
public function reset(): void
{
if ($this->deferred) {
$this->commit();
}
$this->namespaceVersion = '';
$this->ids = [];
}
public function __serialize(): array
{
throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
}
public function __unserialize(array $data): void
{
throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
}
public function __destruct()
{
if ($this->deferred) {
$this->commit();
}
}
private function generateItems(iterable $items, array &$keys): \Generator
{
$f = self::$createCacheItem;
try {
foreach ($items as $id => $value) {
if (!isset($keys[$id])) {
throw new InvalidArgumentException(\sprintf('Could not match value id "%s" to keys "%s".', $id, implode('", "', $keys)));
}
$key = $keys[$id];
unset($keys[$id]);
yield $key => $f($key, $value, true);
}
} catch (\Exception $e) {
CacheItem::log($this->logger, 'Failed to fetch items: '.$e->getMessage(), ['keys' => array_values($keys), 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
}
foreach ($keys as $key) {
yield $key => $f($key, null, false);
}
}
/**
* @internal
*/
protected function getId(mixed $key, ?string $namespace = null): string
{
$namespace ??= $this->namespace;
if ('' !== $this->namespaceVersion) {
$namespace .= $this->namespaceVersion;
} elseif ($this->versioningIsEnabled) {
$rootNamespace = $this->rootNamespace ??= $this->namespace;
$this->ids = [];
$this->namespaceVersion = '1'.static::NS_SEPARATOR;
try {
foreach ($this->doFetch([static::NS_SEPARATOR.$rootNamespace]) as $v) {
$this->namespaceVersion = $v;
}
$e = true;
if ('1'.static::NS_SEPARATOR === $this->namespaceVersion) {
$this->namespaceVersion = self::formatNamespaceVersion(time());
$e = $this->doSave([static::NS_SEPARATOR.$rootNamespace => $this->namespaceVersion], 0);
}
} catch (\Exception $e) {
}
if (true !== $e && [] !== $e) {
$message = 'Failed to save the new namespace'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
CacheItem::log($this->logger, $message, ['exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
}
$namespace .= $this->namespaceVersion;
}
if (\is_string($key) && isset($this->ids[$key])) {
$id = $this->ids[$key];
} else {
\assert('' !== CacheItem::validateKey($key));
$this->ids[$key] = $key;
if (\count($this->ids) > 1000) {
$this->ids = \array_slice($this->ids, 500, null, true); // stop memory leak if there are many keys
}
if (null === $this->maxIdLength) {
return $namespace.$key;
}
if (\strlen($id = $namespace.$key) <= $this->maxIdLength) {
return $id;
}
// Use xxh128 to favor speed over security, which is not an issue here
$this->ids[$key] = $id = substr_replace(base64_encode(hash('xxh128', $key, true)), static::NS_SEPARATOR, -(\strlen($this->namespaceVersion) + 2));
}
$id = $namespace.$id;
if (null !== $this->maxIdLength && \strlen($id) > $this->maxIdLength) {
return base64_encode(hash('xxh128', $id, true));
}
return $id;
}
/**
* @internal
*/
public static function handleUnserializeCallback(string $class): never
{
throw new \DomainException('Class not found: '.$class);
}
private static function formatNamespaceVersion(int $value): string
{
return strtr(substr_replace(base64_encode(pack('V', $value)), static::NS_SEPARATOR, 5), '/', '_');
}
}

View File

@@ -0,0 +1,20 @@
<?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\Traits;
/**
* @internal
*/
interface CachedValueInterface
{
public function getValue(): mixed;
}

View File

@@ -0,0 +1,113 @@
<?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\Traits;
use Psr\Log\LoggerInterface;
use Symfony\Component\Cache\Adapter\AdapterInterface;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
use Symfony\Component\Cache\LockRegistry;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\CacheTrait;
use Symfony\Contracts\Cache\ItemInterface;
/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
trait ContractsTrait
{
use CacheTrait {
doGet as private contractsGet;
}
private \Closure $callbackWrapper;
private array $computing = [];
/**
* Wraps the callback passed to ->get() in a callable.
*
* @return callable the previous callback wrapper
*/
public function setCallbackWrapper(?callable $callbackWrapper): callable
{
if (!isset($this->callbackWrapper)) {
$this->callbackWrapper = LockRegistry::compute(...);
if (\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) {
$this->setCallbackWrapper(null);
}
}
if (null !== $callbackWrapper && !$callbackWrapper instanceof \Closure) {
$callbackWrapper = $callbackWrapper(...);
}
$previousWrapper = $this->callbackWrapper;
$this->callbackWrapper = $callbackWrapper ?? static fn (callable $callback, ItemInterface $item, bool &$save, CacheInterface $pool, \Closure $setMetadata, ?LoggerInterface $logger, ?float $beta = null) => $callback($item, $save);
return $previousWrapper;
}
private function doGet(AdapterInterface $pool, string $key, callable $callback, ?float $beta, ?array &$metadata = null): mixed
{
if (0 > $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(
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]);
}
},
null,
CacheItem::class
);
$this->callbackWrapper ??= LockRegistry::compute(...);
return $this->contractsGet($pool, $key, function (CacheItem $item, bool &$save) use ($pool, $callback, $setMetadata, &$metadata, $key, $beta) {
// don't wrap nor save recursive calls
if (isset($this->computing[$key])) {
$value = $callback($item, $save);
$save = false;
return $value;
}
$this->computing[$key] = $key;
$startTime = microtime(true);
if (!isset($this->callbackWrapper)) {
$this->setCallbackWrapper($this->setCallbackWrapper(null));
}
try {
$value = ($this->callbackWrapper)($callback, $item, $save, $pool, function (CacheItem $item) use ($setMetadata, $startTime, &$metadata) {
$setMetadata($item, $startTime, $metadata);
}, $this->logger ?? null, $beta);
$setMetadata($item, $startTime, $metadata);
return $value;
} finally {
unset($this->computing[$key]);
}
}, $beta, $metadata, $this->logger ?? null);
}
}

View File

@@ -0,0 +1,190 @@
<?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\Traits;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
trait FilesystemCommonTrait
{
private string $directory;
private string $tmpSuffix;
private function init(string $namespace, ?string $directory): void
{
if (!isset($directory[0])) {
$directory = sys_get_temp_dir().\DIRECTORY_SEPARATOR.'symfony-cache';
} else {
$directory = realpath($directory) ?: $directory;
}
if (isset($namespace[0])) {
if (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]));
}
$directory .= \DIRECTORY_SEPARATOR.$namespace;
} else {
$directory .= \DIRECTORY_SEPARATOR.'@';
}
if (!is_dir($directory)) {
@mkdir($directory, 0o777, true);
}
$directory .= \DIRECTORY_SEPARATOR;
// On Windows the whole path is limited to 258 chars
if ('\\' === \DIRECTORY_SEPARATOR && \strlen($directory) > 234) {
throw new InvalidArgumentException(\sprintf('Cache directory too long (%s).', $directory));
}
$this->directory = $directory;
}
protected function doClear(string $namespace): bool
{
$ok = true;
foreach ($this->scanHashDir($this->directory) as $file) {
if ('' !== $namespace && !str_starts_with($this->getFileKey($file), $namespace)) {
continue;
}
$ok = ($this->doUnlink($file) || !file_exists($file)) && $ok;
}
return $ok;
}
protected function doDelete(array $ids): bool
{
$ok = true;
foreach ($ids as $id) {
$file = $this->getFile($id);
$ok = (!is_file($file) || $this->doUnlink($file) || !file_exists($file)) && $ok;
}
return $ok;
}
protected function doUnlink(string $file): bool
{
return @unlink($file);
}
private function write(string $file, string $data, ?int $expiresAt = null): bool
{
$unlink = false;
set_error_handler(static fn ($type, $message, $file, $line) => throw new \ErrorException($message, 0, $type, $file, $line));
try {
$tmp = $this->directory.$this->tmpSuffix ??= str_replace('/', '-', base64_encode(random_bytes(6)));
try {
$h = fopen($tmp, 'x');
} catch (\ErrorException $e) {
if (!str_contains($e->getMessage(), 'File exists')) {
throw $e;
}
$tmp = $this->directory.$this->tmpSuffix = str_replace('/', '-', base64_encode(random_bytes(6)));
$h = fopen($tmp, 'x');
}
fwrite($h, $data);
fclose($h);
$unlink = true;
if (null !== $expiresAt) {
touch($tmp, $expiresAt ?: time() + 31556952); // 1 year in seconds
}
if ('\\' === \DIRECTORY_SEPARATOR) {
$success = copy($tmp, $file);
} else {
$success = rename($tmp, $file);
$unlink = !$success;
}
return $success;
} finally {
restore_error_handler();
if ($unlink) {
@unlink($tmp);
}
}
}
private function getFile(string $id, bool $mkdir = false, ?string $directory = null): string
{
// Use xxh128 to favor speed over security, which is not an issue here
$hash = str_replace('/', '-', base64_encode(hash('xxh128', static::class.$id, true)));
$dir = ($directory ?? $this->directory).strtoupper($hash[0].\DIRECTORY_SEPARATOR.$hash[1].\DIRECTORY_SEPARATOR);
if ($mkdir && !is_dir($dir)) {
@mkdir($dir, 0o777, true);
}
return $dir.substr($hash, 2, 20);
}
private function getFileKey(string $file): string
{
return '';
}
private function scanHashDir(string $directory): \Generator
{
if (!is_dir($directory)) {
return;
}
$chars = '+-ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for ($i = 0; $i < 38; ++$i) {
if (!is_dir($directory.$chars[$i])) {
continue;
}
for ($j = 0; $j < 38; ++$j) {
if (!is_dir($dir = $directory.$chars[$i].\DIRECTORY_SEPARATOR.$chars[$j])) {
continue;
}
foreach (@scandir($dir, \SCANDIR_SORT_NONE) ?: [] as $file) {
if ('.' !== $file && '..' !== $file) {
yield $dir.\DIRECTORY_SEPARATOR.$file;
}
}
}
}
}
public function __serialize(): array
{
throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
}
public function __unserialize(array $data): void
{
throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
}
public function __destruct()
{
if (method_exists(parent::class, '__destruct')) {
parent::__destruct();
}
if (isset($this->tmpSuffix) && is_file($this->directory.$this->tmpSuffix)) {
unlink($this->directory.$this->tmpSuffix);
}
}
}

View File

@@ -0,0 +1,113 @@
<?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\Traits;
use Symfony\Component\Cache\Exception\CacheException;
use Symfony\Component\Cache\Marshaller\MarshallerInterface;
/**
* @author Nicolas Grekas <p@tchwork.com>
* @author Rob Frawley 2nd <rmf@src.run>
*
* @internal
*/
trait FilesystemTrait
{
use FilesystemCommonTrait;
private MarshallerInterface $marshaller;
public function prune(): bool
{
$time = time();
$pruned = true;
foreach ($this->scanHashDir($this->directory) as $file) {
if (!$h = @fopen($file, 'r')) {
continue;
}
if (($expiresAt = (int) fgets($h)) && $time >= $expiresAt) {
fclose($h);
$pruned = (@unlink($file) || !file_exists($file)) && $pruned;
} else {
fclose($h);
}
}
return $pruned;
}
protected function doFetch(array $ids): iterable
{
$values = [];
$now = time();
foreach ($ids as $id) {
$file = $this->getFile($id);
if (!is_file($file) || !$h = @fopen($file, 'r')) {
continue;
}
if (($expiresAt = (int) fgets($h)) && $now >= $expiresAt) {
fclose($h);
@unlink($file);
} else {
$i = rawurldecode(rtrim(fgets($h)));
$value = stream_get_contents($h);
fclose($h);
if ($i === $id) {
$values[$id] = $this->marshaller->unmarshall($value);
}
}
}
return $values;
}
protected function doHave(string $id): bool
{
$file = $this->getFile($id);
return is_file($file) && (@filemtime($file) > time() || $this->doFetch([$id]));
}
protected function doSave(array $values, int $lifetime): array|bool
{
$expiresAt = $lifetime ? (time() + $lifetime) : 0;
$values = $this->marshaller->marshall($values, $failed);
foreach ($values as $id => $value) {
if (!$this->write($this->getFile($id, true), $expiresAt."\n".rawurlencode($id)."\n".$value, $expiresAt)) {
$failed[] = $id;
}
}
if ($failed && !is_writable($this->directory)) {
throw new CacheException(\sprintf('Cache directory is not writable (%s).', $this->directory));
}
return $failed;
}
private function getFileKey(string $file): string
{
if (!$h = @fopen($file, 'r')) {
return '';
}
fgets($h); // expiry
$encodedKey = fgets($h);
fclose($h);
return rawurldecode(rtrim($encodedKey));
}
}

View File

@@ -0,0 +1,37 @@
<?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\Traits;
use Symfony\Component\Cache\PruneableInterface;
use Symfony\Contracts\Service\ResetInterface;
/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
trait ProxyTrait
{
private object $pool;
public function prune(): bool
{
return $this->pool instanceof PruneableInterface && $this->pool->prune();
}
public function reset(): void
{
if ($this->pool instanceof ResetInterface) {
$this->pool->reset();
}
}
}

View File

@@ -0,0 +1,52 @@
<?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\Traits;
if (version_compare(phpversion('redis'), '6.2.0', '>=')) {
/**
* @internal
*/
trait Redis62ProxyTrait
{
public function expiremember($key, $field, $ttl, $unit = null): \Redis|false|int
{
return $this->initializeLazyObject()->expiremember(...\func_get_args());
}
public function expirememberat($key, $field, $timestamp): \Redis|false|int
{
return $this->initializeLazyObject()->expirememberat(...\func_get_args());
}
public function getWithMeta($key): \Redis|array|false
{
return $this->initializeLazyObject()->getWithMeta(...\func_get_args());
}
public function serverName(): false|string
{
return $this->initializeLazyObject()->serverName(...\func_get_args());
}
public function serverVersion(): false|string
{
return $this->initializeLazyObject()->serverVersion(...\func_get_args());
}
}
} else {
/**
* @internal
*/
trait Redis62ProxyTrait
{
}
}

View File

@@ -0,0 +1,162 @@
<?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\Traits;
if (version_compare(phpversion('redis'), '6.3.0', '>=')) {
/**
* @internal
*/
trait Redis63ProxyTrait
{
public function delifeq($key, $value): \Redis|int|false
{
return $this->initializeLazyObject()->delifeq(...\func_get_args());
}
public function hexpire($key, $ttl, $fields, $mode = null): \Redis|array|false
{
return $this->initializeLazyObject()->hexpire(...\func_get_args());
}
public function hexpireat($key, $time, $fields, $mode = null): \Redis|array|false
{
return $this->initializeLazyObject()->hexpireat(...\func_get_args());
}
public function hexpiretime($key, $fields): \Redis|array|false
{
return $this->initializeLazyObject()->hexpiretime(...\func_get_args());
}
public function hgetdel($key, $fields): \Redis|array|false
{
return $this->initializeLazyObject()->hgetdel(...\func_get_args());
}
public function hgetex($key, $fields, $expiry = null): \Redis|array|false
{
return $this->initializeLazyObject()->hgetex(...\func_get_args());
}
public function hGetWithMeta($key, $member): mixed
{
return $this->initializeLazyObject()->hGetWithMeta(...\func_get_args());
}
public function hpersist($key, $fields): \Redis|array|false
{
return $this->initializeLazyObject()->hpersist(...\func_get_args());
}
public function hpexpire($key, $ttl, $fields, $mode = null): \Redis|array|false
{
return $this->initializeLazyObject()->hpexpire(...\func_get_args());
}
public function hpexpireat($key, $mstime, $fields, $mode = null): \Redis|array|false
{
return $this->initializeLazyObject()->hpexpireat(...\func_get_args());
}
public function hpexpiretime($key, $fields): \Redis|array|false
{
return $this->initializeLazyObject()->hpexpiretime(...\func_get_args());
}
public function hpttl($key, $fields): \Redis|array|false
{
return $this->initializeLazyObject()->hpttl(...\func_get_args());
}
public function hsetex($key, $fields, $expiry = null): \Redis|int|false
{
return $this->initializeLazyObject()->hsetex(...\func_get_args());
}
public function httl($key, $fields): \Redis|array|false
{
return $this->initializeLazyObject()->httl(...\func_get_args());
}
public function vadd($key, $values, $element, $options = null): \Redis|int|false
{
return $this->initializeLazyObject()->vadd(...\func_get_args());
}
public function vcard($key): \Redis|int|false
{
return $this->initializeLazyObject()->vcard(...\func_get_args());
}
public function vdim($key): \Redis|int|false
{
return $this->initializeLazyObject()->vdim(...\func_get_args());
}
public function vemb($key, $member, $raw = false): \Redis|array|false
{
return $this->initializeLazyObject()->vemb(...\func_get_args());
}
public function vgetattr($key, $member, $decode = true): \Redis|array|string|false
{
return $this->initializeLazyObject()->vgetattr(...\func_get_args());
}
public function vinfo($key): \Redis|array|false
{
return $this->initializeLazyObject()->vinfo(...\func_get_args());
}
public function vismember($key, $member): \Redis|bool
{
return $this->initializeLazyObject()->vismember(...\func_get_args());
}
public function vlinks($key, $member, $withscores = false): \Redis|array|false
{
return $this->initializeLazyObject()->vlinks(...\func_get_args());
}
public function vrandmember($key, $count = 0): \Redis|array|string|false
{
return $this->initializeLazyObject()->vrandmember(...\func_get_args());
}
public function vrange($key, $min, $max, $count = -1): \Redis|array|false
{
return $this->initializeLazyObject()->vrange(...\func_get_args());
}
public function vrem($key, $member): \Redis|int|false
{
return $this->initializeLazyObject()->vrem(...\func_get_args());
}
public function vsetattr($key, $member, $attributes): \Redis|int|false
{
return $this->initializeLazyObject()->vsetattr(...\func_get_args());
}
public function vsim($key, $member, $options = null): \Redis|array|false
{
return $this->initializeLazyObject()->vsim(...\func_get_args());
}
}
} else {
/**
* @internal
*/
trait Redis63ProxyTrait
{
}
}

View File

@@ -0,0 +1,47 @@
<?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\Traits;
if (version_compare(phpversion('redis'), '6.2.0', '>=')) {
/**
* @internal
*/
trait RedisCluster62ProxyTrait
{
public function expiremember($key, $field, $ttl, $unit = null): \Redis|false|int
{
return $this->initializeLazyObject()->expiremember(...\func_get_args());
}
public function expirememberat($key, $field, $timestamp): \Redis|false|int
{
return $this->initializeLazyObject()->expirememberat(...\func_get_args());
}
public function getdel($key): mixed
{
return $this->initializeLazyObject()->getdel(...\func_get_args());
}
public function getWithMeta($key): \RedisCluster|array|false
{
return $this->initializeLazyObject()->getWithMeta(...\func_get_args());
}
}
} else {
/**
* @internal
*/
trait RedisCluster62ProxyTrait
{
}
}

View File

@@ -0,0 +1,162 @@
<?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\Traits;
if (version_compare(phpversion('redis'), '6.3.0', '>=')) {
/**
* @internal
*/
trait RedisCluster63ProxyTrait
{
public function delifeq($key, $value): \RedisCluster|int|false
{
return $this->initializeLazyObject()->delifeq(...\func_get_args());
}
public function hexpire($key, $ttl, $fields, $mode = null): \RedisCluster|array|false
{
return $this->initializeLazyObject()->hexpire(...\func_get_args());
}
public function hexpireat($key, $time, $fields, $mode = null): \RedisCluster|array|false
{
return $this->initializeLazyObject()->hexpireat(...\func_get_args());
}
public function hexpiretime($key, $fields): \RedisCluster|array|false
{
return $this->initializeLazyObject()->hexpiretime(...\func_get_args());
}
public function hgetdel($key, $fields): \RedisCluster|array|false
{
return $this->initializeLazyObject()->hgetdel(...\func_get_args());
}
public function hgetex($key, $fields, $expiry = null): \RedisCluster|array|false
{
return $this->initializeLazyObject()->hgetex(...\func_get_args());
}
public function hgetWithMeta($key, $member): mixed
{
return $this->initializeLazyObject()->hgetWithMeta(...\func_get_args());
}
public function hpersist($key, $fields): \RedisCluster|array|false
{
return $this->initializeLazyObject()->hpersist(...\func_get_args());
}
public function hpexpire($key, $ttl, $fields, $mode = null): \RedisCluster|array|false
{
return $this->initializeLazyObject()->hpexpire(...\func_get_args());
}
public function hpexpireat($key, $mstime, $fields, $mode = null): \RedisCluster|array|false
{
return $this->initializeLazyObject()->hpexpireat(...\func_get_args());
}
public function hpexpiretime($key, $fields): \RedisCluster|array|false
{
return $this->initializeLazyObject()->hpexpiretime(...\func_get_args());
}
public function hpttl($key, $fields): \RedisCluster|array|false
{
return $this->initializeLazyObject()->hpttl(...\func_get_args());
}
public function hsetex($key, $fields, $expiry = null): \RedisCluster|int|false
{
return $this->initializeLazyObject()->hsetex(...\func_get_args());
}
public function httl($key, $fields): \RedisCluster|array|false
{
return $this->initializeLazyObject()->httl(...\func_get_args());
}
public function vadd($key, $values, $element, $options = null): \RedisCluster|int|false
{
return $this->initializeLazyObject()->vadd(...\func_get_args());
}
public function vcard($key): \RedisCluster|int|false
{
return $this->initializeLazyObject()->vcard(...\func_get_args());
}
public function vdim($key): \RedisCluster|int|false
{
return $this->initializeLazyObject()->vdim(...\func_get_args());
}
public function vemb($key, $member, $raw = false): \RedisCluster|array|false
{
return $this->initializeLazyObject()->vemb(...\func_get_args());
}
public function vgetattr($key, $member, $decode = true): \RedisCluster|array|string|false
{
return $this->initializeLazyObject()->vgetattr(...\func_get_args());
}
public function vinfo($key): \RedisCluster|array|false
{
return $this->initializeLazyObject()->vinfo(...\func_get_args());
}
public function vismember($key, $member): \RedisCluster|bool
{
return $this->initializeLazyObject()->vismember(...\func_get_args());
}
public function vlinks($key, $member, $withscores = false): \RedisCluster|array|false
{
return $this->initializeLazyObject()->vlinks(...\func_get_args());
}
public function vrandmember($key, $count = 0): \RedisCluster|array|string|false
{
return $this->initializeLazyObject()->vrandmember(...\func_get_args());
}
public function vrange($key, $min, $max, $count = -1): \RedisCluster|array|false
{
return $this->initializeLazyObject()->vrange(...\func_get_args());
}
public function vrem($key, $member): \RedisCluster|int|false
{
return $this->initializeLazyObject()->vrem(...\func_get_args());
}
public function vsetattr($key, $member, $attributes): \RedisCluster|int|false
{
return $this->initializeLazyObject()->vsetattr(...\func_get_args());
}
public function vsim($key, $member, $options = null): \RedisCluster|array|false
{
return $this->initializeLazyObject()->vsim(...\func_get_args());
}
}
} else {
/**
* @internal
*/
trait RedisCluster63ProxyTrait
{
}
}

View File

@@ -0,0 +1,47 @@
<?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\Traits;
/**
* This file acts as a wrapper to the \RedisCluster implementation so it can accept the same type of calls as
* individual \Redis objects.
*
* Calls are made to individual nodes via: RedisCluster->{method}($host, ...args)'
* according to https://github.com/phpredis/phpredis/blob/develop/cluster.markdown#directed-node-commands
*
* @author Jack Thomas <jack.thomas@solidalpha.com>
*
* @internal
*/
class RedisClusterNodeProxy
{
public function __construct(
private array $host,
private \RedisCluster $redis,
) {
}
public function __call(string $method, array $args)
{
return $this->redis->{$method}($this->host, ...$args);
}
public function scan(&$iIterator, $strPattern = null, $iCount = null)
{
return $this->redis->scan($iIterator, $this->host, $strPattern, $iCount);
}
public function getOption($name)
{
return $this->redis->getOption($name);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,51 @@
<?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\Traits;
/**
* @internal
*/
trait RedisProxyTrait
{
private \Closure $initializer;
private ?parent $realInstance = null;
public static function createLazyProxy(\Closure $initializer, ?self $instance = null): static
{
$instance ??= (new \ReflectionClass(static::class))->newInstanceWithoutConstructor();
$instance->realInstance = null;
$instance->initializer = $initializer;
return $instance;
}
public function isLazyObjectInitialized(bool $partial = false): bool
{
return isset($this->realInstance);
}
public function initializeLazyObject(): object
{
return $this->realInstance ??= ($this->initializer)();
}
public function resetLazyObject(): bool
{
$this->realInstance = null;
return true;
}
public function __destruct()
{
}
}

View File

@@ -0,0 +1,827 @@
<?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\Traits;
use Predis\Command\Redis\UNLINK;
use Predis\Connection\Aggregate\ClusterInterface;
use Predis\Connection\Aggregate\RedisCluster;
use Predis\Connection\Aggregate\ReplicationInterface;
use Predis\Connection\Cluster\ClusterInterface as Predis2ClusterInterface;
use Predis\Connection\Cluster\RedisCluster as Predis2RedisCluster;
use Predis\Connection\Replication\ReplicationInterface as Predis2ReplicationInterface;
use Predis\Response\ErrorInterface;
use Predis\Response\Status;
use Relay\Cluster as RelayCluster;
use Relay\Relay;
use Relay\Sentinel;
use Symfony\Component\Cache\Exception\CacheException;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
use Symfony\Component\Cache\Marshaller\MarshallerInterface;
/**
* @author Aurimas Niekis <aurimas@niekis.lt>
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
trait RedisTrait
{
private static array $defaultConnectionOptions = [
'class' => null,
'auth' => null,
'persistent' => false,
'persistent_id' => null,
'timeout' => 30,
'read_timeout' => 0,
'retry_interval' => 0,
'tcp_keepalive' => 0,
'lazy' => null,
'cluster' => false,
'cluster_command_timeout' => 0,
'cluster_relay_context' => [],
'sentinel' => null,
'dbindex' => 0,
'failover' => 'none',
'ssl' => null, // see https://php.net/context.ssl
];
private \Redis|Relay|RelayCluster|\RedisArray|\RedisCluster|\Predis\ClientInterface $redis;
private MarshallerInterface $marshaller;
private function init(\Redis|Relay|RelayCluster|\RedisArray|\RedisCluster|\Predis\ClientInterface $redis, string $namespace, int $defaultLifetime, ?MarshallerInterface $marshaller): void
{
parent::__construct($namespace, $defaultLifetime);
if (preg_match('#[^-+_.A-Za-z0-9]#', $namespace, $match)) {
throw new InvalidArgumentException(\sprintf('RedisAdapter namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
}
if ($redis instanceof \Predis\ClientInterface && $redis->getOptions()->exceptions) {
$options = clone $redis->getOptions();
\Closure::bind(function () { $this->options['exceptions'] = false; }, $options, $options)();
$redis = new $redis($redis->getConnection(), $options);
}
$this->redis = $redis;
$this->marshaller = $marshaller ?? new DefaultMarshaller();
}
/**
* Creates a Redis connection using a DSN configuration.
*
* Example DSN:
* - redis://localhost
* - redis://example.com:1234
* - redis://secret@example.com/13
* - redis:///var/run/redis.sock
* - redis://secret@/var/run/redis.sock/13
*
* @param array $options See self::$defaultConnectionOptions
*
* @throws InvalidArgumentException when the DSN is invalid
*/
public static function createConnection(#[\SensitiveParameter] string $dsn, array $options = []): \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|Relay|RelayCluster
{
$scheme = match (true) {
str_starts_with($dsn, 'redis:') => 'redis',
str_starts_with($dsn, 'rediss:') => 'rediss',
str_starts_with($dsn, 'valkey:') => 'valkey',
str_starts_with($dsn, 'valkeys:') => 'valkeys',
default => throw new InvalidArgumentException('Invalid Redis DSN: it does not start with "redis[s]:" nor "valkey[s]:".'),
};
if (!\extension_loaded('redis') && !\extension_loaded('relay') && !class_exists(\Predis\Client::class)) {
throw new CacheException('Cannot find the "redis" extension nor the "relay" extension nor the "predis/predis" package.');
}
$auth = null;
$params = preg_replace_callback('#^'.$scheme.':(//)?(?:(?:(?<user>[^:@]*+):)?(?<password>[^@]*+)@)?#', function ($m) use (&$auth) {
if (isset($m['password'])) {
if (\in_array($m['user'], ['', 'default'], true)) {
$auth = rawurldecode($m['password']);
} else {
$auth = [rawurldecode($m['user']), rawurldecode($m['password'])];
}
if ('' === $auth) {
$auth = null;
}
}
return 'file:'.($m[1] ?? '');
}, $dsn);
if (false === $params = parse_url($params)) {
throw new InvalidArgumentException('Invalid Redis DSN.');
}
$query = $hosts = [];
$tls = 'rediss' === $scheme || 'valkeys' === $scheme;
$tcpScheme = $tls ? 'tls' : 'tcp';
if (isset($params['query'])) {
parse_str($params['query'], $query);
if (isset($query['host'])) {
if (!\is_array($hosts = $query['host'])) {
throw new InvalidArgumentException('Invalid Redis DSN: query parameter "host" must be an array.');
}
foreach ($hosts as $host => $parameters) {
if (\is_string($parameters)) {
parse_str($parameters, $parameters);
}
if (false === $i = strrpos($host, ':')) {
$hosts[$host] = ['scheme' => $tcpScheme, 'host' => $host, 'port' => 6379] + $parameters;
} elseif ($port = (int) substr($host, 1 + $i)) {
$hosts[$host] = ['scheme' => $tcpScheme, 'host' => substr($host, 0, $i), 'port' => $port] + $parameters;
} else {
$hosts[$host] = ['scheme' => 'unix', 'path' => substr($host, 0, $i)] + $parameters;
}
}
$hosts = array_values($hosts);
}
}
if (isset($params['host']) || isset($params['path'])) {
if (!isset($params['dbindex']) && isset($params['path'])) {
if (preg_match('#/(\d+)?$#', $params['path'], $m)) {
$params['dbindex'] = $m[1] ?? $query['dbindex'] ?? '0';
$params['path'] = substr($params['path'], 0, -\strlen($m[0]));
} elseif (isset($params['host'])) {
throw new InvalidArgumentException('Invalid Redis DSN: parameter "dbindex" must be a number.');
}
}
if (isset($params['host'])) {
array_unshift($hosts, ['scheme' => $tcpScheme, 'host' => $params['host'], 'port' => $params['port'] ?? 6379]);
} else {
array_unshift($hosts, ['scheme' => 'unix', 'path' => $params['path']]);
}
}
if (!$hosts) {
throw new InvalidArgumentException('Invalid Redis DSN: missing host.');
}
if (isset($params['dbindex'], $query['dbindex']) && $params['dbindex'] !== $query['dbindex']) {
throw new InvalidArgumentException('Invalid Redis DSN: path and query "dbindex" parameters mismatch.');
}
$params += $query + $options + self::$defaultConnectionOptions;
$booleanStreamOptions = [
'allow_self_signed',
'capture_peer_cert',
'capture_peer_cert_chain',
'disable_compression',
'SNI_enabled',
'verify_peer',
'verify_peer_name',
];
foreach ($params['ssl'] ?? [] as $streamOption => $value) {
if (\in_array($streamOption, $booleanStreamOptions, true) && \is_string($value)) {
$params['ssl'][$streamOption] = filter_var($value, \FILTER_VALIDATE_BOOL);
}
}
$aliases = [
'sentinel_master' => 'sentinel',
'redis_sentinel' => 'sentinel',
'redis_cluster' => 'cluster',
];
foreach ($aliases as $alias => $key) {
$params[$key] = match (true) {
\array_key_exists($key, $query) => $query[$key],
\array_key_exists($alias, $query) => $query[$alias],
\array_key_exists($key, $options) => $options[$key],
\array_key_exists($alias, $options) => $options[$alias],
default => $params[$key],
};
}
if (!isset($params['sentinel'])) {
$params['auth'] ??= $auth;
$sentinelAuth = null;
} elseif (!class_exists(\Predis\Client::class) && !class_exists(\RedisSentinel::class) && !class_exists(Sentinel::class)) {
throw new CacheException('Redis Sentinel support requires one of: "predis/predis", "ext-redis >= 6.1", "ext-relay".');
} else {
$sentinelAuth = $params['auth'] ?? null;
$params['auth'] = $auth ?? $params['auth'];
}
foreach (['lazy', 'persistent', 'cluster'] as $option) {
if (!\is_bool($params[$option] ?? false)) {
$params[$option] = filter_var($params[$option], \FILTER_VALIDATE_BOOLEAN);
}
}
if ($params['cluster'] && isset($params['sentinel'])) {
throw new InvalidArgumentException('Cannot use both "cluster" and "sentinel" at the same time.');
}
$class = $params['class'] ?? match (true) {
$params['cluster'] => match (true) {
\extension_loaded('redis') => \RedisCluster::class,
\extension_loaded('relay') => RelayCluster::class,
default => \Predis\Client::class,
},
isset($params['sentinel']) => match (true) {
\extension_loaded('redis') => \Redis::class,
\extension_loaded('relay') => Relay::class,
default => \Predis\Client::class,
},
1 < \count($hosts) && \extension_loaded('redis') => \RedisArray::class,
\extension_loaded('redis') => \Redis::class,
\extension_loaded('relay') => Relay::class,
default => \Predis\Client::class,
};
if (isset($params['sentinel']) && !is_a($class, \Predis\Client::class, true) && !class_exists(\RedisSentinel::class) && !class_exists(Sentinel::class)) {
throw new CacheException(\sprintf('Cannot use Redis Sentinel: class "%s" does not extend "Predis\Client" and neither ext-redis >= 6.1 nor ext-relay have been found.', $class));
}
$isRedisExt = is_a($class, \Redis::class, true);
$isRelayExt = !$isRedisExt && is_a($class, Relay::class, true);
if ($isRedisExt || $isRelayExt) {
$connect = $params['persistent'] || $params['persistent_id'] ? 'pconnect' : 'connect';
$initializer = static function () use ($class, $isRedisExt, $connect, $params, $sentinelAuth, $hosts, $tls) {
$sentinelClass = $isRedisExt ? \RedisSentinel::class : Sentinel::class;
$redis = new $class();
$hostIndex = 0;
do {
$host = $hosts[$hostIndex]['host'] ?? $hosts[$hostIndex]['path'];
$port = $hosts[$hostIndex]['port'] ?? 0;
$passAuth = null !== $sentinelAuth && (!$isRedisExt || \defined('Redis::OPT_NULL_MULTIBULK_AS_NULL'));
$address = false;
if (isset($hosts[$hostIndex]['host']) && $tls) {
$host = 'tls://'.$host;
}
if (!isset($params['sentinel'])) {
break;
}
try {
if ($isRedisExt) {
$options = [
'host' => $host,
'port' => $port,
'connectTimeout' => (float) $params['timeout'],
'persistent' => $params['persistent_id'],
'retryInterval' => (int) $params['retry_interval'],
'readTimeout' => (float) $params['read_timeout'],
];
if ($passAuth) {
$options['auth'] = $sentinelAuth;
}
if (null !== $params['ssl'] && version_compare(phpversion('redis'), '6.2.0', '>=')) {
$options['ssl'] = $params['ssl'];
}
$sentinel = new \RedisSentinel($options);
} else {
$extra = $passAuth ? [$sentinelAuth] : [];
$sentinel = @new $sentinelClass($host, $port, $params['timeout'], (string) $params['persistent_id'], $params['retry_interval'], $params['read_timeout'], ...$extra);
}
if ($address = @$sentinel->getMasterAddrByName($params['sentinel'])) {
[$host, $port] = $address;
}
} catch (\RedisException|\Relay\Exception $redisException) {
}
} while (++$hostIndex < \count($hosts) && !$address);
if (isset($params['sentinel']) && !$address) {
throw new InvalidArgumentException(\sprintf('Failed to retrieve master information from sentinel "%s".', $params['sentinel']), previous: $redisException ?? null);
}
try {
$extra = [
'stream' => self::filterSslOptions($params['ssl'] ?? []) ?: null,
];
if (null !== $params['auth']) {
$extra['auth'] = $params['auth'];
}
@$redis->{$connect}($host, $port, (float) $params['timeout'], (string) $params['persistent_id'], $params['retry_interval'], $params['read_timeout'], ...\defined('Redis::SCAN_PREFIX') || !$isRedisExt ? [$extra] : []);
set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
try {
$isConnected = $redis->isConnected();
} finally {
restore_error_handler();
}
if (!$isConnected) {
$error = preg_match('/^Redis::p?connect\(\): (.*)/', $error ?? $redis->getLastError() ?? '', $error) ? \sprintf(' (%s)', $error[1]) : '';
throw new InvalidArgumentException('Redis connection failed: '.$error.'.');
}
if (0 < $params['tcp_keepalive'] && (!$isRedisExt || \defined('Redis::OPT_TCP_KEEPALIVE'))) {
$redis->setOption($isRedisExt ? \Redis::OPT_TCP_KEEPALIVE : Relay::OPT_TCP_KEEPALIVE, $params['tcp_keepalive']);
}
if (!$redis->select($params['dbindex'])) {
$e = preg_replace('/^ERR /', '', $redis->getLastError());
throw new InvalidArgumentException('Redis connection failed: '.$e.'.');
}
} catch (\RedisException|\Relay\Exception $e) {
throw new InvalidArgumentException('Redis connection failed: '.$e->getMessage());
}
return $redis;
};
if ($params['lazy']) {
$redis = $isRedisExt ? RedisProxy::createLazyProxy($initializer) : RelayProxy::createLazyProxy($initializer);
} else {
$redis = $initializer();
}
} 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'],
};
}
$params['lazy_connect'] = $params['lazy'] ?? true;
$params['connect_timeout'] = $params['timeout'];
try {
$redis = new $class($hosts, $params);
} catch (\RedisClusterException $e) {
throw new InvalidArgumentException('Redis connection failed: '.$e->getMessage());
}
if (0 < $params['tcp_keepalive'] && (!$isRedisExt || \defined('Redis::OPT_TCP_KEEPALIVE'))) {
$redis->setOption($isRedisExt ? \Redis::OPT_TCP_KEEPALIVE : Relay::OPT_TCP_KEEPALIVE, $params['tcp_keepalive']);
}
} elseif (is_a($class, RelayCluster::class, true)) {
$initializer = static function () use ($class, $params, $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'],
};
}
try {
$context = $params['cluster_relay_context'];
$context['stream'] = self::filterSslOptions($params['ssl'] ?? []) ?: null;
foreach ($context as $name => $value) {
match ($name) {
'use-cache', 'client-tracking', 'throw-on-error', 'client-invalidations', 'reply-literal', 'persistent',
=> $context[$name] = filter_var($value, \FILTER_VALIDATE_BOOLEAN),
'max-retries', 'serializer', 'compression', 'compression-level',
=> $context[$name] = filter_var($value, \FILTER_VALIDATE_INT),
default => null,
};
}
$relayCluster = new $class(
name: null,
seeds: $hosts,
connect_timeout: $params['timeout'],
command_timeout: $params['cluster_command_timeout'],
persistent: $params['persistent'],
auth: $params['auth'] ?? null,
context: $context,
);
} catch (\Relay\Exception $e) {
throw new InvalidArgumentException('Relay cluster connection failed: '.$e->getMessage());
}
if (0 < $params['tcp_keepalive']) {
$relayCluster->setOption(Relay::OPT_TCP_KEEPALIVE, $params['tcp_keepalive']);
}
if (0 < $params['read_timeout']) {
$relayCluster->setOption(Relay::OPT_READ_TIMEOUT, $params['read_timeout']);
}
return $relayCluster;
};
$redis = $params['lazy'] ? RelayClusterProxy::createLazyProxy($initializer) : $initializer();
} elseif (is_a($class, \RedisCluster::class, true)) {
$initializer = static function () use ($isRedisExt, $class, $params, $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'],
};
}
try {
$redis = new $class(null, $hosts, $params['timeout'], $params['read_timeout'], $params['persistent'], $params['auth'] ?? '', ...\defined('Redis::SCAN_PREFIX') ? [$params['ssl'] ?? null] : []);
} catch (\RedisClusterException $e) {
throw new InvalidArgumentException('Redis connection failed: '.$e->getMessage());
}
if (0 < $params['tcp_keepalive'] && (!$isRedisExt || \defined('Redis::OPT_TCP_KEEPALIVE'))) {
$redis->setOption($isRedisExt ? \Redis::OPT_TCP_KEEPALIVE : Relay::OPT_TCP_KEEPALIVE, $params['tcp_keepalive']);
}
$redis->setOption(\RedisCluster::OPT_SLAVE_FAILOVER, match ($params['failover']) {
'error' => \RedisCluster::FAILOVER_ERROR,
'distribute' => \RedisCluster::FAILOVER_DISTRIBUTE,
'slaves' => \RedisCluster::FAILOVER_DISTRIBUTE_SLAVES,
'none' => \RedisCluster::FAILOVER_NONE,
});
return $redis;
};
$redis = $params['lazy'] ? RedisClusterProxy::createLazyProxy($initializer) : $initializer();
} elseif (is_a($class, \Predis\ClientInterface::class, true)) {
if ($params['cluster']) {
$params['cluster'] = 'redis';
} else {
unset($params['cluster']);
}
if (isset($params['sentinel'])) {
$params['replication'] = 'sentinel';
$params['service'] = $params['sentinel'];
}
$params += ['parameters' => []];
$params['parameters'] += [
'persistent' => $params['persistent'],
'timeout' => $params['timeout'],
'read_write_timeout' => $params['read_timeout'],
'tcp_nodelay' => true,
];
if ($params['dbindex']) {
$params['parameters']['database'] = $params['dbindex'];
}
if (\is_array($params['auth'])) {
// ACL
$params['parameters']['username'] = $params['auth'][0];
$params['parameters']['password'] = $params['auth'][1];
} elseif (null !== $params['auth']) {
$params['parameters']['password'] = $params['auth'];
}
if (isset($params['sentinel']) && null !== $sentinelAuth) {
if (\is_array($sentinelAuth)) {
$sentinelUsername = $sentinelAuth[0];
$sentinelPassword = $sentinelAuth[1];
} else {
$sentinelUsername = null;
$sentinelPassword = $sentinelAuth;
}
foreach ($hosts as $i => $host) {
$hosts[$i]['password'] ??= $sentinelPassword;
if (null !== $sentinelUsername) {
$hosts[$i]['username'] ??= $sentinelUsername;
}
}
}
if (isset($params['ssl'])) {
foreach ($hosts as $i => $host) {
$hosts[$i]['ssl'] ??= $params['ssl'];
}
}
if (1 === \count($hosts) && !isset($params['cluster']) & !isset($params['sentinel'])) {
$hosts = $hosts[0];
} elseif (\in_array($params['failover'], ['slaves', 'distribute'], true) && !isset($params['replication'])) {
$params['replication'] = true;
$hosts[0] += ['alias' => 'master'];
}
$params['exceptions'] = false;
$redis = new $class($hosts, array_diff_key($params, array_diff_key(self::$defaultConnectionOptions, ['cluster' => null])));
if (isset($params['sentinel'])) {
$redis->getConnection()->setSentinelTimeout($params['timeout']);
}
} elseif (class_exists($class, false)) {
throw new InvalidArgumentException(\sprintf('"%s" is not a subclass of "Redis", "RedisArray", "RedisCluster", "Relay\Relay" nor "Predis\ClientInterface".', $class));
} else {
throw new InvalidArgumentException(\sprintf('Class "%s" does not exist.', $class));
}
return $redis;
}
protected function doFetch(array $ids): iterable
{
if (!$ids) {
return [];
}
$result = [];
if (($this->redis instanceof \Predis\ClientInterface && ($this->redis->getConnection() instanceof ClusterInterface || $this->redis->getConnection() instanceof Predis2ClusterInterface)) || $this->redis instanceof RelayCluster) {
$values = $this->pipeline(function () use ($ids) {
foreach ($ids as $id) {
yield 'get' => [$id];
}
});
} else {
$values = $this->redis->mget($ids);
if (!\is_array($values) || \count($values) !== \count($ids)) {
return [];
}
$values = array_combine($ids, $values);
}
foreach ($values as $id => $v) {
if ($v) {
$result[$id] = $this->marshaller->unmarshall($v);
}
}
return $result;
}
protected function doHave(string $id): bool
{
return (bool) $this->redis->exists($id);
}
protected function doClear(string $namespace): bool
{
if ($this->redis instanceof \Predis\ClientInterface) {
$prefix = $this->redis->getOptions()->prefix ? $this->redis->getOptions()->prefix->getPrefix() : '';
$prefixLen = \strlen($prefix ?? '');
}
$cleared = true;
if ($this->redis instanceof RelayCluster) {
$prefix = Relay::SCAN_PREFIX & $this->redis->getOption(Relay::OPT_SCAN) ? '' : $this->redis->getOption(Relay::OPT_PREFIX);
$prefixLen = \strlen($prefix);
$pattern = $prefix.$namespace.'*';
foreach ($this->redis->_masters() as $ipAndPort) {
$address = implode(':', $ipAndPort);
$cursor = null;
do {
$keys = $this->redis->scan($cursor, $address, $pattern, 1000);
if (isset($keys[1]) && \is_array($keys[1])) {
$cursor = $keys[0];
$keys = $keys[1];
}
if ($keys) {
if ($prefixLen) {
foreach ($keys as $i => $key) {
$keys[$i] = substr($key, $prefixLen);
}
}
$this->doDelete($keys);
}
} while ($cursor);
}
return $cleared;
}
$hosts = $this->getHosts();
$host = reset($hosts);
if ($host instanceof \Predis\Client) {
$connection = $host->getConnection();
if ($connection instanceof ReplicationInterface) {
$hosts = [$host->getClientFor('master')];
} elseif ($connection instanceof Predis2ReplicationInterface) {
$connection->switchToMaster();
$hosts = [$host];
}
}
foreach ($hosts as $host) {
if (!isset($namespace[0])) {
$cleared = $host->flushDb() && $cleared;
continue;
}
$info = $host->info('Server');
$info = !$info instanceof ErrorInterface ? $info['Server'] ?? $info : ['redis_version' => '2.0'];
if ($host instanceof Relay) {
$prefix = Relay::SCAN_PREFIX & $host->getOption(Relay::OPT_SCAN) ? '' : $host->getOption(Relay::OPT_PREFIX);
$prefixLen = \strlen($host->getOption(Relay::OPT_PREFIX) ?? '');
} elseif (!$host instanceof \Predis\ClientInterface) {
$prefix = \defined('Redis::SCAN_PREFIX') && (\Redis::SCAN_PREFIX & $host->getOption(\Redis::OPT_SCAN)) ? '' : $host->getOption(\Redis::OPT_PREFIX);
$prefixLen = \strlen($host->getOption(\Redis::OPT_PREFIX) ?? '');
}
$pattern = $prefix.$namespace.'*';
if (!version_compare($info['redis_version'], '2.8', '>=')) {
// As documented in Redis documentation (http://redis.io/commands/keys) using KEYS
// can hang your server when it is executed against large databases (millions of items).
// Whenever you hit this scale, you should really consider upgrading to Redis 2.8 or above.
$unlink = version_compare($info['redis_version'], '4.0', '>=') ? 'UNLINK' : 'DEL';
$args = $this->redis instanceof \Predis\ClientInterface ? [0, $pattern] : [[$pattern], 0];
$cleared = $host->eval("local keys=redis.call('KEYS',ARGV[1]) for i=1,#keys,5000 do redis.call('$unlink',unpack(keys,i,math.min(i+4999,#keys))) end return 1", $args[0], $args[1]) && $cleared;
continue;
}
$cursor = null;
do {
$keys = $host instanceof \Predis\ClientInterface ? $host->scan($cursor ?? 0, 'MATCH', $pattern, 'COUNT', 1000) : $host->scan($cursor, $pattern, 1000);
if (isset($keys[1]) && \is_array($keys[1])) {
$cursor = $keys[0];
$keys = $keys[1];
}
if ($keys) {
if ($prefixLen) {
foreach ($keys as $i => $key) {
$keys[$i] = substr($key, $prefixLen);
}
}
$this->doDelete($keys);
}
} while ($cursor);
}
return $cleared;
}
protected function doDelete(array $ids): bool
{
if (!$ids) {
return true;
}
if ($this->redis instanceof \Predis\ClientInterface && ($this->redis->getConnection() instanceof ClusterInterface || $this->redis->getConnection() instanceof Predis2ClusterInterface)) {
static $del;
$del ??= (class_exists(UNLINK::class) ? 'unlink' : 'del');
$this->pipeline(function () use ($ids, $del) {
foreach ($ids as $id) {
yield $del => [$id];
}
})->rewind();
} else {
static $unlink = true;
if ($unlink) {
try {
$unlink = false !== $this->redis->unlink($ids);
} catch (\Throwable) {
$unlink = false;
}
}
if (!$unlink) {
$this->redis->del($ids);
}
}
return true;
}
protected function doSave(array $values, int $lifetime): array|bool
{
if (!$values = $this->marshaller->marshall($values, $failed)) {
return $failed;
}
$results = $this->pipeline(function () use ($values, $lifetime) {
foreach ($values as $id => $value) {
if (0 >= $lifetime) {
yield 'set' => [$id, $value];
} else {
yield 'setEx' => [$id, $lifetime, $value];
}
}
});
foreach ($results as $id => $result) {
if (true !== $result && (!$result instanceof Status || Status::get('OK') !== $result)) {
$failed[] = $id;
}
}
return $failed;
}
private function pipeline(\Closure $generator, ?object $redis = null): \Generator
{
$ids = [];
$redis ??= $this->redis;
if ($redis instanceof \RedisCluster || $redis instanceof RelayCluster || ($redis instanceof \Predis\ClientInterface && ($redis->getConnection() instanceof RedisCluster || $redis->getConnection() instanceof Predis2RedisCluster))) {
// phpredis & predis don't support pipelining with RedisCluster
// \Relay\Cluster does not support multi with pipeline mode
// see https://github.com/phpredis/phpredis/blob/develop/cluster.markdown#pipelining
// see https://github.com/nrk/predis/issues/267#issuecomment-123781423
$results = [];
foreach ($generator() as $command => $args) {
$results[] = $redis->{$command}(...$args);
$ids[] = 'eval' === $command ? ($redis instanceof \Predis\ClientInterface ? $args[2] : $args[1][0]) : $args[0];
}
} elseif ($redis instanceof \Predis\ClientInterface) {
$results = $redis->pipeline(static function ($redis) use ($generator, &$ids) {
foreach ($generator() as $command => $args) {
$redis->{$command}(...$args);
$ids[] = 'eval' === $command ? $args[2] : $args[0];
}
});
} elseif ($redis instanceof \RedisArray) {
$connections = $results = [];
foreach ($generator() as $command => $args) {
$id = 'eval' === $command ? $args[1][0] : $args[0];
if (!isset($connections[$h = $redis->_target($id)])) {
$connections[$h] = [$redis->_instance($h), -1];
$connections[$h][0]->multi(\Redis::PIPELINE);
}
$connections[$h][0]->{$command}(...$args);
$results[] = [$h, ++$connections[$h][1]];
$ids[] = $id;
}
foreach ($connections as $h => $c) {
$connections[$h] = $c[0]->exec();
}
foreach ($results as $k => [$h, $c]) {
$results[$k] = $connections[$h][$c];
}
} else {
$redis->multi($redis instanceof Relay ? Relay::PIPELINE : \Redis::PIPELINE);
foreach ($generator() as $command => $args) {
$redis->{$command}(...$args);
$ids[] = 'eval' === $command ? $args[1][0] : $args[0];
}
$results = $redis->exec();
}
if (!$redis instanceof \Predis\ClientInterface && 'eval' === $command && $redis->getLastError()) {
$e = $redis instanceof Relay ? new \Relay\Exception($redis->getLastError()) : new \RedisException($redis->getLastError());
$results = array_map(fn ($v) => false === $v ? $e : $v, (array) $results);
}
if (\is_bool($results)) {
return;
}
foreach ($ids as $k => $id) {
yield $id => $results[$k];
}
}
private function getHosts(): array
{
$hosts = [$this->redis];
if ($this->redis instanceof \Predis\ClientInterface) {
$connection = $this->redis->getConnection();
if (($connection instanceof ClusterInterface || $connection instanceof Predis2ClusterInterface) && $connection instanceof \Traversable) {
$hosts = [];
foreach ($connection as $c) {
$hosts[] = new \Predis\Client($c);
}
}
} elseif ($this->redis instanceof \RedisArray) {
$hosts = [];
foreach ($this->redis->_hosts() as $host) {
$hosts[] = $this->redis->_instance($host);
}
} elseif ($this->redis instanceof \RedisCluster) {
$hosts = [];
foreach ($this->redis->_masters() as $host) {
$hosts[] = new RedisClusterNodeProxy($host, $this->redis);
}
}
return $hosts;
}
private static function filterSslOptions(array $options): array
{
foreach ($options as $name => $value) {
match ($name) {
'allow_self_signed', 'capture_peer_cert', 'capture_peer_cert_chain', 'disable_compression', 'SNI_enabled', 'verify_peer', 'verify_peer_name',
=> $options[$name] = filter_var($value, \FILTER_VALIDATE_BOOLEAN),
default => null,
};
}
return $options;
}
}

View File

@@ -0,0 +1,47 @@
<?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\Traits\Relay;
if (version_compare(phpversion('relay'), '0.20.0', '>=')) {
/**
* @internal
*/
trait Relay20Trait
{
public function _digest($value): string
{
return $this->initializeLazyObject()->_digest(...\func_get_args());
}
public function delex($key, $options = null): \Relay\Relay|false|int
{
return $this->initializeLazyObject()->delex(...\func_get_args());
}
public function digest($key): \Relay\Relay|false|null|string
{
return $this->initializeLazyObject()->digest(...\func_get_args());
}
public function msetex($kvals, $ttl = null): \Relay\Relay|false|int
{
return $this->initializeLazyObject()->msetx(...\func_get_args());
}
}
} else {
/**
* @internal
*/
trait Relay20Trait
{
}
}

View File

@@ -0,0 +1,47 @@
<?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\Traits\Relay;
if (version_compare(phpversion('relay'), '0.20.0', '>=')) {
/**
* @internal
*/
trait RelayCluster20Trait
{
public function _digest($value): string
{
return $this->initializeLazyObject()->_digest(...\func_get_args());
}
public function delex($key, $options = null): \Relay\Cluster|false|int
{
return $this->initializeLazyObject()->delex(...\func_get_args());
}
public function digest($key): \Relay\Cluster|false|null|string
{
return $this->initializeLazyObject()->digest(...\func_get_args());
}
public function wait($key_or_address, $replicas, $timeout): \Relay\Cluster|false|int
{
return $this->initializeLazyObject()->digest(...\func_get_args());
}
}
} else {
/**
* @internal
*/
trait RelayCluster20Trait
{
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,81 @@
<?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 ©
{
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): void
{
$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;
}
}