Skip to content

Commit

Permalink
Reduce filesystem operations (#94)
Browse files Browse the repository at this point in the history
* Reduce filesystem operations

* Updated changelog

* Handle race condition

* typo

* cs

* Handle exception

* cs
  • Loading branch information
Nyholm authored Oct 19, 2016
1 parent 2040282 commit eeb6a2b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 14 deletions.
4 changes: 4 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ The change log describes what is "Added", "Removed", "Changed" or "Fixed" betwee

## UNRELEASED

### Changed

Using `Filesystem::update` instead of `Filesystem::delete` and `Filesystem::write`.

## 0.3.1

### Added
Expand Down
45 changes: 31 additions & 14 deletions FilesystemCachePool.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Cache\Taggable\TaggableItemInterface;
use Cache\Taggable\TaggablePoolInterface;
use Cache\Taggable\TaggablePoolTrait;
use League\Flysystem\FileExistsException;
use League\Flysystem\FileNotFoundException;
use League\Flysystem\Filesystem;
use Psr\Cache\CacheItemInterface;
Expand Down Expand Up @@ -64,19 +65,25 @@ public function setFolder($folder)
*/
protected function fetchObjectFromCache($key)
{
$file = $this->getFilePath($key);
$empty = [false, null, []];
$file = $this->getFilePath($key);
if (!$this->filesystem->has($file)) {
return [false, null, []];
return $empty;
}

try {
$data = unserialize($this->filesystem->read($file));
} catch (FileNotFoundException $e) {
return $empty;
}

$data = unserialize($this->filesystem->read($file));
if ($data[0] !== null && time() > $data[0]) {
foreach ($data[2] as $tag) {
$this->removeListItem($this->getTagKey($tag), $key);
}
$this->forceClear($key);

return [false, null, []];
return $empty;
}

return [true, $data[1], $data[2]];
Expand Down Expand Up @@ -108,21 +115,31 @@ protected function clearOneObjectFromCache($key)
*/
protected function storeItemInCache(CacheItemInterface $item, $ttl)
{
$file = $this->getFilePath($item->getKey());
if ($this->filesystem->has($file)) {
$this->filesystem->delete($file);
}

$tags = [];
if ($item instanceof TaggableItemInterface) {
$tags = $item->getTags();
}

return $this->filesystem->write($file, serialize([
($ttl === null ? null : time() + $ttl),
$item->get(),
$tags,
]));
$data = serialize(
[
($ttl === null ? null : time() + $ttl),
$item->get(),
$tags,
]
);

$file = $this->getFilePath($item->getKey());
if ($this->filesystem->has($file)) {
// Update file if it exists
return $this->filesystem->update($file, $data);
}

try {
return $this->filesystem->write($file, $data);
} catch (FileExistsException $e) {
// To handle issues when/if race conditions occurs, we try to update here.
return $this->filesystem->update($file, $data);
}
}

/**
Expand Down

0 comments on commit eeb6a2b

Please sign in to comment.