Skip to content

Commit

Permalink
Make prune methos more robust against runtime exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
mzur committed Feb 19, 2024
1 parent 02bef6d commit 5178cee
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions src/FileCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use GuzzleHttp\ClientInterface;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Filesystem\FilesystemManager;
use RuntimeException;
use SplFileInfo;
use Symfony\Component\Finder\Finder;

Expand Down Expand Up @@ -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();
}
}
}
Expand Down

0 comments on commit 5178cee

Please sign in to comment.