From 27de2de631df6f078d74abac01f5cb5e0e9b8e8f Mon Sep 17 00:00:00 2001 From: Phillip Look Date: Tue, 31 Mar 2020 09:16:37 +0200 Subject: [PATCH] Use checks from AbstractCache to ensure data is valid on load --- src/Storage/Adapter.php | 12 +++++++----- tests/AdapterCacheTests.php | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/src/Storage/Adapter.php b/src/Storage/Adapter.php index 3aa8b1a..9d64b43 100644 --- a/src/Storage/Adapter.php +++ b/src/Storage/Adapter.php @@ -67,11 +67,13 @@ public function setFromStorage($json) { list($cache, $complete, $expire) = json_decode($json, true); - if (! $expire || $expire > $this->getTime()) { - $this->cache = $cache; - $this->complete = $complete; - } else { - $this->adapter->delete($this->file); + if (json_last_error() === JSON_ERROR_NONE && is_array($cache) && is_array($complete)) { + if (! $expire || $expire > $this->getTime()) { + $this->cache = $cache; + $this->complete = $complete; + } else { + $this->adapter->delete($this->file); + } } } diff --git a/tests/AdapterCacheTests.php b/tests/AdapterCacheTests.php index b63cba7..1d9d23f 100644 --- a/tests/AdapterCacheTests.php +++ b/tests/AdapterCacheTests.php @@ -14,6 +14,39 @@ public function testLoadFail() $this->assertFalse($cache->isComplete('', false)); } + public function testLoadInvalidJson() + { + $response = ['contents' => 'invalid json', 'path' => 'file.json']; + $adapter = Mockery::mock('League\Flysystem\AdapterInterface'); + $adapter->shouldReceive('has')->once()->with('file.json')->andReturn(true); + $adapter->shouldReceive('read')->once()->with('file.json')->andReturn($response); + $cache = new Adapter($adapter, 'file.json', 10); + $cache->load(); + $this->assertFalse($cache->isComplete('', false)); + } + + public function testLoadInvalidDataCacheIsNotAnArray() + { + $response = ['contents' => json_encode([null, ['' => true], 9876543210]), 'path' => 'file.json']; + $adapter = Mockery::mock('League\Flysystem\AdapterInterface'); + $adapter->shouldReceive('has')->once()->with('file.json')->andReturn(true); + $adapter->shouldReceive('read')->once()->with('file.json')->andReturn($response); + $cache = new Adapter($adapter, 'file.json', 10); + $cache->load(); + $this->assertFalse($cache->isComplete('', false)); + } + + public function testLoadInvalidDataCompleteIsNotAnArray() + { + $response = ['contents' => json_encode([[], null, 9876543210]), 'path' => 'file.json']; + $adapter = Mockery::mock('League\Flysystem\AdapterInterface'); + $adapter->shouldReceive('has')->once()->with('file.json')->andReturn(true); + $adapter->shouldReceive('read')->once()->with('file.json')->andReturn($response); + $cache = new Adapter($adapter, 'file.json', 10); + $cache->load(); + $this->assertFalse($cache->isComplete('', false)); + } + public function testLoadExpired() { $response = ['contents' => json_encode([[], ['' => true], 1234567890]), 'path' => 'file.json'];