You've already forked Epicnabbo-Catalogus-Updated-Daily
98 lines
2.8 KiB
PHP
98 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\WebsiteAd;
|
|
use App\Services\SettingsService;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Collection;
|
|
|
|
class ImportAdsData extends Command
|
|
{
|
|
protected $signature = 'import:ads-data';
|
|
|
|
protected $description = 'Import ads data from the filesystem';
|
|
|
|
private const int CHUNK_SIZE = 100;
|
|
|
|
private const array ALLOWED_EXTENSIONS = ['jpeg', 'jpg', 'png', 'gif'];
|
|
|
|
public function handle(SettingsService $settingsService): void
|
|
{
|
|
$adsPath = $settingsService->getOrDefault('ads_path_filesystem');
|
|
|
|
if (! $this->validatePath($adsPath)) {
|
|
return;
|
|
}
|
|
|
|
$files = $this->getImageFiles($adsPath);
|
|
|
|
if ($files === []) {
|
|
$this->warn('No valid image files found in the ads directory.');
|
|
|
|
return;
|
|
}
|
|
|
|
$this->processFiles($files);
|
|
|
|
$this->info('Ads data import completed successfully.');
|
|
}
|
|
|
|
private function validatePath(?string $adsPath): bool
|
|
{
|
|
if (in_array($adsPath, [null, '', '0'], true)) {
|
|
$this->error('Ads path is not configured in website_settings.');
|
|
|
|
return false;
|
|
}
|
|
|
|
if (! is_dir($adsPath)) {
|
|
$this->error("The ads path '{$adsPath}' does not exist in the filesystem.");
|
|
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
private function getImageFiles(string $adsPath): array
|
|
{
|
|
$files = scandir($adsPath);
|
|
if (! is_array($files)) {
|
|
return [];
|
|
}
|
|
|
|
$filtered = array_filter($files, function (string $file) use ($adsPath): bool {
|
|
$filePath = $adsPath . DIRECTORY_SEPARATOR . $file;
|
|
$ext = pathinfo($file, PATHINFO_EXTENSION);
|
|
$ext = strtolower((string) $ext);
|
|
return is_file($filePath) && in_array($ext, self::ALLOWED_EXTENSIONS, true);
|
|
});
|
|
|
|
return array_values(array_map(fn ($f): string => (string) $f, $filtered));
|
|
}
|
|
|
|
private function processFiles(array $files): void
|
|
{
|
|
// Get existing images to avoid duplicates
|
|
$existingImages = WebsiteAd::pluck('image')->toArray();
|
|
|
|
$newFiles = Collection::make($files)
|
|
->filter(fn ($file): bool => is_string($file) && ! in_array($file, $existingImages, true))
|
|
->map(fn (string $file): array => ['image' => $file])
|
|
->values();
|
|
|
|
$skippedCount = count($files) - $newFiles->count();
|
|
if ($skippedCount > 0) {
|
|
$this->warn("Skipped {$skippedCount} existing files.");
|
|
}
|
|
|
|
$newFiles->chunk(self::CHUNK_SIZE)->each(
|
|
function (Collection $chunk): void {
|
|
WebsiteAd::insert($chunk->toArray());
|
|
$this->info('Processed ' . $chunk->count() . ' files.');
|
|
},
|
|
);
|
|
}
|
|
}
|