openvk/CLI/RebuildImagesCommand.php

86 lines
2.7 KiB
PHP
Raw Permalink Normal View History

2022-04-05 15:54:53 +03:00
<?php declare(strict_types=1);
namespace openvk\CLI;
use Chandler\Database\DatabaseConnection;
use openvk\Web\Models\Repositories\Photos;
2022-04-05 15:54:53 +03:00
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
2022-04-06 23:59:31 +03:00
use Nette\Utils\ImageException;
2022-04-05 15:54:53 +03:00
class RebuildImagesCommand extends Command
{
private $images;
protected static $defaultName = "build-images";
function __construct()
{
$this->images = DatabaseConnection::i()->getContext()->table("photos");
parent::__construct();
}
protected function configure(): void
{
$this->setDescription("Create resized versions of images")
->setHelp("This command allows you to resize all your images after configuration change")
->addOption("upgrade-only", "U", InputOption::VALUE_NEGATABLE, "Only upgrade images which aren't resized?");
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$header = $output->section();
$counter = $output->section();
$header->writeln([
"Image Rebuild Utility",
"=====================",
"",
]);
$filter = ["deleted" => false];
if($input->getOption("upgrade-only"))
$filter["sizes"] = NULL;
$selection = $this->images->select("id")->where($filter);
$totalPics = $selection->count();
2022-04-05 15:54:53 +03:00
$header->writeln([
"Total of $totalPics images found.",
2022-04-05 15:54:53 +03:00
"",
]);
2022-04-06 23:59:31 +03:00
$errors = 0;
$count = 0;
$avgTime = NULL;
$begin = new \DateTimeImmutable("now");
foreach($selection as $idHolder) {
$start = microtime(true);
2022-04-06 23:59:31 +03:00
try {
$photo = (new Photos)->get($idHolder->id);
$photo->getSizes(true, true);
$photo->getDimensions();
} catch(ImageException $ex) {
$errors++;
}
2022-04-05 15:54:53 +03:00
$timeConsumed = microtime(true) - $start;
if(!$avgTime)
$avgTime = $timeConsumed;
else
$avgTime = ($avgTime + $timeConsumed) / 2;
$eta = $begin->getTimestamp() + ceil($totalPics * $avgTime);
$int = (new \DateTimeImmutable("now"))->diff(new \DateTimeImmutable("@$eta"));
$int = $int->d . "d" . $int->h . "h" . $int->i . "m" . $int->s . "s";
$pct = floor(100 * ($count / $totalPics));
2022-04-06 23:59:31 +03:00
$counter->overwrite("Processed " . ++$count . " images... ($pct% $int left $errors/$count fail)");
2022-04-05 15:54:53 +03:00
}
$counter->overwrite("Processing finished :3");
return Command::SUCCESS;
}
}