From 6aa258385e3e571ea480b32e98d6840f8a2fdc04 Mon Sep 17 00:00:00 2001 From: Nikita Kiselev Date: Tue, 9 Dec 2025 21:13:12 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4=D1=8B=20Ima?= =?UTF-8?q?gesCacheClearCommand=20=D0=B4=D0=BB=D1=8F=20=D0=BE=D1=87=D0=B8?= =?UTF-8?q?=D1=81=D1=82=D0=BA=D0=B8=20=D0=BA=D0=B5=D1=88=D0=B0=20=D0=B8?= =?UTF-8?q?=D0=B7=D0=BE=D0=B1=D1=80=D0=B0=D0=B6=D0=B5=D0=BD=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Добавлена настройка paths.images_cache в configs/app.php для централизованного управления путем к кешу - Обновлен ImageFactory для использования пути кеша из конфигурации вместо жестко закодированного пути - Обновлен ImageToolServiceProvider для передачи пути кеша в ImageFactory - Реализована полная функциональность очистки кеша в ImagesCacheClearCommand с подсчетом статистики - Добавлен запрос подтверждения перед удалением файлов - Команда зарегистрирована в cli.php --- module/oc_telegram_shop/upload/cli.php | 6 +- .../upload/oc_telegram_shop/configs/app.php | 4 + .../Commands/ImagesCacheClearCommand.php | 156 ++++++++++++++++++ ...mmand.php => ImagesWarmupCacheCommand.php} | 2 +- .../framework/ImageTool/ImageFactory.php | 6 +- .../ImageTool/ImageToolServiceProvider.php | 5 +- 6 files changed, 174 insertions(+), 5 deletions(-) create mode 100644 module/oc_telegram_shop/upload/oc_telegram_shop/console/Commands/ImagesCacheClearCommand.php rename module/oc_telegram_shop/upload/oc_telegram_shop/console/Commands/{WarmupImagesCacheCommand.php => ImagesWarmupCacheCommand.php} (99%) diff --git a/module/oc_telegram_shop/upload/cli.php b/module/oc_telegram_shop/upload/cli.php index e7b3d55..86c6421 100755 --- a/module/oc_telegram_shop/upload/cli.php +++ b/module/oc_telegram_shop/upload/cli.php @@ -6,7 +6,8 @@ use Console\Commands\PulseSendEventsCommand; use Console\Commands\ScheduleListCommand; use Console\Commands\ScheduleRunCommand; use Console\Commands\VersionCommand; -use Console\Commands\WarmupImagesCacheCommand; +use Console\Commands\ImagesWarmupCacheCommand; +use Console\Commands\ImagesCacheClearCommand; use Monolog\Handler\RotatingFileHandler; use Monolog\Logger; use Openguru\OpenCartFramework\QueryBuilder\Connections\MySqlConnection; @@ -95,5 +96,6 @@ $console->add($app->get(VersionCommand::class)); $console->add($app->get(ScheduleRunCommand::class)); $console->add($app->get(ScheduleListCommand::class)); $console->add($app->get(PulseSendEventsCommand::class)); -$console->add($app->get(WarmupImagesCacheCommand::class)); +$console->add($app->get(ImagesWarmupCacheCommand::class)); +$console->add($app->get(ImagesCacheClearCommand::class)); $console->run(); diff --git a/module/oc_telegram_shop/upload/oc_telegram_shop/configs/app.php b/module/oc_telegram_shop/upload/oc_telegram_shop/configs/app.php index dcc126d..82f9c5d 100755 --- a/module/oc_telegram_shop/upload/oc_telegram_shop/configs/app.php +++ b/module/oc_telegram_shop/upload/oc_telegram_shop/configs/app.php @@ -93,4 +93,8 @@ TEXT, 'db_table' => 'telecart_cache_items', ], ], + + 'paths' => [ + 'images_cache' => 'cache/telecart', + ], ]; diff --git a/module/oc_telegram_shop/upload/oc_telegram_shop/console/Commands/ImagesCacheClearCommand.php b/module/oc_telegram_shop/upload/oc_telegram_shop/console/Commands/ImagesCacheClearCommand.php new file mode 100644 index 0000000..7746d4a --- /dev/null +++ b/module/oc_telegram_shop/upload/oc_telegram_shop/console/Commands/ImagesCacheClearCommand.php @@ -0,0 +1,156 @@ +container = $container; + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + + $io->title('Очистка кеша изображений товаров'); + + // Получаем пути из конфига + $imagesDir = $this->container->getConfigValue('paths.images'); + $cachePath = $this->container->getConfigValue('paths.images_cache', 'cache/telecart'); + $cachePath = ltrim($cachePath, '/'); + $fullCachePath = rtrim($imagesDir, '/') . '/' . $cachePath; + + if (!is_dir($fullCachePath)) { + $io->warning("Директория кеша не существует: {$fullCachePath}"); + return Command::SUCCESS; + } + + $io->section('Информация'); + $io->listing([ + "Директория изображений: {$imagesDir}", + "Путь кеша: {$cachePath}", + "Полный путь кеша: {$fullCachePath}", + ]); + + // Подсчитываем файлы перед удалением + $fileCount = 0; + $totalSize = 0; + $iterator = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($fullCachePath, RecursiveDirectoryIterator::SKIP_DOTS), + RecursiveIteratorIterator::CHILD_FIRST + ); + + foreach ($iterator as $file) { + if ($file->isFile()) { + $fileCount++; + $totalSize += $file->getSize(); + } + } + + if ($fileCount === 0) { + $io->info('Кеш пуст, нечего очищать.'); + return Command::SUCCESS; + } + + $io->section('Статистика перед очисткой'); + $io->listing([ + "Файлов: {$fileCount}", + "Размер: " . $this->formatBytes($totalSize), + ]); + + // Запрашиваем подтверждение + if (!$io->confirm('Вы уверены, что хотите удалить все файлы из кеша?', false)) { + $io->info('Очистка кеша отменена.'); + return Command::SUCCESS; + } + + // Удаляем файлы и директории + $deletedFiles = 0; + $deletedDirs = 0; + $errors = 0; + + $progressBar = $io->createProgressBar($fileCount); + $progressBar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %message%'); + $progressBar->setMessage('Удаление файлов...'); + $progressBar->start(); + + $iterator = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($fullCachePath, RecursiveDirectoryIterator::SKIP_DOTS), + RecursiveIteratorIterator::CHILD_FIRST + ); + + foreach ($iterator as $file) { + try { + if ($file->isFile()) { + if (@unlink($file->getPathname())) { + $deletedFiles++; + } else { + $errors++; + } + $progressBar->advance(); + } elseif ($file->isDir()) { + if (@rmdir($file->getPathname())) { + $deletedDirs++; + } + } + } catch (\Exception $e) { + $errors++; + } + } + + // Удаляем саму директорию кеша, если она пуста + if (is_dir($fullCachePath)) { + @rmdir($fullCachePath); + } + + $progressBar->setMessage('Завершено'); + $progressBar->finish(); + $io->newLine(2); + + // Выводим статистику + $io->section('Результаты'); + $io->table( + ['Метрика', 'Значение'], + [ + ['Удалено файлов', $deletedFiles], + ['Удалено директорий', $deletedDirs], + ['Ошибок', $errors], + ] + ); + + if ($errors > 0) { + $io->warning("Обнаружено {$errors} ошибок при удалении файлов."); + } else { + $io->success('Кеш изображений успешно очищен!'); + } + + return Command::SUCCESS; + } + + private function formatBytes(int $bytes, int $precision = 2): string + { + $units = ['B', 'KB', 'MB', 'GB', 'TB']; + + for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) { + $bytes /= 1024; + } + + return round($bytes, $precision) . ' ' . $units[$i]; + } +} + diff --git a/module/oc_telegram_shop/upload/oc_telegram_shop/console/Commands/WarmupImagesCacheCommand.php b/module/oc_telegram_shop/upload/oc_telegram_shop/console/Commands/ImagesWarmupCacheCommand.php similarity index 99% rename from module/oc_telegram_shop/upload/oc_telegram_shop/console/Commands/WarmupImagesCacheCommand.php rename to module/oc_telegram_shop/upload/oc_telegram_shop/console/Commands/ImagesWarmupCacheCommand.php index 30655fa..86828d3 100644 --- a/module/oc_telegram_shop/upload/oc_telegram_shop/console/Commands/WarmupImagesCacheCommand.php +++ b/module/oc_telegram_shop/upload/oc_telegram_shop/console/Commands/ImagesWarmupCacheCommand.php @@ -16,7 +16,7 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; -class WarmupImagesCacheCommand extends TeleCartCommand +class ImagesWarmupCacheCommand extends TeleCartCommand { protected static $defaultName = 'images:warmup'; protected static $defaultDescription = 'Прогрев кеша изображений товаров'; diff --git a/module/oc_telegram_shop/upload/oc_telegram_shop/framework/ImageTool/ImageFactory.php b/module/oc_telegram_shop/upload/oc_telegram_shop/framework/ImageTool/ImageFactory.php index fece8be..34c9bec 100755 --- a/module/oc_telegram_shop/upload/oc_telegram_shop/framework/ImageTool/ImageFactory.php +++ b/module/oc_telegram_shop/upload/oc_telegram_shop/framework/ImageTool/ImageFactory.php @@ -31,6 +31,7 @@ class ImageFactory 'format' => 'webp', 'quality' => 90, 'no_image_path' => 'no_image.png', + 'cache_path' => 'cache/telecart', ]; public function __construct(string $imageDir, string $siteUrl, string $driver, array $options = []) @@ -179,7 +180,10 @@ class ImageFactory $filename .= '_' . substr(hash('SHA256', json_encode($this->modifications)), 0, 12); } - return $this->imageDir . '/cache/telecart/' . $imagePath . $filename . '.' . $format; + $cachePath = $this->options['cache_path'] ?? 'cache/telecart'; + $cachePath = ltrim($cachePath, '/'); + + return $this->imageDir . '/' . $cachePath . '/' . $imagePath . $filename . '.' . $format; } private function applyModifications(): void diff --git a/module/oc_telegram_shop/upload/oc_telegram_shop/framework/ImageTool/ImageToolServiceProvider.php b/module/oc_telegram_shop/upload/oc_telegram_shop/framework/ImageTool/ImageToolServiceProvider.php index 90fe370..057d1d4 100755 --- a/module/oc_telegram_shop/upload/oc_telegram_shop/framework/ImageTool/ImageToolServiceProvider.php +++ b/module/oc_telegram_shop/upload/oc_telegram_shop/framework/ImageTool/ImageToolServiceProvider.php @@ -15,7 +15,10 @@ class ImageToolServiceProvider extends ServiceProvider return new ImageFactory( $container->getConfigValue('paths.images'), $container->getConfigValue('app.shop_base_url'), - $driver + $driver, + [ + 'cache_path' => $container->getConfigValue('paths.images_cache', 'cache/telecart'), + ] ); }); }