框架升级及修复升级后的bug

This commit is contained in:
Dev
2026-10-16 18:13:09 +08:00
parent dafb0c96c0
commit 2d342bcbd7
537 changed files with 49836 additions and 40933 deletions
@@ -131,6 +131,10 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Name
return MemcachedAdapter::createConnection($dsn, $options);
}
if (str_starts_with($dsn, 'couchbase:')) {
if (class_exists(\CouchbaseBucket::class) && CouchbaseBucketAdapter::isSupported()) {
return CouchbaseBucketAdapter::createConnection($dsn, $options);
}
return CouchbaseCollectionAdapter::createConnection($dsn, $options);
}
if (preg_match('/^(mysql|oci|pgsql|sqlsrv|sqlite):/', $dsn)) {
+57 -50
View File
@@ -18,7 +18,6 @@ use Psr\Log\LoggerAwareTrait;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
use Symfony\Component\Cache\ResettableInterface;
use Symfony\Component\VarExporter\DeepCloner;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\NamespacedPoolInterface;
@@ -42,11 +41,11 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, NamespacedPoolIn
private static \Closure $createCacheItem;
/**
* @param bool $deepClone Disabling deep-cloning can lead to cache corruptions when storing mutable values but increases performance otherwise
* @param bool $storeSerialized Disabling serialization can lead to cache corruptions when storing mutable values but increases performance otherwise
*/
public function __construct(
private int $defaultLifetime = 0,
private bool $deepClone = true,
private bool $storeSerialized = true,
private float $maxLifetime = 0,
private int $maxItems = 0,
private ?ClockInterface $clock = null,
@@ -60,11 +59,12 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, NamespacedPoolIn
}
self::$createCacheItem ??= \Closure::bind(
static function ($key, $value, $isHit, $tags, $expiry = null) {
static function ($key, $value, $isHit, $tags, $expiry = null, $clock = null) {
$item = new CacheItem();
$item->key = $key;
$item->value = $value;
$item->isHit = $isHit;
$item->clock = $clock;
if (null !== $tags) {
$item->metadata[CacheItem::METADATA_TAGS] = $tags;
}
@@ -79,9 +79,6 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, NamespacedPoolIn
);
}
/**
* @param-immediately-invoked-callable $callback
*/
public function get(string $key, callable $callback, ?float $beta = null, ?array &$metadata = null): mixed
{
$item = $this->getItem($key);
@@ -131,10 +128,10 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, NamespacedPoolIn
$this->values[$key] = null;
}
} else {
$value = $this->deepClone ? $this->unfreeze($key, $isHit) : $this->values[$key];
$value = $this->storeSerialized ? $this->unfreeze($key, $isHit) : $this->values[$key];
}
return (self::$createCacheItem)($key, $value, $isHit, $this->tags[$key] ?? null, $this->explicitExpiries[$key] ?? null);
return (self::$createCacheItem)($key, $value, $isHit, $this->tags[$key] ?? null, $this->explicitExpiries[$key] ?? null, $this->clock);
}
public function getItems(array $keys = []): iterable
@@ -186,26 +183,8 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, NamespacedPoolIn
return true;
}
}
if ($this->deepClone) {
try {
$cloner = new DeepCloner($value, null, true);
} catch (\Exception $e) {
if (!isset($this->expiries[$key])) {
unset($this->values[$key]);
}
$type = get_debug_type($value);
$message = \sprintf('Failed to save key "{key}" of type %s: %s', $type, $e->getMessage());
CacheItem::log($this->logger, $message, ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
return false;
}
// keep static values unwrapped for performance, except null (which must
// stay distinguishable from a cache miss) and strings holding a colon
// (which getValues() consumers must not confuse with a serialized value)
if (!$cloner->isStaticValue() || null === $value || (\is_string($value) && str_contains($value, ':'))) {
$value = $cloner;
}
if ($this->storeSerialized && null === $value = $this->freeze($value, $key)) {
return false;
}
if (null === $expiry && 0 < $this->defaultLifetime) {
$expiry = $this->defaultLifetime;
@@ -298,27 +277,20 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, NamespacedPoolIn
/**
* Returns all cached values, with cache miss as null.
*
* @param bool $raw Whether to return the raw stored values (DeepCloner instances and unwrapped scalars) instead of serialized strings
*/
public function getValues(/* bool $raw = false */): array
public function getValues(): array
{
$raw = \func_num_args() ? func_get_arg(0) : false;
if (!$this->deepClone || $raw) {
if (!$this->storeSerialized) {
return $this->values;
}
$values = $this->values;
foreach ($values as $k => $v) {
if (null === $v) {
if (null === $v || 'N;' === $v) {
continue;
}
try {
$values[$k] = serialize($v instanceof DeepCloner ? $v->clone(null, true) : $v);
} catch (\Exception) {
// skip values that cannot be serialized, e.g. when they hold a Closure
unset($values[$k]);
if (!\is_string($v) || !isset($v[2]) || ':' !== $v[1]) {
$values[$k] = serialize($v);
}
}
@@ -355,11 +327,11 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, NamespacedPoolIn
$this->values[$key] = $value;
}
$value = $this->deepClone ? $this->unfreeze($key, $isHit) : $this->values[$key];
$value = $this->storeSerialized ? $this->unfreeze($key, $isHit) : $this->values[$key];
}
unset($keys[$i]);
yield $key => $f($key, $value, $isHit, $this->tags[$key] ?? null, $this->explicitExpiries[$key] ?? null);
yield $key => $f($key, $value, $isHit, $this->tags[$key] ?? null, $this->explicitExpiries[$key] ?? null, $this->clock);
}
foreach ($keys as $key) {
@@ -367,22 +339,57 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, NamespacedPoolIn
}
}
private function freeze($value, string $key): string|int|float|bool|array|\UnitEnum|null
{
if (null === $value) {
return 'N;';
}
if (\is_string($value)) {
// Serialize strings if they could be confused with serialized objects or arrays
if ('N;' === $value || (isset($value[2]) && ':' === $value[1])) {
return serialize($value);
}
} elseif (!\is_scalar($value)) {
try {
$serialized = serialize($value);
} catch (\Exception $e) {
if (!isset($this->expiries[$key])) {
unset($this->values[$key]);
}
$type = get_debug_type($value);
$message = \sprintf('Failed to save key "{key}" of type %s: %s', $type, $e->getMessage());
CacheItem::log($this->logger, $message, ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
return null;
}
// Keep value serialized if it contains any objects or any internal references
if ('C' === $serialized[0] || 'O' === $serialized[0] || preg_match('/;[OCRr]:[1-9]/', $serialized)) {
return $serialized;
}
}
return $value;
}
private function unfreeze(string $key, bool &$isHit): mixed
{
$value = $this->values[$key];
if ($value instanceof DeepCloner) {
if ('N;' === $value = $this->values[$key]) {
return null;
}
if (\is_string($value) && isset($value[2]) && ':' === $value[1]) {
try {
return $value->clone(null, true);
$value = unserialize($value, ['allowed_classes' => true]);
} catch (\Exception $e) {
CacheItem::log($this->logger, 'Failed to clone key "{key}": '.$e->getMessage(), ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
CacheItem::log($this->logger, 'Failed to unserialize key "{key}": '.$e->getMessage(), ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
$value = false;
}
if (false === $value) {
$value = null;
$isHit = false;
if (!$this->maxItems) {
$this->values[$key] = null;
}
return null;
}
}
-3
View File
@@ -91,9 +91,6 @@ class ChainAdapter implements AdapterInterface, CacheInterface, NamespacedPoolIn
);
}
/**
* @param-immediately-invoked-callable $callback
*/
public function get(string $key, callable $callback, ?float $beta = null, ?array &$metadata = null): mixed
{
$doSave = true;
@@ -0,0 +1,237 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Cache\Adapter;
use Symfony\Component\Cache\Exception\CacheException;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
use Symfony\Component\Cache\Marshaller\MarshallerInterface;
trigger_deprecation('symfony/cache', '7.1', 'The "%s" class is deprecated, use "%s" instead.', CouchbaseBucketAdapter::class, CouchbaseCollectionAdapter::class);
/**
* @author Antonio Jose Cerezo Aranda <aj.cerezo@gmail.com>
*
* @deprecated since Symfony 7.1, use {@see CouchbaseCollectionAdapter} instead
*/
class CouchbaseBucketAdapter extends AbstractAdapter
{
private const THIRTY_DAYS_IN_SECONDS = 2592000;
private const MAX_KEY_LENGTH = 250;
private const KEY_NOT_FOUND = 13;
private const VALID_DSN_OPTIONS = [
'operationTimeout',
'configTimeout',
'configNodeTimeout',
'n1qlTimeout',
'httpTimeout',
'configDelay',
'htconfigIdleTimeout',
'durabilityInterval',
'durabilityTimeout',
];
private MarshallerInterface $marshaller;
public function __construct(
private \CouchbaseBucket $bucket,
string $namespace = '',
int $defaultLifetime = 0,
?MarshallerInterface $marshaller = null,
) {
if (!static::isSupported()) {
throw new CacheException('Couchbase >= 2.6.0 < 3.0.0 is required.');
}
$this->maxIdLength = static::MAX_KEY_LENGTH;
parent::__construct($namespace, $defaultLifetime);
$this->enableVersioning();
$this->marshaller = $marshaller ?? new DefaultMarshaller();
}
public static function createConnection(#[\SensitiveParameter] array|string $servers, array $options = []): \CouchbaseBucket
{
if (\is_string($servers)) {
$servers = [$servers];
}
if (!static::isSupported()) {
throw new CacheException('Couchbase >= 2.6.0 < 3.0.0 is required.');
}
set_error_handler(static fn ($type, $msg, $file, $line) => throw new \ErrorException($msg, 0, $type, $file, $line));
$dsnPattern = '/^(?<protocol>couchbase(?:s)?)\:\/\/(?:(?<username>[^\:]+)\:(?<password>[^\@]{6,})@)?'
.'(?<host>[^\:]+(?:\:\d+)?)(?:\/(?<bucketName>[^\?]+))(?:\?(?<options>.*))?$/i';
$newServers = [];
$protocol = 'couchbase';
try {
$options = self::initOptions($options);
$username = $options['username'];
$password = $options['password'];
foreach ($servers as $dsn) {
if (!str_starts_with($dsn, 'couchbase:')) {
throw new InvalidArgumentException('Invalid Couchbase DSN: it does not start with "couchbase:".');
}
preg_match($dsnPattern, $dsn, $matches);
$username = $matches['username'] ?: $username;
$password = $matches['password'] ?: $password;
$protocol = $matches['protocol'] ?: $protocol;
if (isset($matches['options'])) {
$optionsInDsn = self::getOptions($matches['options']);
foreach ($optionsInDsn as $parameter => $value) {
$options[$parameter] = $value;
}
}
$newServers[] = $matches['host'];
}
$connectionString = $protocol.'://'.implode(',', $newServers);
$client = new \CouchbaseCluster($connectionString);
$client->authenticateAs($username, $password);
$bucket = $client->openBucket($matches['bucketName']);
unset($options['username'], $options['password']);
foreach ($options as $option => $value) {
if ($value) {
$bucket->$option = $value;
}
}
return $bucket;
} finally {
restore_error_handler();
}
}
public static function isSupported(): bool
{
return \extension_loaded('couchbase') && version_compare(phpversion('couchbase'), '2.6.0', '>=') && version_compare(phpversion('couchbase'), '3.0', '<');
}
private static function getOptions(string $options): array
{
$results = [];
$optionsInArray = explode('&', $options);
foreach ($optionsInArray as $option) {
[$key, $value] = explode('=', $option);
if (\in_array($key, static::VALID_DSN_OPTIONS, true)) {
$results[$key] = $value;
}
}
return $results;
}
private static function initOptions(array $options): array
{
$options['username'] ??= '';
$options['password'] ??= '';
$options['operationTimeout'] ??= 0;
$options['configTimeout'] ??= 0;
$options['configNodeTimeout'] ??= 0;
$options['n1qlTimeout'] ??= 0;
$options['httpTimeout'] ??= 0;
$options['configDelay'] ??= 0;
$options['htconfigIdleTimeout'] ??= 0;
$options['durabilityInterval'] ??= 0;
$options['durabilityTimeout'] ??= 0;
return $options;
}
protected function doFetch(array $ids): iterable
{
$resultsCouchbase = $this->bucket->get($ids);
$results = [];
foreach ($resultsCouchbase as $key => $value) {
if (null !== $value->error) {
continue;
}
$results[$key] = $this->marshaller->unmarshall($value->value);
}
return $results;
}
protected function doHave(string $id): bool
{
return false !== $this->bucket->get($id);
}
protected function doClear(string $namespace): bool
{
if ('' === $namespace) {
$this->bucket->manager()->flush();
return true;
}
return false;
}
protected function doDelete(array $ids): bool
{
$results = $this->bucket->remove(array_values($ids));
foreach ($results as $key => $result) {
if (null !== $result->error && static::KEY_NOT_FOUND !== $result->error->getCode()) {
continue;
}
unset($results[$key]);
}
return 0 === \count($results);
}
protected function doSave(array $values, int $lifetime): array|bool
{
if (!$values = $this->marshaller->marshall($values, $failed)) {
return $failed;
}
$lifetime = $this->normalizeExpiry($lifetime);
$ko = [];
foreach ($values as $key => $value) {
$result = $this->bucket->upsert($key, $value, ['expiry' => $lifetime]);
if (null !== $result->error) {
$ko[$key] = $result;
}
}
return [] === $ko ? true : $ko;
}
private function normalizeExpiry(int $expiry): int
{
if ($expiry && $expiry > static::THIRTY_DAYS_IN_SECONDS) {
$expiry += time();
}
return $expiry;
}
}
+21 -12
View File
@@ -21,7 +21,6 @@ use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Platforms\AbstractMySQLPlatform;
use Doctrine\DBAL\Platforms\OraclePlatform;
use Doctrine\DBAL\Platforms\PostgreSQLPlatform;
use Doctrine\DBAL\Platforms\SQLitePlatform;
use Doctrine\DBAL\Platforms\SQLServerPlatform;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\DefaultSchemaManagerFactory;
@@ -74,10 +73,6 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
array $options = [],
?MarshallerInterface $marshaller = null,
) {
if (!class_exists(PrimaryKeyConstraint::class)) {
throw new \LogicException(\sprintf('Using "%s" requires "doctrine/dbal" 4.3 or higher; try running "composer require doctrine/dbal:^4.3".', __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]));
}
@@ -135,9 +130,9 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
}
/**
* @param-immediately-invoked-callable $isSameDatabase
* @return Schema The (possibly new) schema with the table added
*/
public function configureSchema(Schema $schema, Connection $forConnection, \Closure $isSameDatabase): Schema
public function configureSchema(Schema $schema, Connection $forConnection, \Closure $isSameDatabase)
{
if ($schema->hasTable($this->table)) {
return $schema;
@@ -222,13 +217,16 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
{
if ('' === $namespace) {
$sql = $this->conn->getDatabasePlatform()->getTruncateTableSQL($this->table);
$params = [];
} else {
$namespace = str_replace('_', '!_', $namespace);
$sql = "DELETE FROM $this->table WHERE $this->idCol LIKE '$namespace%' ESCAPE '!'";
// SQL Server also treats [ as a wildcard, while Oracle rejects an escape character followed by it
$namespace = preg_replace('sqlsrv' === $this->getPlatformName() ? '/[!%_[]/' : '/[!%_]/', '!$0', $namespace);
$sql = "DELETE FROM $this->table WHERE $this->idCol LIKE ? ESCAPE '!'";
$params = [$namespace.'%'];
}
try {
$this->conn->executeStatement($sql);
$this->conn->executeStatement($sql, $params);
} catch (TableNotFoundException) {
}
@@ -395,9 +393,16 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
$platform = $this->conn->getDatabasePlatform();
if (interface_exists(DBALException::class)) {
// DBAL 4+
$sqlitePlatformClass = 'Doctrine\DBAL\Platforms\SQLitePlatform';
} else {
$sqlitePlatformClass = 'Doctrine\DBAL\Platforms\SqlitePlatform';
}
return $this->platformName = match (true) {
$platform instanceof AbstractMySQLPlatform => 'mysql',
$platform instanceof SQLitePlatform => 'sqlite',
$platform instanceof $sqlitePlatformClass => 'sqlite',
$platform instanceof PostgreSQLPlatform => 'pgsql',
$platform instanceof OraclePlatform => 'oci',
$platform instanceof SQLServerPlatform => 'sqlsrv',
@@ -448,6 +453,10 @@ class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
$table->addColumn($this->lifetimeCol, 'integer', ['unsigned' => true, 'notnull' => false]);
$table->addColumn($this->timeCol, 'integer', ['unsigned' => true]);
$table->addPrimaryKeyConstraint(new PrimaryKeyConstraint(null, [new UnqualifiedName(Identifier::unquoted($this->idCol))], true));
if (class_exists(PrimaryKeyConstraint::class)) {
$table->addPrimaryKeyConstraint(new PrimaryKeyConstraint(null, [new UnqualifiedName(Identifier::unquoted($this->idCol))], true));
} else {
$table->setPrimaryKey([$this->idCol]);
}
}
}
-3
View File
@@ -39,9 +39,6 @@ class NullAdapter implements AdapterInterface, CacheInterface, NamespacedPoolInt
);
}
/**
* @param-immediately-invoked-callable $callback
*/
public function get(string $key, callable $callback, ?float $beta = null, ?array &$metadata = null): mixed
{
$save = true;
+10 -3
View File
@@ -223,13 +223,20 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface
} else {
$sql = "TRUNCATE TABLE $this->table";
}
$params = [];
} else {
$namespace = str_replace('_', '!_', $namespace);
$sql = "DELETE FROM $this->table WHERE $this->idCol LIKE '$namespace%' ESCAPE '!'";
// SQL Server also treats [ as a wildcard, while Oracle rejects an escape character followed by it
$namespace = preg_replace('sqlsrv' === $this->getDriver() ? '/[!%_[]/' : '/[!%_]/', '!$0', $namespace);
$sql = "DELETE FROM $this->table WHERE $this->idCol LIKE ? ESCAPE '!'";
$params = [$namespace.'%'];
}
try {
$conn->exec($sql);
if ($params) {
$conn->prepare($sql)->execute($params);
} else {
$conn->exec($sql);
}
} catch (\PDOException) {
}
+1 -2
View File
@@ -41,8 +41,7 @@ class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
* @param bool $appendOnly Set to `true` to gain extra performance when the items stored in this pool never expire.
* Doing so is encouraged because it fits perfectly OPcache's memory model.
*
* @throws InvalidArgumentException When $namespace contains invalid characters, exceeds the adapter's max length
* or when the resolved cache directory path is too long on Windows
* @throws CacheException if OPcache is not enabled
*/
public function __construct(
string $namespace = '',
-3
View File
@@ -86,9 +86,6 @@ class ProxyAdapter implements AdapterInterface, NamespacedPoolInterface, CacheIn
);
}
/**
* @param-immediately-invoked-callable $callback
*/
public function get(string $key, callable $callback, ?float $beta = null, ?array &$metadata = null): mixed
{
if (!$this->pool instanceof CacheInterface) {
@@ -39,8 +39,6 @@ class TraceableAdapter implements AdapterInterface, CacheInterface, NamespacedPo
}
/**
* @param-immediately-invoked-callable $callback
*
* @throws BadMethodCallException When the item pool is not a CacheInterface
*/
public function get(string $key, callable $callback, ?float $beta = null, ?array &$metadata = null): mixed