Skip to content

Instantly share code, notes, and snippets.

@leite
Last active November 5, 2016 02:47
Show Gist options
  • Save leite/dc5b8ab7f3ef61fbb20c7670e668c6f4 to your computer and use it in GitHub Desktop.
Save leite/dc5b8ab7f3ef61fbb20c7670e668c6f4 to your computer and use it in GitHub Desktop.
gauge class
<?php
class Gauge {
static $_sizes = ['B','kB','MB','GB','TB','PB','EB','ZB','YB'];
static $_short = ['%dh%dm%ds', '%sm%ds', '%ds'];
static $_time = [
'%d second', '%d seconds', '%d minute, ', '%d minutes', '%d hour, ', '%d hours'
];
private $prev_time = 0;
private $start_time = 0;
private $prev_size = 0;
private $counter = 0;
private $crazy = 0;
function __construct () {
$this->start_time = $this->prev_time = microtime(true);
}
function size ($size, $precision = 1) {
for($i = 0; ($size / 1024) > 0.9; $i++, $size /= 1024) {}
return round($size, $precision) .' '. self::$_sizes[$i];
}
function estimation ($seconds, $short = true) {
$h = ($seconds > 3599 ? floor($seconds / 3600) : 0);
$m = ($seconds > 59 ? floor(($seconds / 60) % 60) : 0);
$s = $seconds % 60;
if ($short)
return $h > 0 ? sprintf(self::$_short[0], $h, $m, $s) : ($m > 0 ?
sprintf(self::$_short[1], $m, $s) : sprintf(self::$_short[2], $s));
return join(', ', [
($h == 0 ? '' : sprintf(self::$_time[($h > 1 ? 5 : 4)], $h)),
($m == 0 ? '' : sprintf(self::$_time[($m > 1 ? 3 : 2)], $m)),
($s == 0 ? '' : sprintf(self::$_time[($s > 1 ? 1 : 0)], $s))
]);
}
function progress ($resource, $download_size, $downloaded, $upload_size, $uploaded) {
$average_speed = $downloaded / (microtime(true) - $this->start_time);
$current_speed = ($downloaded - $this->prev_size) / (microtime(true) - $this->prev_time);
$this->prev_time = microtime(true);
$this->prev_size = $downloaded;
$this->crazy += $downloaded;
if ($download_size == 0) {
++$this->counter;
printf(
"\r %s, %s/s - remaining time unknow - %d, pt:%d, ps:%d, cs:%d, as:%d, down:%d, cz:%d %s",
$this->size($downloaded),
$this->size($current_speed),
$this->counter,
$this->prev_time,
$this->prev_size,
$current_speed,
$average_speed,
$downloaded,
$this->crazy,
str_repeat(' ', 50)
);
} else {
$time_remaining = ($downloaded - $download_size) / $average_speed;
if (($size = round($downloaded / $download_size) * 100) % 2 == 0)
printf(
"\r %s %s%s %s/s - %s remaining.",
$this->size($downloaded_size),
str_repeat('*', $size),
str_repeat('-', 100 - $size),
$this->size($current_speed),
$this->estimation($time_remaining)
);
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment