protected function cleanDirectory($directory, $maxAge = null, $keepMax = 5, array $blacklist = [], $quiet = true)
{
if (!is_dir($directory)) {
return [0, 0];
}
$files = glob($directory . '/*');
if (!$files) {
return [0, 0];
}
// Sort files by modified time (descending).
usort($files, function ($a, $b) {
return filemtime($a) < filemtime($b);
});
$now = time();
$numDeleted = 0;
$numKept = 0;
foreach ($files as $filename) {
if (in_array($filename, $blacklist)) {
$numKept++;
continue;
}
if ($keepMax !== null && $numKept >= $keepMax || $maxAge !== null && $now - filemtime($filename) > $maxAge) {
if (!$quiet) {
$this->output->writeln("Deleting: " . basename($filename));
}
if ($this->fsHelper->remove($filename)) {
$numDeleted++;
} elseif (!$quiet) {
$this->output->writeln("Failed to delete: <error>" . basename($filename) . "</error>");
}
} else {
$numKept++;
}
}
return [$numDeleted, $numKept];
}