From 5178cee6924eda4c87b9968501dca11dfece9156 Mon Sep 17 00:00:00 2001 From: Martin Zurowietz Date: Mon, 19 Feb 2024 16:23:24 +0100 Subject: [PATCH] Make prune methos more robust against runtime exceptions --- src/FileCache.php | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/FileCache.php b/src/FileCache.php index 4fc1e18..47d08a5 100644 --- a/src/FileCache.php +++ b/src/FileCache.php @@ -10,6 +10,7 @@ use GuzzleHttp\ClientInterface; use Illuminate\Filesystem\Filesystem; use Illuminate\Filesystem\FilesystemManager; +use RuntimeException; use SplFileInfo; use Symfony\Component\Finder\Finder; @@ -220,17 +221,38 @@ public function prune() $files = Finder::create() ->files() ->ignoreDotFiles(true) - // This will return the least recently accessed files first. - ->sortByAccessedTime() ->in($this->config['path']) ->getIterator(); - while ($totalSize > $allowedSize && ($file = $files->current())) { + $files = iterator_to_array($files); + // This will return the least recently accessed files first. + // We use a custom sorting function which ignores errors (because files may + // have been deleted in the meantime). + uasort($files, function (SplFileInfo $a, SplFileInfo $b) { + try { + $aTime = $a->getATime(); + } catch (RuntimeException $e) { + return 1; + } + + try { + $bTime = $b->getATime(); + } catch (RuntimeException $e) { + return -1; + } + + return $aTime - $bTime; + }); + + foreach ($files as $file) { + if ($totalSize <= $allowedSize) { + break; + } + $fileSize = $file->getSize(); if ($this->delete($file)) { $totalSize -= $fileSize; } - $files->next(); } } }