Skip to content

Commit

Permalink
Use checks from AbstractCache to ensure data is valid on load
Browse files Browse the repository at this point in the history
  • Loading branch information
Phillip Look authored and pl-github committed Jun 11, 2024
1 parent d1925ef commit 83fa07a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/Storage/Adapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,13 @@ public function setFromStorage($json)
{
list($cache, $complete, $expire) = json_decode($json, true);

if (! $expire || $expire > $this->getTime()) {
if (json_last_error() === JSON_ERROR_NONE && is_array($cache) && is_array($complete)) {
if (! $expire || $expire > $this->getTime()) {
$this->cache = is_array($cache) ? $cache : [];
$this->complete = is_array($complete) ? $complete : [];
} else {
$this->adapter->delete($this->file);
} else {
$this->adapter->delete($this->file);
}
}
}

Expand Down
33 changes: 33 additions & 0 deletions tests/AdapterCacheTests.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'];
Expand Down

0 comments on commit 83fa07a

Please sign in to comment.