92 lines
2.3 KiB
PHP
Executable File
92 lines
2.3 KiB
PHP
Executable File
<?php
|
|
|
|
namespace Meoran\Images\Console\Commands;
|
|
|
|
use FilesystemIterator;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Filesystem\Filesystem;
|
|
use Meoran\Images\Model\Image;
|
|
|
|
class RemoveUselessPicturesCommand extends Command
|
|
{
|
|
/**
|
|
* The name and signature of the console command.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'images:remove';
|
|
/**
|
|
* The console command description.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $description = 'Remove useless pictures.';
|
|
|
|
/**
|
|
* RemoveUselessPicturesCommand constructor.
|
|
*/
|
|
public function __construct()
|
|
{
|
|
parent::__construct();
|
|
}
|
|
|
|
/**
|
|
* Execute the console command.
|
|
*
|
|
* @return mixed
|
|
*/
|
|
public function handle()
|
|
{
|
|
$this->removeNonExistentPictures();
|
|
// $this->removeNotUsedPictures();
|
|
}
|
|
|
|
private function removeNonExistentPictures()
|
|
{
|
|
$base = config('image.path');
|
|
if (empty($base)) {
|
|
throw new \Exception("Config image.path must be defined");
|
|
}
|
|
|
|
$fs = new Filesystem();
|
|
$files = collect($fs->allFiles($base));
|
|
$filenames = $files->filter(function ($el) {
|
|
$mime = mime_content_type($el->getPathName());
|
|
if (strpos($mime, 'image/') === false) {
|
|
return false;
|
|
}
|
|
return true;
|
|
})->map(function ($el) {
|
|
return $el->getFilename();
|
|
});
|
|
|
|
/**
|
|
* Suppression des images qui n'existent pas physiquement
|
|
*/
|
|
$linesToDelete = Image::whereNotIn('filename', $filenames)->get();
|
|
$delete = 0;
|
|
foreach ($linesToDelete as $lineToDelete) {
|
|
$lineToDelete->delete();
|
|
$delete++;
|
|
}
|
|
$this->info("Images supprimées en base : " . $delete);
|
|
|
|
/**
|
|
* Suppression des images qui ne sont pas en base
|
|
*/
|
|
$pictures = Image::select('filename')->getQuery()->get()->transform(function ($item) {
|
|
return $item->filename;
|
|
})->all();
|
|
$delete = 0;
|
|
foreach ($files as $file) {
|
|
if (!in_array($file, $pictures)) {
|
|
unlink($base . $file);
|
|
$delete++;
|
|
}
|
|
}
|
|
$this->info("Images supprimées physiquement : " . $delete);
|
|
|
|
}
|
|
|
|
}
|