diff --git a/src/KeyNormalizer.php b/src/KeyNormalizer.php new file mode 100644 index 0000000..7507e47 --- /dev/null +++ b/src/KeyNormalizer.php @@ -0,0 +1,40 @@ +, Tobias Nyholm + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Cache\CacheBundle; + +/** + * A class to normalize cache keys. + * + * @author Tobias Nyholm + */ +class KeyNormalizer +{ + /** + * Remove all characters that is not supported by PSR6. + * + * @param $key + */ + public static function onlyValid($key) + { + return preg_replace('|[^A-Za-z0-9_\.]|', '', $key); + } + + /** + * Remove all characters that are marked as reserved in PSR6. + * + * @param string $key + */ + public static function noInvalid($key) + { + return preg_replace('|[\{\}\(\)/\\\@\:]|', '', $key); + } +} diff --git a/src/Routing/CachingRouter.php b/src/Routing/CachingRouter.php index 6a631a2..5124b1f 100644 --- a/src/Routing/CachingRouter.php +++ b/src/Routing/CachingRouter.php @@ -11,6 +11,7 @@ namespace Cache\CacheBundle\Routing; +use Cache\CacheBundle\KeyNormalizer; use Cache\Taggable\TaggableItemInterface; use Psr\Cache\CacheItemPoolInterface; use Symfony\Component\Routing\RequestContext; @@ -125,7 +126,7 @@ private function getCacheItemMatch($pathinfo) { /** @type RequestContext $c */ $c = $this->getContext(); - $key = sprintf('%s__%s__%s__%s', $c->getHost(), str_replace('/', '.', $pathinfo), $c->getMethod(), $c->getQueryString()); + $key = sprintf('%s__%s__%s__%s', $c->getHost(), $pathinfo, $c->getMethod(), $c->getQueryString()); return $this->getCacheItemFromKey($key, 'match'); } @@ -163,7 +164,7 @@ public function __call($method, $args) */ private function getCacheItemFromKey($key, $tag) { - $item = $this->cache->getItem($key); + $item = $this->cache->getItem(KeyNormalizer::noInvalid($key)); if ($item instanceof TaggableItemInterface) { $item->setTags(['router', $tag]); diff --git a/tests/KeyNormalizerTest.php b/tests/KeyNormalizerTest.php new file mode 100644 index 0000000..e6fd69f --- /dev/null +++ b/tests/KeyNormalizerTest.php @@ -0,0 +1,31 @@ +, Tobias Nyholm + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Cache\CacheBundle\Tests; + +use Cache\CacheBundle\KeyNormalizer; + +class KeyNormalizerTest extends \PHPUnit_Framework_TestCase +{ + public function testOnlyValid() + { + $input = '%foo!bar-'; + $expected = 'foobar'; + $this->assertEquals($expected, KeyNormalizer::onlyValid($input)); + } + + public function testNoInvalid() + { + $input = '{foo@bar}'; + $expected = 'foobar'; + $this->assertEquals($expected, KeyNormalizer::noInvalid($input)); + } +}