This commit is contained in:
Nicolas Grekas
2025-07-10 09:12:18 +02:00
parent c88690befb
commit 52a03d7916
34 changed files with 92 additions and 92 deletions

View File

@@ -40,7 +40,7 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg
$this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace).static::NS_SEPARATOR;
$this->defaultLifetime = $defaultLifetime;
if (null !== $this->maxIdLength && \strlen($namespace) > $this->maxIdLength - 24) {
throw new InvalidArgumentException(sprintf('Namespace must be %d chars max, %d given ("%s").', $this->maxIdLength - 24, \strlen($namespace), $namespace));
throw new InvalidArgumentException(\sprintf('Namespace must be %d chars max, %d given ("%s").', $this->maxIdLength - 24, \strlen($namespace), $namespace));
}
self::$createCacheItem ??= \Closure::bind(
static function ($key, $value, $isHit) {
@@ -155,7 +155,7 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg
$ok = false;
$v = $values[$id];
$type = get_debug_type($v);
$message = sprintf('Failed to save key "{key}" of type %s%s', $type, $e instanceof \Exception ? ': '.$e->getMessage() : '.');
$message = \sprintf('Failed to save key "{key}" of type %s%s', $type, $e instanceof \Exception ? ': '.$e->getMessage() : '.');
CacheItem::log($this->logger, $message, ['key' => substr($id, \strlen($this->namespace)), 'exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
}
} else {
@@ -178,7 +178,7 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg
}
$ok = false;
$type = get_debug_type($v);
$message = sprintf('Failed to save key "{key}" of type %s%s', $type, $e instanceof \Exception ? ': '.$e->getMessage() : '.');
$message = \sprintf('Failed to save key "{key}" of type %s%s', $type, $e instanceof \Exception ? ': '.$e->getMessage() : '.');
CacheItem::log($this->logger, $message, ['key' => substr($id, \strlen($this->namespace)), 'exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
}
}

View File

@@ -42,7 +42,7 @@ abstract class AbstractTagAwareAdapter implements TagAwareAdapterInterface, TagA
$this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace).':';
$this->defaultLifetime = $defaultLifetime;
if (null !== $this->maxIdLength && \strlen($namespace) > $this->maxIdLength - 24) {
throw new InvalidArgumentException(sprintf('Namespace must be %d chars max, %d given ("%s").', $this->maxIdLength - 24, \strlen($namespace), $namespace));
throw new InvalidArgumentException(\sprintf('Namespace must be %d chars max, %d given ("%s").', $this->maxIdLength - 24, \strlen($namespace), $namespace));
}
self::$createCacheItem ??= \Closure::bind(
static function ($key, $value, $isHit) {
@@ -194,7 +194,7 @@ abstract class AbstractTagAwareAdapter implements TagAwareAdapterInterface, TagA
$ok = false;
$v = $values[$id];
$type = get_debug_type($v);
$message = sprintf('Failed to save key "{key}" of type %s%s', $type, $e instanceof \Exception ? ': '.$e->getMessage() : '.');
$message = \sprintf('Failed to save key "{key}" of type %s%s', $type, $e instanceof \Exception ? ': '.$e->getMessage() : '.');
CacheItem::log($this->logger, $message, ['key' => substr($id, \strlen($this->namespace)), 'exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
}
} else {
@@ -218,7 +218,7 @@ abstract class AbstractTagAwareAdapter implements TagAwareAdapterInterface, TagA
}
$ok = false;
$type = get_debug_type($v);
$message = sprintf('Failed to save key "{key}" of type %s%s', $type, $e instanceof \Exception ? ': '.$e->getMessage() : '.');
$message = \sprintf('Failed to save key "{key}" of type %s%s', $type, $e instanceof \Exception ? ': '.$e->getMessage() : '.');
CacheItem::log($this->logger, $message, ['key' => substr($id, \strlen($this->namespace)), 'exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
}
}

View File

@@ -82,7 +82,7 @@ class ApcuAdapter extends AbstractAdapter
protected function doClear(string $namespace): bool
{
return isset($namespace[0]) && class_exists(\APCUIterator::class, false) && ('cli' !== \PHP_SAPI || filter_var(\ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOL))
? apcu_delete(new \APCUIterator(sprintf('/^%s/', preg_quote($namespace, '/')), \APC_ITER_KEY))
? apcu_delete(new \APCUIterator(\sprintf('/^%s/', preg_quote($namespace, '/')), \APC_ITER_KEY))
: apcu_clear_cache();
}

View File

@@ -46,11 +46,11 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
public function __construct(int $defaultLifetime = 0, bool $storeSerialized = true, float $maxLifetime = 0, int $maxItems = 0)
{
if (0 > $maxLifetime) {
throw new InvalidArgumentException(sprintf('Argument $maxLifetime must be positive, %F passed.', $maxLifetime));
throw new InvalidArgumentException(\sprintf('Argument $maxLifetime must be positive, %F passed.', $maxLifetime));
}
if (0 > $maxItems) {
throw new InvalidArgumentException(sprintf('Argument $maxItems must be a positive integer, %d passed.', $maxItems));
throw new InvalidArgumentException(\sprintf('Argument $maxItems must be a positive integer, %d passed.', $maxItems));
}
$this->defaultLifetime = $defaultLifetime;
@@ -316,7 +316,7 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
unset($this->values[$key]);
}
$type = get_debug_type($value);
$message = sprintf('Failed to save key "{key}" of type %s: %s', $type, $e->getMessage());
$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)]);
return null;

View File

@@ -51,7 +51,7 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
foreach ($adapters as $adapter) {
if (!$adapter instanceof CacheItemPoolInterface) {
throw new InvalidArgumentException(sprintf('The class "%s" does not implement the "%s" interface.', get_debug_type($adapter), CacheItemPoolInterface::class));
throw new InvalidArgumentException(\sprintf('The class "%s" does not implement the "%s" interface.', get_debug_type($adapter), CacheItemPoolInterface::class));
}
if ('cli' === \PHP_SAPI && $adapter instanceof ApcuAdapter && !filter_var(\ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOL)) {
continue; // skip putting APCu in the chain when the backend is disabled
@@ -76,7 +76,7 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
$item->metadata = $item->newMetadata = $sourceItem->metadata = $sourceMetadata;
if (isset($item->metadata[CacheItem::METADATA_EXPIRY])) {
$item->expiresAt(\DateTimeImmutable::createFromFormat('U.u', sprintf('%.6F', $item->metadata[CacheItem::METADATA_EXPIRY])));
$item->expiresAt(\DateTimeImmutable::createFromFormat('U.u', \sprintf('%.6F', $item->metadata[CacheItem::METADATA_EXPIRY])));
} elseif (0 < $defaultLifetime) {
$item->expiresAfter($defaultLifetime);
}

View File

@@ -62,7 +62,7 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
public function __construct(Connection|string $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]));
throw new InvalidArgumentException(\sprintf('Namespace contains "%s" but only characters in [-+.A-Za-z0-9] are allowed.', $match[0]));
}
if ($connOrDsn instanceof Connection) {
@@ -151,7 +151,7 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
if ('' !== $this->namespace) {
$deleteSql .= " AND $this->idCol LIKE ?";
$params[] = sprintf('%s%%', $this->namespace);
$params[] = \sprintf('%s%%', $this->namespace);
$paramTypes[] = ParameterType::STRING;
}

View File

@@ -25,7 +25,7 @@ class MemcachedAdapter extends AbstractAdapter
/**
* We are replacing characters that are illegal in Memcached keys with reserved characters from
* {@see \Symfony\Contracts\Cache\ItemInterface::RESERVED_CHARACTERS} that are legal in Memcached.
* Note: dont use {@see \Symfony\Component\Cache\Adapter\AbstractAdapter::NS_SEPARATOR}.
* Note: dont use {@see AbstractAdapter::NS_SEPARATOR}.
*/
private const RESERVED_MEMCACHED = " \n\r\t\v\f\0";
private const RESERVED_PSR6 = '@()\{}/';
@@ -314,7 +314,7 @@ class MemcachedAdapter extends AbstractAdapter
throw new CacheException('MemcachedAdapter: "serializer" option must be "php" or "igbinary".');
}
if ('' !== $prefix = (string) $this->lazyClient->getOption(\Memcached::OPT_PREFIX_KEY)) {
throw new CacheException(sprintf('MemcachedAdapter: "prefix_key" option must be empty when using proxified connections, "%s" given.', $prefix));
throw new CacheException(\sprintf('MemcachedAdapter: "prefix_key" option must be empty when using proxified connections, "%s" given.', $prefix));
}
return $this->client = $this->lazyClient;

View File

@@ -29,7 +29,7 @@ final class ParameterNormalizer
try {
return \DateTimeImmutable::createFromFormat('U', 0)->add(new \DateInterval($duration))->getTimestamp();
} catch (\Exception $e) {
throw new \InvalidArgumentException(sprintf('Cannot parse date interval "%s".', $duration), 0, $e);
throw new \InvalidArgumentException(\sprintf('Cannot parse date interval "%s".', $duration), 0, $e);
}
}
}

View File

@@ -57,16 +57,16 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
public function __construct(#[\SensitiveParameter] \PDO|string $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.', __CLASS__, DoctrineDbalAdapter::class));
throw new InvalidArgumentException(\sprintf('Usage of Doctrine DBAL URL with "%s" is not supported. Use a PDO DSN or "%s" instead.', __CLASS__, DoctrineDbalAdapter::class));
}
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]));
throw new InvalidArgumentException(\sprintf('Namespace contains "%s" but only characters in [-+.A-Za-z0-9] are allowed.', $match[0]));
}
if ($connOrDsn instanceof \PDO) {
if (\PDO::ERRMODE_EXCEPTION !== $connOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) {
throw new InvalidArgumentException(sprintf('"%s" requires PDO error mode attribute be set to throw Exceptions (i.e. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)).', __CLASS__));
throw new InvalidArgumentException(\sprintf('"%s" requires PDO error mode attribute be set to throw Exceptions (i.e. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)).', __CLASS__));
}
$this->conn = $connOrDsn;
@@ -113,7 +113,7 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
'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".', $driver)),
default => throw new \DomainException(\sprintf('Creating the cache table is currently not implemented for PDO driver "%s".', $driver)),
};
$this->getConnection()->exec($sql);
@@ -137,7 +137,7 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
$delete->bindValue(':time', time(), \PDO::PARAM_INT);
if ('' !== $this->namespace) {
$delete->bindValue(':namespace', sprintf('%s%%', $this->namespace), \PDO::PARAM_STR);
$delete->bindValue(':namespace', \sprintf('%s%%', $this->namespace), \PDO::PARAM_STR);
}
try {
return $delete->execute();

View File

@@ -111,7 +111,7 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
public function getItem(mixed $key): CacheItem
{
if (!\is_string($key)) {
throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', get_debug_type($key)));
throw new InvalidArgumentException(\sprintf('Cache key must be string, "%s" given.', get_debug_type($key)));
}
if (!isset($this->values)) {
$this->initialize();
@@ -141,7 +141,7 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
{
foreach ($keys as $key) {
if (!\is_string($key)) {
throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', get_debug_type($key)));
throw new InvalidArgumentException(\sprintf('Cache key must be string, "%s" given.', get_debug_type($key)));
}
}
if (!isset($this->values)) {
@@ -154,7 +154,7 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
public function hasItem(mixed $key): bool
{
if (!\is_string($key)) {
throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', get_debug_type($key)));
throw new InvalidArgumentException(\sprintf('Cache key must be string, "%s" given.', get_debug_type($key)));
}
if (!isset($this->values)) {
$this->initialize();
@@ -166,7 +166,7 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
public function deleteItem(mixed $key): bool
{
if (!\is_string($key)) {
throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', get_debug_type($key)));
throw new InvalidArgumentException(\sprintf('Cache key must be string, "%s" given.', get_debug_type($key)));
}
if (!isset($this->values)) {
$this->initialize();
@@ -182,7 +182,7 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
foreach ($keys as $key) {
if (!\is_string($key)) {
throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', get_debug_type($key)));
throw new InvalidArgumentException(\sprintf('Cache key must be string, "%s" given.', get_debug_type($key)));
}
if (isset($this->keys[$key])) {
@@ -250,21 +250,21 @@ class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInte
{
if (file_exists($this->file)) {
if (!is_file($this->file)) {
throw new InvalidArgumentException(sprintf('Cache path exists and is not a file: "%s".', $this->file));
throw new InvalidArgumentException(\sprintf('Cache path exists and is not a file: "%s".', $this->file));
}
if (!is_writable($this->file)) {
throw new InvalidArgumentException(sprintf('Cache file is not writable: "%s".', $this->file));
throw new InvalidArgumentException(\sprintf('Cache file is not writable: "%s".', $this->file));
}
} else {
$directory = \dirname($this->file);
if (!is_dir($directory) && !@mkdir($directory, 0777, true)) {
throw new InvalidArgumentException(sprintf('Cache directory does not exist and cannot be created: "%s".', $directory));
throw new InvalidArgumentException(\sprintf('Cache directory does not exist and cannot be created: "%s".', $directory));
}
if (!is_writable($directory)) {
throw new InvalidArgumentException(sprintf('Cache directory is not writable: "%s".', $directory));
throw new InvalidArgumentException(\sprintf('Cache directory is not writable: "%s".', $directory));
}
}
@@ -291,7 +291,7 @@ EOF;
try {
$value = VarExporter::export($value, $isStaticValue, $preload);
} catch (\Exception $e) {
throw new InvalidArgumentException(sprintf('Cache key "%s" has non-serializable "%s" value.', $key, get_debug_type($value)), 0, $e);
throw new InvalidArgumentException(\sprintf('Cache key "%s" has non-serializable "%s" value.', $key, get_debug_type($value)), 0, $e);
}
} elseif (\is_string($value)) {
// Wrap "N;" in a closure to not confuse it with an encoded `null`
@@ -300,7 +300,7 @@ EOF;
}
$value = var_export($value, true);
} elseif (!\is_scalar($value)) {
throw new InvalidArgumentException(sprintf('Cache key "%s" has non-serializable "%s" value.', $key, get_debug_type($value)));
throw new InvalidArgumentException(\sprintf('Cache key "%s" has non-serializable "%s" value.', $key, get_debug_type($value)));
} else {
$value = var_export($value, true);
}

View File

@@ -217,7 +217,7 @@ class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
try {
$value = VarExporter::export($value, $isStaticValue);
} catch (\Exception $e) {
throw new InvalidArgumentException(sprintf('Cache key "%s" has non-serializable "%s" value.', $key, get_debug_type($value)), 0, $e);
throw new InvalidArgumentException(\sprintf('Cache key "%s" has non-serializable "%s" value.', $key, get_debug_type($value)), 0, $e);
}
} elseif (\is_string($value)) {
// Wrap "N;" in a closure to not confuse it with an encoded `null`
@@ -226,7 +226,7 @@ class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
}
$value = var_export($value, true);
} elseif (!\is_scalar($value)) {
throw new InvalidArgumentException(sprintf('Cache key "%s" has non-serializable "%s" value.', $key, get_debug_type($value)));
throw new InvalidArgumentException(\sprintf('Cache key "%s" has non-serializable "%s" value.', $key, get_debug_type($value)));
} else {
$value = var_export($value, true);
}
@@ -255,7 +255,7 @@ class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
}
if (!$ok && !is_writable($this->directory)) {
throw new CacheException(sprintf('Cache directory is not writable (%s).', $this->directory));
throw new CacheException(\sprintf('Cache directory is not writable (%s).', $this->directory));
}
return $ok;

View File

@@ -73,7 +73,7 @@ class ProxyAdapter implements AdapterInterface, CacheInterface, PruneableInterfa
self::$setInnerItem ??= \Closure::bind(
static function (CacheItemInterface $innerItem, CacheItem $item, $expiry = null) {
$innerItem->set($item->pack());
$innerItem->expiresAt(($expiry ?? $item->expiry) ? \DateTimeImmutable::createFromFormat('U.u', sprintf('%.6F', $expiry ?? $item->expiry)) : null);
$innerItem->expiresAt(($expiry ?? $item->expiry) ? \DateTimeImmutable::createFromFormat('U.u', \sprintf('%.6F', $expiry ?? $item->expiry)) : null);
},
null,
CacheItem::class

View File

@@ -63,7 +63,7 @@ class RedisTagAwareAdapter extends AbstractTagAwareAdapter
public function __construct(\Redis|Relay|\RedisArray|\RedisCluster|\Predis\ClientInterface $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())));
throw new InvalidArgumentException(\sprintf('Unsupported Predis cluster connection: only "%s" is, "%s" given.', PredisCluster::class, get_debug_type($redis->getConnection())));
}
$isRelay = $redis instanceof Relay;
@@ -72,7 +72,7 @@ class RedisTagAwareAdapter extends AbstractTagAwareAdapter
foreach (\is_array($compression) ? $compression : [$compression] as $c) {
if ($isRelay ? Relay::COMPRESSION_NONE : \Redis::COMPRESSION_NONE !== $c) {
throw new InvalidArgumentException(sprintf('redis compression must be disabled when using "%s", use "%s" instead.', static::class, DeflateMarshaller::class));
throw new InvalidArgumentException(\sprintf('redis compression must be disabled when using "%s", use "%s" instead.', static::class, DeflateMarshaller::class));
}
}
}
@@ -85,7 +85,7 @@ class RedisTagAwareAdapter extends AbstractTagAwareAdapter
{
$eviction = $this->getRedisEvictionPolicy();
if ('noeviction' !== $eviction && !str_starts_with($eviction, 'volatile-')) {
throw new LogicException(sprintf('Redis maxmemory-policy setting "%s" is *not* supported by RedisTagAwareAdapter, use "noeviction" or "volatile-*" eviction policies.', $eviction));
throw new LogicException(\sprintf('Redis maxmemory-policy setting "%s" is *not* supported by RedisTagAwareAdapter, use "noeviction" or "volatile-*" eviction policies.', $eviction));
}
// serialize values

View File

@@ -38,7 +38,7 @@ class TraceableAdapter implements AdapterInterface, CacheInterface, PruneableInt
public function get(string $key, callable $callback, ?float $beta = null, ?array &$metadata = null): mixed
{
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));
throw new \BadMethodCallException(\sprintf('Cannot call "%s::get()": this class doesn\'t implement "%s".', get_debug_type($this->pool), CacheInterface::class));
}
$isHit = true;

View File

@@ -82,7 +82,7 @@ final class CacheItem implements ItemInterface
} elseif (\is_int($time)) {
$this->expiry = $time + microtime(true);
} else {
throw new InvalidArgumentException(sprintf('Expiration date must be an integer, a DateInterval or null, "%s" given.', get_debug_type($time)));
throw new InvalidArgumentException(\sprintf('Expiration date must be an integer, a DateInterval or null, "%s" given.', get_debug_type($time)));
}
return $this;
@@ -91,14 +91,14 @@ final class CacheItem implements ItemInterface
public function tag(mixed $tags): static
{
if (!$this->isTaggable) {
throw new LogicException(sprintf('Cache item "%s" comes from a non tag-aware pool: you cannot tag it.', $this->key));
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
$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)));
throw new InvalidArgumentException(\sprintf('Cache tag must be string or object that implements __toString(), "%s" given.', get_debug_type($tag)));
}
$tag = (string) $tag;
if (isset($this->newMetadata[self::METADATA_TAGS][$tag])) {
@@ -108,7 +108,7 @@ final class CacheItem implements ItemInterface
throw new InvalidArgumentException('Cache tag length must be greater than zero.');
}
if (false !== strpbrk($tag, self::RESERVED_CHARACTERS)) {
throw new InvalidArgumentException(sprintf('Cache tag "%s" contains reserved characters "%s".', $tag, self::RESERVED_CHARACTERS));
throw new InvalidArgumentException(\sprintf('Cache tag "%s" contains reserved characters "%s".', $tag, self::RESERVED_CHARACTERS));
}
$this->newMetadata[self::METADATA_TAGS][$tag] = $tag;
}
@@ -131,13 +131,13 @@ final class CacheItem implements ItemInterface
public static function validateKey($key): string
{
if (!\is_string($key)) {
throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', get_debug_type($key)));
throw new InvalidArgumentException(\sprintf('Cache key must be string, "%s" given.', get_debug_type($key)));
}
if ('' === $key) {
throw new InvalidArgumentException('Cache key length must be greater than zero.');
}
if (false !== strpbrk($key, self::RESERVED_CHARACTERS)) {
throw new InvalidArgumentException(sprintf('Cache key "%s" contains reserved characters "%s".', $key, self::RESERVED_CHARACTERS));
throw new InvalidArgumentException(\sprintf('Cache key "%s" contains reserved characters "%s".', $key, self::RESERVED_CHARACTERS));
}
return $key;

View File

@@ -111,7 +111,7 @@ class CachePoolPass implements CompilerPassInterface
}
if (ChainAdapter::class === $chainedClass) {
throw new InvalidArgumentException(sprintf('Invalid service "%s": chain of adapters cannot reference another chain, found "%s".', $id, $chainedPool->getParent()));
throw new InvalidArgumentException(\sprintf('Invalid service "%s": chain of adapters cannot reference another chain, found "%s".', $id, $chainedPool->getParent()));
}
$i = 0;
@@ -169,7 +169,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 "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]))));
}
if (null !== $clearer) {

View File

@@ -38,7 +38,7 @@ class CachePoolPrunerPass implements CompilerPassInterface
$class = $container->getParameterBag()->resolveValue($container->getDefinition($id)->getClass());
if (!$reflection = $container->getReflectionClass($class)) {
throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
throw new InvalidArgumentException(\sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
}
if ($reflection->implementsInterface(PruneableInterface::class)) {

View File

@@ -105,7 +105,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?->info(\sprintf('Lock %s, now computing item "{key}"', $locked ? 'acquired' : 'not supported'), ['key' => $item->getKey()]);
self::$lockedFiles[$key] = true;
$value = $callback($item, $save);

View File

@@ -135,7 +135,7 @@ class Psr16Cache implements CacheInterface, PruneableInterface, ResettableInterf
if ($keys instanceof \Traversable) {
$keys = iterator_to_array($keys, false);
} elseif (!\is_array($keys)) {
throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given.', get_debug_type($keys)));
throw new InvalidArgumentException(\sprintf('Cache keys must be array or Traversable, "%s" given.', get_debug_type($keys)));
}
try {
@@ -166,7 +166,7 @@ class Psr16Cache implements CacheInterface, PruneableInterface, ResettableInterf
{
$valuesIsArray = \is_array($values);
if (!$valuesIsArray && !$values instanceof \Traversable) {
throw new InvalidArgumentException(sprintf('Cache values must be array or Traversable, "%s" given.', get_debug_type($values)));
throw new InvalidArgumentException(\sprintf('Cache values must be array or Traversable, "%s" given.', get_debug_type($values)));
}
$items = [];
@@ -215,7 +215,7 @@ class Psr16Cache implements CacheInterface, PruneableInterface, ResettableInterf
if ($keys instanceof \Traversable) {
$keys = iterator_to_array($keys, false);
} elseif (!\is_array($keys)) {
throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given.', get_debug_type($keys)));
throw new InvalidArgumentException(\sprintf('Cache keys must be array or Traversable, "%s" given.', get_debug_type($keys)));
}
try {

View File

@@ -175,7 +175,7 @@ class DoctrineDbalAdapterTest extends AdapterTestCase
/** @var Connection $conn */
$conn = $connProp->getValue($cache);
$result = $conn->executeQuery('SELECT 1 FROM cache_items WHERE item_id LIKE ?', [sprintf('%%%s', $name)]);
$result = $conn->executeQuery('SELECT 1 FROM cache_items WHERE item_id LIKE ?', [\sprintf('%%%s', $name)]);
return 1 !== (int) $result->fetchOne();
}

View File

@@ -123,7 +123,7 @@ class PdoAdapterTest extends AdapterTestCase
/** @var \PDOStatement $select */
$select = $getPdoConn->invoke($cache)->prepare('SELECT 1 FROM cache_items WHERE item_id LIKE :id');
$select->bindValue(':id', sprintf('%%%s', $name));
$select->bindValue(':id', \sprintf('%%%s', $name));
$select->execute();
return 1 !== (int) $select->fetch(\PDO::FETCH_COLUMN);

View File

@@ -27,9 +27,9 @@ class PredisReplicationAdapterTest extends AbstractRedisAdapterTestCase
$hosts = explode(' ', getenv('REDIS_REPLICATION_HOSTS'));
$lastArrayKey = array_key_last($hosts);
$hostTable = [];
foreach($hosts as $key => $host) {
foreach ($hosts as $key => $host) {
$hostInformation = array_combine(['host', 'port'], explode(':', $host));
if($lastArrayKey === $key) {
if ($lastArrayKey === $key) {
$hostInformation['role'] = 'master';
}
$hostTable[] = $hostInformation;

View File

@@ -41,7 +41,7 @@ class EarlyExpirationDispatcherTest extends TestCase
$item = $pool->getItem('foo');
$computationService = new class() {
$computationService = new class {
public function __invoke(CacheItem $item)
{
return 123;
@@ -90,7 +90,7 @@ class EarlyExpirationDispatcherTest extends TestCase
$pool->save($item->set(789));
$item = $pool->getItem('foo');
$computationService = new class() {
$computationService = new class {
public function __invoke(CacheItem $item)
{
return 123;

View File

@@ -38,7 +38,7 @@ class EarlyExpirationHandlerTest extends TestCase
$item = $pool->getItem('foo');
$item->set(234);
$computationService = new class() implements CallbackInterface {
$computationService = new class implements CallbackInterface {
public function __invoke(CacheItemInterface $item, bool &$save): mixed
{
usleep(30000);

View File

@@ -27,7 +27,7 @@ class EarlyExpirationMessageTest extends TestCase
$item = $pool->getItem('foo');
$item->set(234);
$computationService = new class() {
$computationService = new class {
public function __invoke(CacheItem $item)
{
return 123;

View File

@@ -32,7 +32,7 @@ class Psr16CacheTest extends SimpleCacheTest
$pool = $this->createSimpleCache();
if ($pool instanceof Psr16Cache) {
$pool = ((array) $pool)[sprintf("\0%s\0pool", Psr16Cache::class)];
$pool = ((array) $pool)[\sprintf("\0%s\0pool", Psr16Cache::class)];
}
if (!$pool instanceof PruneableInterface) {
@@ -167,7 +167,7 @@ class Psr16CacheTest extends SimpleCacheTest
$this->fail('Test classes for pruneable caches must implement `isPruned($cache, $name)` method.');
}
$pool = ((array) $cache)[sprintf("\0%s\0pool", Psr16Cache::class)];
$pool = ((array) $cache)[\sprintf("\0%s\0pool", Psr16Cache::class)];
$getFileMethod = (new \ReflectionObject($pool))->getMethod('getFile');
return !file_exists($getFileMethod->invoke($pool, $name));

View File

@@ -33,7 +33,7 @@ class RedisProxiesTest extends TestCase
$expected = substr($proxy, 0, 4 + strpos($proxy, '[];'));
$methods = [];
foreach ((new \ReflectionClass(sprintf('Symfony\Component\Cache\Traits\\%s%dProxy', $class, $version)))->getMethods() as $method) {
foreach ((new \ReflectionClass(\sprintf('Symfony\Component\Cache\Traits\\%s%dProxy', $class, $version)))->getMethods() as $method) {
if ('reset' === $method->name || method_exists(LazyProxyTrait::class, $method->name)) {
continue;
}

View File

@@ -26,13 +26,13 @@ class RedisTraitTest extends TestCase
public function testCreateConnection(string $dsn, string $expectedClass)
{
if (!class_exists($expectedClass)) {
self::markTestSkipped(sprintf('The "%s" class is required.', $expectedClass));
self::markTestSkipped(\sprintf('The "%s" class is required.', $expectedClass));
}
if (!getenv('REDIS_CLUSTER_HOSTS')) {
self::markTestSkipped('REDIS_CLUSTER_HOSTS env var is not defined.');
}
$mock = new class () {
$mock = new class {
use RedisTrait;
};
$connection = $mock::createConnection($dsn);
@@ -46,7 +46,7 @@ class RedisTraitTest extends TestCase
self::markTestSkipped('REDIS_AUTHENTICATED_HOST env var is not defined.');
}
$mock = new class () {
$mock = new class {
use RedisTrait;
};
$connection = $mock::createConnection('redis://:p%40ssword@'.getenv('REDIS_AUTHENTICATED_HOST'));
@@ -57,23 +57,23 @@ class RedisTraitTest extends TestCase
public static function provideCreateConnection(): array
{
$hosts = array_map(fn ($host) => sprintf('host[%s]', $host), explode(' ', getenv('REDIS_CLUSTER_HOSTS')));
$hosts = array_map(fn ($host) => \sprintf('host[%s]', $host), explode(' ', getenv('REDIS_CLUSTER_HOSTS')));
return [
[
sprintf('redis:?%s&redis_cluster=1', $hosts[0]),
\sprintf('redis:?%s&redis_cluster=1', $hosts[0]),
'RedisCluster',
],
[
sprintf('redis:?%s&redis_cluster=true', $hosts[0]),
\sprintf('redis:?%s&redis_cluster=true', $hosts[0]),
'RedisCluster',
],
[
sprintf('redis:?%s', $hosts[0]),
\sprintf('redis:?%s', $hosts[0]),
'Redis',
],
[
sprintf('redis:?%s', implode('&', \array_slice($hosts, 0, 2))),
\sprintf('redis:?%s', implode('&', \array_slice($hosts, 0, 2))),
'RedisArray',
],
];
@@ -105,7 +105,7 @@ class RedisTraitTest extends TestCase
}
try {
$mock = new class () {
$mock = new class {
use RedisTrait;
};
@@ -143,7 +143,7 @@ class RedisTraitTest extends TestCase
self::markTestSkipped('REDIS_AUTHENTICATED_HOST env var is not defined.');
}
$mock = new class () {
$mock = new class {
use RedisTrait;
};
$connection = $mock::createConnection($dsn);
@@ -190,7 +190,7 @@ class RedisTraitTest extends TestCase
}
$this->expectException(InvalidArgumentException::class);
$mock = new class () {
$mock = new class {
use RedisTrait;
};
$mock::createConnection($dsn);
@@ -200,11 +200,11 @@ class RedisTraitTest extends TestCase
{
return [
[
'redis://:p%40ssword@'.getenv('REDIS_AUTHENTICATED_HOST').'/abc'
'redis://:p%40ssword@'.getenv('REDIS_AUTHENTICATED_HOST').'/abc',
],
[
'redis://:p%40ssword@'.getenv('REDIS_AUTHENTICATED_HOST').'/3?dbindex=6'
]
'redis://:p%40ssword@'.getenv('REDIS_AUTHENTICATED_HOST').'/3?dbindex=6',
],
];
}
}

View File

@@ -303,7 +303,7 @@ trait AbstractAdapterTrait
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)));
throw new InvalidArgumentException(\sprintf('Could not match value id "%s" to keys "%s".', $id, implode('", "', $keys)));
}
$key = $keys[$id];
unset($keys[$id]);

View File

@@ -62,7 +62,7 @@ trait ContractsTrait
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));
throw new InvalidArgumentException(\sprintf('Argument "$beta" provided to "%s::get()" must be a positive number, %f given.', static::class, $beta));
}
static $setMetadata;

View File

@@ -32,7 +32,7 @@ trait FilesystemCommonTrait
}
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]));
throw new InvalidArgumentException(\sprintf('Namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
}
$directory .= \DIRECTORY_SEPARATOR.$namespace;
} else {
@@ -44,7 +44,7 @@ trait FilesystemCommonTrait
$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));
throw new InvalidArgumentException(\sprintf('Cache directory too long (%s).', $directory));
}
$this->directory = $directory;

View File

@@ -92,7 +92,7 @@ trait FilesystemTrait
}
if ($failed && !is_writable($this->directory)) {
throw new CacheException(sprintf('Cache directory is not writable (%s).', $this->directory));
throw new CacheException(\sprintf('Cache directory is not writable (%s).', $this->directory));
}
return $failed;

View File

@@ -58,7 +58,7 @@ trait RedisTrait
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]));
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) {
@@ -201,7 +201,7 @@ trait RedisTrait
};
if (isset($params['redis_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 >= 5.2 nor ext-relay have been found.', $class));
throw new CacheException(\sprintf('Cannot use Redis Sentinel: class "%s" does not extend "Predis\Client" and neither ext-redis >= 5.2 nor ext-relay have been found.', $class));
}
$isRedisExt = is_a($class, \Redis::class, true);
@@ -258,7 +258,7 @@ trait RedisTrait
} while (++$hostIndex < \count($hosts) && !$address);
if (isset($params['redis_sentinel']) && !$address) {
throw new InvalidArgumentException(sprintf('Failed to retrieve master information from sentinel "%s".', $params['redis_sentinel']), previous: $redisException ?? null);
throw new InvalidArgumentException(\sprintf('Failed to retrieve master information from sentinel "%s".', $params['redis_sentinel']), previous: $redisException ?? null);
}
try {
@@ -293,7 +293,7 @@ trait RedisTrait
restore_error_handler();
}
if (!$isConnected) {
$error = preg_match('/^Redis::p?connect\(\): (.*)/', $error ?? $redis->getLastError() ?? '', $error) ? sprintf(' (%s)', $error[1]) : '';
$error = preg_match('/^Redis::p?connect\(\): (.*)/', $error ?? $redis->getLastError() ?? '', $error) ? \sprintf(' (%s)', $error[1]) : '';
throw new InvalidArgumentException('Redis connection failed: '.$error.'.');
}
@@ -418,9 +418,9 @@ trait RedisTrait
$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));
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));
throw new InvalidArgumentException(\sprintf('Class "%s" does not exist.', $class));
}
return $redis;

View File

@@ -33,12 +33,12 @@ if (version_compare(phpversion('relay'), '0.9.0', '>=')) {
*/
trait MoveTrait
{
public function blmove($srckey, $dstkey, $srcpos, $dstpos, $timeout): \Relay\Relay|false|null|string
public function blmove($srckey, $dstkey, $srcpos, $dstpos, $timeout): \Relay\Relay|false|string|null
{
return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->blmove(...\func_get_args());
}
public function lmove($srckey, $dstkey, $srcpos, $dstpos): \Relay\Relay|false|null|string
public function lmove($srckey, $dstkey, $srcpos, $dstpos): \Relay\Relay|false|string|null
{
return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->lmove(...\func_get_args());
}