From 4795756cc7e2f4fe32daaea4fe912785d3e07405 Mon Sep 17 00:00:00 2001 From: Nyholm Date: Wed, 21 Oct 2020 23:51:48 +0200 Subject: [PATCH] [RateLimiter] Be more type safe when fetching form cache --- .../Component/RateLimiter/Storage/CacheStorage.php | 7 ++++--- .../RateLimiter/Tests/Storage/CacheStorageTest.php | 12 ++++++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/Symfony/Component/RateLimiter/Storage/CacheStorage.php b/src/Symfony/Component/RateLimiter/Storage/CacheStorage.php index 5c39b0fcd2b2d..34e27798e6375 100644 --- a/src/Symfony/Component/RateLimiter/Storage/CacheStorage.php +++ b/src/Symfony/Component/RateLimiter/Storage/CacheStorage.php @@ -42,11 +42,12 @@ public function save(LimiterStateInterface $limiterState): void public function fetch(string $limiterStateId): ?LimiterStateInterface { $cacheItem = $this->pool->getItem(sha1($limiterStateId)); - if (!$cacheItem->isHit()) { - return null; + $value = $cacheItem->get(); + if ($value instanceof LimiterStateInterface) { + return $value; } - return $cacheItem->get(); + return null; } public function delete(string $limiterStateId): void diff --git a/src/Symfony/Component/RateLimiter/Tests/Storage/CacheStorageTest.php b/src/Symfony/Component/RateLimiter/Tests/Storage/CacheStorageTest.php index de8f77b4630e8..97de6e554fda7 100644 --- a/src/Symfony/Component/RateLimiter/Tests/Storage/CacheStorageTest.php +++ b/src/Symfony/Component/RateLimiter/Tests/Storage/CacheStorageTest.php @@ -55,6 +55,18 @@ public function testFetchExistingState() $this->assertEquals($window, $this->storage->fetch('test')); } + public function testFetchExistingJunk() + { + $cacheItem = $this->createMock(CacheItemInterface::class); + + $cacheItem->expects($this->any())->method('get')->willReturn('junk'); + $cacheItem->expects($this->any())->method('isHit')->willReturn(true); + + $this->pool->expects($this->any())->method('getItem')->with(sha1('test'))->willReturn($cacheItem); + + $this->assertNull($this->storage->fetch('test')); + } + public function testFetchNonExistingState() { $cacheItem = $this->createMock(CacheItemInterface::class);