Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 47 additions & 7 deletions src/View/ProgressBarView.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,21 @@
use function floor;
use function max;
use function str_repeat;
use function vsprintf;

class ProgressBarView extends View implements ProgressBar
{
protected int $current = 0;

protected int $barWidth = 28;
protected int $width = 28;

protected int $total = 100;

/**
* Creates a progress bar with the specified total number of steps.
*
* @param int $total The total number of steps.
*
* @return $this
*/
public function create(int $total): static
Expand Down Expand Up @@ -62,15 +64,53 @@ public function finish(): void
*/
protected function display(): void
{
$percent = $this->current / $this->total;
$filled = (int) floor($percent * $this->barWidth);
$empty = $this->barWidth - $filled;
$percText = (int) floor($percent * 100);
$percent = $this->percent();

$bar = str_repeat('▓', $filled) . str_repeat('░', $empty);
$filled = $this->filledText($percent);
$empty = $this->emptyText($filled);

$line = " {$this->current}/{$this->total} [{$bar}] {$percText}%";
$line = $this->buildLine($filled, $empty, $percent);

$this->write("\r" . $line);
}

protected function buildLine(int $filled, int $empty, float $percent): string
{
return vsprintf(' %s/%s [%s] %s%%', [
$this->numberFormat($this->current),
$this->numberFormat($this->total),
$this->buildBar($filled, $empty),
$this->percentText($percent),
]);
}

protected function buildBar(int $filled, int $empty): string
{
return str_repeat('▓', $filled) . str_repeat('░', $empty);
}

protected function percent(): float
{
return $this->current / $this->total;
}

protected function filledText(float $percent): int
{
return (int) floor($percent * $this->width);
}

protected function emptyText(int $filled): int
{
return $this->width - $filled;
}

protected function percentText(float $percent): int
{
return (int) floor($percent * 100);
}

protected function numberFormat(int $number): string
{
return number_format($number, thousands_separator: "'");
}
}
Loading