[Cache] Test & tweak CacheItem::validateKey()

This commit is contained in:
Nicolas Grekas 2016-04-20 18:02:35 +02:00
parent 357785aace
commit 4256add915
5 changed files with 65 additions and 8 deletions

View File

@ -337,7 +337,9 @@ abstract class AbstractAdapter implements AdapterInterface, LoggerAwareInterface
private function getId($key)
{
return $this->namespace.CacheItem::validateKey($key);
CacheItem::validateKey($key);
return $this->namespace.$key;
}
private function generateItems($items, &$keys)

View File

@ -84,7 +84,9 @@ class ArrayAdapter implements AdapterInterface, LoggerAwareInterface
*/
public function hasItem($key)
{
return isset($this->expiries[CacheItem::validateKey($key)]) && ($this->expiries[$key] >= time() || !$this->deleteItem($key));
CacheItem::validateKey($key);
return isset($this->expiries[$key]) && ($this->expiries[$key] >= time() || !$this->deleteItem($key));
}
/**
@ -102,7 +104,9 @@ class ArrayAdapter implements AdapterInterface, LoggerAwareInterface
*/
public function deleteItem($key)
{
unset($this->values[CacheItem::validateKey($key)], $this->expiries[$key]);
CacheItem::validateKey($key);
unset($this->values[$key], $this->expiries[$key]);
return true;
}

View File

@ -193,6 +193,8 @@ class ProxyAdapter implements AdapterInterface
private function getId($key)
{
return $this->namespace.CacheItem::validateKey($key);
CacheItem::validateKey($key);
return $this->namespace.$key;
}
}

View File

@ -104,8 +104,6 @@ final class CacheItem implements CacheItemInterface
*
* @param string $key The key to validate.
*
* @return string $key if it is valid.
*
* @throws InvalidArgumentException When $key is not valid.
*/
public static function validateKey($key)
@ -119,8 +117,6 @@ final class CacheItem implements CacheItemInterface
if (isset($key[strcspn($key, '{}()/\@:')])) {
throw new InvalidArgumentException('Cache key contains reserved characters {}()/\@:');
}
return $key;
}
/**

View File

@ -0,0 +1,53 @@
<?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\Tests;
use Symfony\Component\Cache\CacheItem;
class CacheItemTest extends \PHPUnit_Framework_TestCase
{
public function testValidKey()
{
$this->assertNull(CacheItem::validateKey('foo'));
}
/**
* @dataProvider provideInvalidKey
* @expectedException Symfony\Component\Cache\Exception\InvalidArgumentException
* @expectedExceptionMessage Cache key
*/
public function testInvalidKey($key)
{
CacheItem::validateKey($key);
}
public function provideInvalidKey()
{
return array(
array(''),
array('{'),
array('}'),
array('('),
array(')'),
array('/'),
array('\\'),
array('@'),
array(':'),
array(true),
array(null),
array(1),
array(1.1),
array(array()),
array(new \Exception('foo')),
);
}
}