Files
thetool/lib/ProgressLogger/ProgressLogger.php
2025-05-27 14:04:36 +02:00

64 lines
2.1 KiB
PHP

<?php
class ProgressLogger {
private $totalItems;
private $startTime;
private $processedCount;
private $lastOutputTime;
private $outputInterval; // in seconds
public function __construct($totalItems, $outputInterval = 1) {
$this->totalItems = $totalItems;
$this->processedCount = 0;
$this->startTime = microtime(true);
$this->lastOutputTime = 0;
$this->outputInterval = $outputInterval;
}
public function incrementAndLog() {
$this->processedCount++;
$currentTime = microtime(true);
// Only update the console if enough time has passed or it's the last item
if (($currentTime - $this->lastOutputTime > $this->outputInterval) || ($this->processedCount === $this->totalItems)) {
$this->logProgress();
$this->lastOutputTime = $currentTime;
}
}
private function logProgress() {
$elapsedTime = microtime(true) - $this->startTime;
$itemsPerSecond = ($this->processedCount > 0) ? ($this->processedCount / $elapsedTime) : 0;
$remainingItems = $this->totalItems - $this->processedCount;
$estimatedTimeRemaining = ($itemsPerSecond > 0) ? ($remainingItems / $itemsPerSecond) : 0;
$hours = floor($estimatedTimeRemaining / 3600);
$minutes = floor(($estimatedTimeRemaining % 3600) / 60);
$seconds = floor($estimatedTimeRemaining % 60);
printf("\rProcessing: %d/%d (%.2f%%) | Elapsed: %s | Remaining: %02d:%02d:%02d",
$this->processedCount,
$this->totalItems,
($this->processedCount / $this->totalItems) * 100,
gmdate("H:i:s", $elapsedTime),
$hours,
$minutes,
$seconds
);
// If all items are processed, add a newline
if ($this->processedCount === $this->totalItems) {
echo "\n";
}
}
public function startMessage() {
echo "Starting update for {$this->totalItems} items...\n";
}
public function finishMessage($type = 'items') {
echo "Finished! Updated {$this->processedCount} $type.\n";
}
}
?>