diff --git a/Changelog.md b/Changelog.md index 7bb5560..59df633 100644 --- a/Changelog.md +++ b/Changelog.md @@ -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 diff --git a/FilesystemCachePool.php b/FilesystemCachePool.php index 3ed47bd..11bfde1 100644 --- a/FilesystemCachePool.php +++ b/FilesystemCachePool.php @@ -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; @@ -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]]; @@ -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); + } } /**