Skip to content

Commit

Permalink
Add precision to progress bar
Browse files Browse the repository at this point in the history
  • Loading branch information
quasipickle authored and duncan3dc committed Oct 30, 2024
1 parent 9e8a8b1 commit 70a0e1b
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
27 changes: 25 additions & 2 deletions src/TerminalObject/Dynamic/Progress.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ class Progress extends DynamicTerminalObject
*/
protected $current_percentage = '';

/**
* The number of decimal points to display
*
* @var integer $precision
*/
protected $precision = 0;

/**
* The string length of the bar when at 100%
*
Expand Down Expand Up @@ -88,6 +95,20 @@ public function total($total)
return $this;
}

/**
* Set the completed percentage precision
*
* @param integer $precision The number of decimal places to display
*
* @return Progress
*/
public function precision($precision)
{
$this->precision = $precision;

return $this;
}

/**
* Determines the current percentage we are at and re-writes the progress bar
*
Expand Down Expand Up @@ -281,12 +302,14 @@ protected function getBarStrLen()
/**
* Format the percentage so it looks pretty
*
* @param integer $percentage
* @param integer $percentage The percentage (0-1) to format
*
* @return float
*/
protected function percentageFormatted($percentage)
{
return round($percentage * 100) . '%';
$factor = pow(10, $this->precision);
return round($percentage * 100 * $factor) / $factor . '%';
}

/**
Expand Down
26 changes: 26 additions & 0 deletions tests/ProgressTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,32 @@ public function it_can_output_a_progress_bar_via_constructor()
}
}

/**
* @test
* @doesNotPerformAssertions
*/
public function it_can_output_a_progress_bar_with_precision()
{
$this->shouldWrite('');
$this->shouldWrite("\e[m\e[1A\r\e[K{$this->repeat(0)} 0.008%\e[0m");
$progress = $this->cli->progress(100000);
$progress->precision(3);
$progress->current(8);
}

/**
* @test
* @doesNotPerformAssertions
*/
public function it_can_output_a_progress_bar_with_precision_rounded()
{
$this->shouldWrite('');
$this->shouldWrite("\e[m\e[1A\r\e[K{$this->repeat(0)} 0.01%\e[0m");
$progress = $this->cli->progress(100000);
$progress->precision(2);
$progress->current(8);
}

/**
* @test
* @doesNotPerformAssertions
Expand Down

0 comments on commit 70a0e1b

Please sign in to comment.