aboutsummaryrefslogtreecommitdiff
path: root/lib/task/mySfTask.class.php
blob: 15d45023f776b68a6f77f6452a1a71376a80c435 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
/**
 * See http://pastebin.com/SarJ5mjP
 *     http://www.mail-archive.com/symfony-users@googlegroups.com/msg27122.html
 */
abstract class mySfTask extends sfBaseTask
{
  private
    $counter = 1,
    $indicators = array('-', '\\', '|', '/');
  
  /**
   * Output a progress bar
   *
   * @param integer $current The current iteration, must always be 0 on first call
   * @param integer $total Total number of iterations this progressbar will handle
   * @param integer $size Width of the progress bar in characters
   **/
  public function progressBar($current=0, $total=100, $size=NULL)
  {
    if(is_null($size))
    {
      $size = (int) `tput cols`;
    }
    
    // Don't do anything if this isn't a commandline task or verbosity is off
    if (is_null($this->commandApplication) || !$this->commandApplication->isVerbose())
    {
      return;
    }
    
    $perc = ($current/$total)*100;

    // Show activity by cycling through the array of indicators on each iteration
    $this->counter += $this->counter === count($this->indicators) ? -3 : 1;
    $indicator = $this->indicators[$this->counter - 1];

    // if it's not first iteration, remove the previous bar by outputting a
    // backspace characters
    if($current > 0) echo str_repeat("\x08", $size);

    // generate progess bar
    $progress = floor($current / $total * ($size - 11));
    $soFar      = str_repeat('=', $progress);
    $remaining  = str_repeat(' ', $size - 11 - $progress);

    // prefix the bar with a (padded) percent progress and activity indicator
    // and wrap it in square brackets, with a greater-than as the current
    // position indicator
    printf(" %s %3u%% [%s>%s]",$indicator,$perc,$soFar,$remaining);
    
    // if it's the end, add a new line
    if($current == $total)
    {
      echo "\n";
    }
  }
}