Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Cache] Allow to use namespace delimiter in cache key #54710

Open
wants to merge 4 commits into
base: 7.2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/Symfony/Component/Cache/Adapter/AbstractAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,19 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg
*/
protected const NS_SEPARATOR = ':';

/**
* @internal
*/
protected static ?string $reservedChars = null;

private static bool $apcuSupported;

protected function __construct(string $namespace = '', int $defaultLifetime = 0)
{
$this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace).static::NS_SEPARATOR;
if (null === static::$reservedChars) {
static::$reservedChars = str_replace(self::NS_SEPARATOR, '', CacheItem::RESERVED_CHARACTERS);
}
$this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace, static::$reservedChars).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));
Expand Down
15 changes: 14 additions & 1 deletion src/Symfony/Component/Cache/Adapter/AbstractTagAwareAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,22 @@ abstract class AbstractTagAwareAdapter implements TagAwareAdapterInterface, TagA

private const TAGS_PREFIX = "\1tags\1";

/**
* @internal
*/
protected const NS_SEPARATOR = ':';

/**
* @internal
*/
protected static ?string $reservedChars = null;

protected function __construct(string $namespace = '', int $defaultLifetime = 0)
{
$this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace).':';
if (null === static::$reservedChars) {
static::$reservedChars = str_replace(self::NS_SEPARATOR, '', CacheItem::RESERVED_CHARACTERS);
}
$this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace, static::$reservedChars).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));
Expand Down
20 changes: 17 additions & 3 deletions src/Symfony/Component/Cache/Adapter/ArrayAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
{
use LoggerAwareTrait;

/**
* @internal
*/
protected const NS_SEPARATOR = ':';

/**
* @internal
*/
protected static ?string $reservedChars = null;

private array $values = [];
private array $tags = [];
private array $expiries = [];
Expand All @@ -45,6 +55,10 @@ public function __construct(
private float $maxLifetime = 0,
private int $maxItems = 0,
) {
if (null === static::$reservedChars) {
static::$reservedChars = str_replace(self::NS_SEPARATOR, '', CacheItem::RESERVED_CHARACTERS);
}

if (0 > $maxLifetime) {
throw new InvalidArgumentException(sprintf('Argument $maxLifetime must be positive, %F passed.', $maxLifetime));
}
Expand Down Expand Up @@ -104,7 +118,7 @@ public function hasItem(mixed $key): bool

return true;
}
\assert('' !== CacheItem::validateKey($key));
\assert('' !== CacheItem::validateKey($key, static::$reservedChars));

return isset($this->expiries[$key]) && !$this->deleteItem($key);
}
Expand Down Expand Up @@ -134,7 +148,7 @@ public function getItems(array $keys = []): iterable

public function deleteItem(mixed $key): bool
{
\assert('' !== CacheItem::validateKey($key));
\assert('' !== CacheItem::validateKey($key, static::$reservedChars));
unset($this->values[$key], $this->tags[$key], $this->expiries[$key]);

return true;
Expand Down Expand Up @@ -350,7 +364,7 @@ private function validateKeys(array $keys): bool
{
foreach ($keys as $key) {
if (!\is_string($key) || !isset($this->expiries[$key])) {
CacheItem::validateKey($key);
CacheItem::validateKey($key, static::$reservedChars);
}
}

Expand Down
22 changes: 22 additions & 0 deletions src/Symfony/Component/Cache/Adapter/Psr16Adapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Cache\Adapter;

use Psr\SimpleCache\CacheInterface;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\PruneableInterface;
use Symfony\Component\Cache\ResettableInterface;
use Symfony\Component\Cache\Traits\ProxyTrait;
Expand Down Expand Up @@ -40,6 +41,20 @@ public function __construct(CacheInterface $pool, string $namespace = '', int $d
$this->miss = new \stdClass();
}

public function getItem(mixed $key): CacheItem
{
CacheItem::validateKey($key);

return parent::getItem($key);
}

public function getItems(array $keys = []): iterable
{
CacheItem::validateKeys($keys);

return parent::getItems($keys);
}

protected function doFetch(array $ids): iterable
{
foreach ($this->pool->getMultiple($ids, $this->miss) as $key => $value) {
Expand All @@ -64,6 +79,13 @@ protected function doDelete(array $ids): bool
return $this->pool->deleteMultiple($ids);
}

public function deleteItems(array $keys): bool
{
CacheItem::validateKeys($keys);

return parent::deleteItems($keys);
}

protected function doSave(array $values, int $lifetime): array|bool
{
return $this->pool->setMultiple($values, 0 === $lifetime ? null : $lifetime);
Expand Down
19 changes: 15 additions & 4 deletions src/Symfony/Component/Cache/CacheItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,25 +123,36 @@ public function getMetadata(): array
/**
* Validates a cache key according to PSR-6.
*
* @param mixed $key The key to validate
* @param mixed $key The key to validate
* @param string $reservedChars Can be used to override the list of reserved characters
*
* @throws InvalidArgumentException When $key is not valid
*/
public static function validateKey($key): string
public static function validateKey($key, string $reservedChars = self::RESERVED_CHARACTERS): string
{
if (!\is_string($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));
if ('' !== $reservedChars && false !== strpbrk($key, $reservedChars)) {
throw new InvalidArgumentException(sprintf('Cache key "%s" contains reserved characters "%s".', $key, $reservedChars));
}

return $key;
}

/**
* @param mixed[] $keys The keys to validate
*/
public static function validateKeys(array $keys): void
{
foreach ($keys as $key) {
self::validateKey($key);
}
}

/**
* Internal logging helper.
*
Expand Down
17 changes: 15 additions & 2 deletions src/Symfony/Component/Cache/Psr16Cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
if ($allowInt && \is_int($key)) {
$item->key = (string) $key;
} else {
\assert('' !== CacheItem::validateKey($key));
CacheItem::validateKey($key);
$item->key = $key;
}
$item->value = $value;
Expand Down Expand Up @@ -79,6 +79,7 @@

public function get($key, $default = null): mixed
{
CacheItem::validateKey($key);
try {
$item = $this->pool->getItem($key);
} catch (SimpleCacheException $e) {
Expand All @@ -96,6 +97,7 @@

public function set($key, $value, $ttl = null): bool
{
CacheItem::validateKey($key);
try {
if (null !== $f = $this->createCacheItem) {
$item = $f($key, $value);
Expand All @@ -117,6 +119,8 @@
public function delete($key): bool
{
try {
CacheItem::validateKey($key);

return $this->pool->deleteItem($key);
} catch (SimpleCacheException $e) {
throw $e;
Expand All @@ -130,7 +134,7 @@
return $this->pool->clear();
}

public function getMultiple($keys, $default = null): iterable

Check failure on line 137 in src/Symfony/Component/Cache/Psr16Cache.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidReturnType

src/Symfony/Component/Cache/Psr16Cache.php:137:58: InvalidReturnType: The declared return type 'iterable<string, mixed>' for Symfony\Component\Cache\Psr16Cache::getMultiple is incorrect, got 'array<array-key, mixed>' (see https://psalm.dev/011)

Check failure on line 137 in src/Symfony/Component/Cache/Psr16Cache.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidReturnType

src/Symfony/Component/Cache/Psr16Cache.php:137:58: InvalidReturnType: The declared return type 'iterable<string, mixed>' for Symfony\Component\Cache\Psr16Cache::getMultiple is incorrect, got 'array<array-key, mixed>' (see https://psalm.dev/011)
{
if ($keys instanceof \Traversable) {
$keys = iterator_to_array($keys, false);
Expand All @@ -139,6 +143,7 @@
}

try {
CacheItem::validateKeys($keys);
$items = $this->pool->getItems($keys);
} catch (SimpleCacheException $e) {
throw $e;
Expand Down Expand Up @@ -179,14 +184,17 @@
} elseif ($valuesIsArray) {
$items = [];
foreach ($values as $key => $value) {
$items[] = (string) $key;
$key = (string) $key;
CacheItem::validateKey($key);
$items[] = $key;
}
$items = $this->pool->getItems($items);
} else {
foreach ($values as $key => $value) {
if (\is_int($key)) {
$key = (string) $key;
}
CacheItem::validateKey($key);
$items[$key] = $this->pool->getItem($key)->set($value);
}
}
Expand All @@ -198,6 +206,7 @@
$ok = true;

foreach ($items as $key => $item) {
CacheItem::validateKey((string) $key);
if ($valuesIsArray) {
$item->set($values[$key]);
}
Expand All @@ -219,6 +228,8 @@
}

try {
CacheItem::validateKeys($keys);

return $this->pool->deleteItems($keys);
} catch (SimpleCacheException $e) {
throw $e;
Expand All @@ -230,6 +241,8 @@
public function has($key): bool
{
try {
CacheItem::validateKey($key);

return $this->pool->hasItem($key);
} catch (SimpleCacheException $e) {
throw $e;
Expand Down
12 changes: 12 additions & 0 deletions src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@

abstract class AdapterTestCase extends CachePoolTest
{
protected static ?string $allowPsr6Keys = ':';

protected function setUp(): void
{
parent::setUp();
Expand All @@ -40,6 +42,16 @@ protected function setUp(): void
}
}

public static function invalidKeys(): array
{
$keys = parent::invalidKeys();
if (null !== static::$allowPsr6Keys) {
$keys = array_filter($keys, fn ($key) => !\is_string($key[0] ?? null) || false === strpbrk($key[0], static::$allowPsr6Keys));
}

return $keys;
}

public function testGet()
{
if (isset($this->skippedTests[__FUNCTION__])) {
Expand Down