Skip to content

Instantly share code, notes, and snippets.

@tassoevan
Created March 26, 2014 17:11
Show Gist options
  • Save tassoevan/9788324 to your computer and use it in GitHub Desktop.
Save tassoevan/9788324 to your computer and use it in GitHub Desktop.
Show console progress bar
<?php
function progress($current, $total = null, $extra = null)
{
static $width = null;
static $startTime = null;
if ( $width === null ) {
if ( strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' )
$width = 80;
else
$width = intval(`tput cols`);
}
if ( $current == 'create' ) {
$startTime = microtime(true);
echo "\x1b[?25l\x1b[0K";
}
elseif ( $current == 'destroy' ) {
$startTime = null;
echo "\x1b[?25h\x1b[0K";
}
else {
if ( empty($total) ) {
$remain = $current % $width;
echo str_repeat($empty, $remain) . $filled . str_repeat($empty, $width - $remain - 1);
}
else {
$deltaTime = microtime(true) - $startTime;
$rate = $deltaTime > 0 ? $current / $deltaTime : PHP_INT_MAX;
$remain = ($total - $current) / $rate;
$quocient = $current / $total;
$progress = intval($quocient * $width);
if ( empty($extra) )
$extra = '';
$extra = ' ' . $extra;
$string = $current . ' / ' . $total . ' (restam ' . interval($remain) . ') ';
$string = str_pad($extra, $width - strlen($string), ' ', STR_PAD_RIGHT) . $string;
echo "\x1b[1;37;46m",
mb_substr($string, 0, $progress),
"\x1b[40m",
mb_substr($string, $progress),
"\x1b[0m",
str_repeat("\x8", $width);
}
echo str_repeat("\010", $width);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment