Simplification
This commit is contained in:
56
scripts/clean-orphan-media.php
Normal file
56
scripts/clean-orphan-media.php
Normal file
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
$f3 = require __DIR__ . '/bootstrap.php';
|
||||
Media::bootstrap($f3->get('DB'));
|
||||
|
||||
$mode = strtolower(trim((string) ($argv[1] ?? 'list')));
|
||||
if (!in_array($mode, ['list', 'delete'], true)) {
|
||||
fwrite(STDERR, "Usage: php scripts/clean-orphan-media.php [list|delete]\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$directory = rtrim((string) $f3->get('paths.media_dir'), '/\\');
|
||||
$knownFiles = [];
|
||||
foreach ((new Media())->find(null) ?: [] as $row) {
|
||||
$knownFiles[(string) $row->file_name] = true;
|
||||
}
|
||||
|
||||
$orphans = [];
|
||||
if (is_dir($directory)) {
|
||||
foreach (glob($directory . DIRECTORY_SEPARATOR . '*') ?: [] as $path) {
|
||||
if (!is_file($path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = basename($path);
|
||||
if (!isset($knownFiles[$name])) {
|
||||
$orphans[] = $path;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort($orphans, SORT_NATURAL);
|
||||
|
||||
if ($mode === 'list') {
|
||||
if ($orphans === []) {
|
||||
fwrite(STDOUT, "Aucun fichier orphelin.\n");
|
||||
exit(0);
|
||||
}
|
||||
|
||||
fwrite(STDOUT, "Fichiers orphelins:\n");
|
||||
foreach ($orphans as $path) {
|
||||
fwrite(STDOUT, '- ' . basename($path) . PHP_EOL);
|
||||
}
|
||||
exit(0);
|
||||
}
|
||||
|
||||
$deleted = 0;
|
||||
foreach ($orphans as $path) {
|
||||
if (@unlink($path)) {
|
||||
$deleted++;
|
||||
}
|
||||
}
|
||||
|
||||
fwrite(STDOUT, "Fichiers orphelins supprimés : {$deleted}\n");
|
||||
Reference in New Issue
Block a user