Skip to content

Instantly share code, notes, and snippets.

@taichunmin
Created June 4, 2014 18:24
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 taichunmin/420c557443c58ae454dd to your computer and use it in GitHub Desktop.
Save taichunmin/420c557443c58ae454dd to your computer and use it in GitHub Desktop.
<?php
class progress_bar
{
private $max = 1;
private $cnt = 0;
private $molecular = 0; // 分子
private $ng; // 下一個目標
private $clear_line = " \r";
private $write_func;
public $printFormat;
public static $_display = true; // 用來關閉輸出
public function __construct($max, $write_func, $f = 'Running: %d%%')
{
if($max<1)$max=1;
$this->max = $max;
$this->ng = $this->cnt = $this->molecular = 0;
$this->setf($f);
$this->write_func = $write_func;
$this->_nextGoalCompute();
}
private function _nextGoalCompute()
{
if( $this->cnt + 1 >= $this->max )
$this->ng = $this->max;
else $this->ng = floor($this->max*($this->molecular+1)/100.0);
}
public function c()
{
$this->cnt++;
if($this->cnt >= $this->ng)
{
$this->molecular = round( $this->cnt / $this->max * 100.0 );
$this->_nextGoalCompute();
$this->p();
}
return $this;
}
public function g()
{
return $this->molecular;
}
public function i()
{
return $this->cnt;
}
public function p($f=null)
{
if(isset($f))$this->setf($f);
if( !self::$_display || empty($this->printFormat) ) return;
call_user_func_array( $this->write_func, array(
sprintf($this->clear_line.$this->printFormat."\r",$this->molecular)
));
return $this;
}
public function cls()
{
call_user_func_array( $this->write_func, array(
sprintf($this->clear_line)
));
return $this;
}
public function setf($f)
{
$this->printFormat = ' '.str_replace(array("\n","\r"),'',$f);
return $this;
}
public function debug()
{
var_dump($this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment