Skip to content

Instantly share code, notes, and snippets.

@ScottYates
Forked from marcojetson/progressBar.php
Last active May 16, 2018 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ScottYates/1e0a0185beff02197f2945a82c8847d4 to your computer and use it in GitHub Desktop.
Save ScottYates/1e0a0185beff02197f2945a82c8847d4 to your computer and use it in GitHub Desktop.
Simple and customisable command line progress bar in PHP
<?php
/**
* Create a progress bar
*
* @param int $total Max amount of items
* @param int $width Width in characters of the progress bar (defaults to 100)
* @param string $template Template to use,
* Available placeholders are %finished, %unfinished, %percent, %eta, %current and %total
* @return callable A function that renders the bar and takes the current value as only argument
*
* // usage examples
* $maxValue = 200;
* $pb = progress_bar($maxValue);
* for ($i = 0; $i <= $maxValue; $i++) {
* echo $pb($i);
* usleep(25000);
* }
* echo PHP_EOL;
* // colors and changes to template
* $custom = progress_bar(100, 50, "\033[42m%finished:' '\033[41m%unfinished\033[0m");
* for ($i = 0; $i <= 100; $i++) {
* echo $custom($i);
* usleep(25000);
* }
* echo PHP_EOL;
*/
function progress_bar($total = 100, $width = 100, $template = '[%finished>%unfinished] %percent % (%current of %total) - ETA: %eta') {
$symbols = array(
'finished' => '=',
'unfinished' => ' ',
'eta' => '?',
'current' => '#',
'total' => '#');
$template = preg_replace_callback(
'/%(' . implode('|', array_keys($symbols)) . '):(\'|")(.+?)\2/',
function ($match) use (&$symbols) {
$symbols[$match[1]] = $match[3];
return '%' . $match[1];
},
$template
);
$startTime = null;
$totalAmt = $total;
return function ($current) use ($template, $width, $totalAmt, $symbols, &$startTime) {
if ($startTime === null) {
$startTime = microtime(true);
$percent = $current;
$eta = $symbols['eta'];
} else {
$percent = max((int)(($current/$totalAmt) * 100),1);
$elapsed = microtime(true) - $startTime;
$eta = (int)((100 - $percent) * $elapsed / $percent);
}
$completed = max(round($percent * $width / 100),1);
$view = str_replace(array(
'%finished',
'%unfinished',
'%percent',
'%eta',
'%current',
'%total'),
array(
str_repeat($symbols['finished'], $completed),
str_repeat($symbols['unfinished'], $width - $completed),
$percent,
sprintf('%02dh %02dm %02ds', ($eta/3600),($eta/60%60), $eta%60),
$current,
$totalAmt),
$template
);
return "\033[" . strlen($view) . 'D' . $view;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment