From c3ec2fb1de08e7b6736c0e7bfde449974ee08917 Mon Sep 17 00:00:00 2001 From: Possum Date: Tue, 5 Jan 2016 23:14:09 +0100 Subject: [PATCH] Make file cache tolerant for trailing (back)slashes on directory configuration. --- lib/Twig/Cache/Filesystem.php | 4 ++-- test/Twig/Tests/Cache/FilesystemTest.php | 25 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/lib/Twig/Cache/Filesystem.php b/lib/Twig/Cache/Filesystem.php index 2c2182a82f..bebc2bfad8 100644 --- a/lib/Twig/Cache/Filesystem.php +++ b/lib/Twig/Cache/Filesystem.php @@ -27,7 +27,7 @@ class Twig_Cache_Filesystem implements Twig_CacheInterface */ public function __construct($directory, $options = 0) { - $this->directory = $directory; + $this->directory = rtrim($directory, '\/').'/'; $this->options = $options; } @@ -38,7 +38,7 @@ public function generateKey($name, $className) { $hash = hash('sha256', $className); - return $this->directory.'/'.$hash[0].$hash[1].'/'.$hash.'.php'; + return $this->directory.$hash[0].$hash[1].'/'.$hash.'.php'; } /** diff --git a/test/Twig/Tests/Cache/FilesystemTest.php b/test/Twig/Tests/Cache/FilesystemTest.php index 541328dd62..93a92d93d9 100644 --- a/test/Twig/Tests/Cache/FilesystemTest.php +++ b/test/Twig/Tests/Cache/FilesystemTest.php @@ -159,6 +159,31 @@ public function testGetTimestampMissingFile() $this->assertSame(0, $this->cache->getTimestamp($key)); } + /** + * Test file cache is tolerant towards trailing (back)slashes on the configured cache directory. + * + * @dataProvider provideDirectories + */ + public function testGenerateKey($expected, $input) + { + $cache = new Twig_Cache_Filesystem($input); + $this->assertRegExp($expected, $cache->generateKey('_test_', get_class($this))); + } + + public function provideDirectories() + { + $pattern = '#a/b/[a-zA-Z0-9]+/[a-zA-Z0-9]+.php$#'; + + return array( + array($pattern, 'a/b'), + array($pattern, 'a/b/'), + array($pattern, 'a/b\\'), + array($pattern, 'a/b\\/'), + array($pattern, 'a/b\\//'), + array('#/'.substr($pattern, 1), '/a/b'), + ); + } + private function generateSource() { return strtr('