Completed
Pull Request — master (#112)
by Daniel
19:27 queued 17:52
created

Progress::each()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 4
nop 2
crap 3
1
<?php
2
3
namespace League\CLImate\TerminalObject\Dynamic;
4
5
class Progress extends DynamicTerminalObject
6
{
7
    /**
8
     * The total number of items involved
9
     *
10
     * @var integer $total
11
     */
12
    protected $total = 0;
13
14
    /**
15
     * The current item that the progress bar represents
16
     *
17
     * @var integer $current
18
     */
19
    protected $current = 0;
20
21
    /**
22
     * The current percentage displayed
23
     *
24
     * @var string $current_percentage
25
     */
26
    protected $current_percentage = '';
27
28
    /**
29
     * The string length of the bar when at 100%
30
     *
31
     * @var integer $bar_str_len
32
     */
33
    protected $bar_str_len;
34
35
    /**
36
     * Flag indicating whether we are writing the bar for the first time
37
     *
38
     * @var boolean $first_line
39
     */
40
    protected $first_line = true;
41
42
    /**
43
     * Current status bar label
44
     *
45
     * @var string $label
46
     */
47
    protected $label;
48
49
    /**
50
     * Force a redraw every time
51
     *
52
     * @var boolean $force_redraw
53
     */
54
    protected $force_redraw = false;
55
56
    /**
57
     * If they pass in a total, set the total
58
     *
59
     * @param integer $total
60
     */
61 48
    public function __construct($total = null)
62
    {
63 48
        if ($total !== null) {
64 20
            $this->total($total);
65 5
        }
66 48
    }
67
68
    /**
69
     * Set the total property
70
     *
71
     * @param  integer $total
72
     *
73
     * @return Progress
74
     */
75 44
    public function total($total)
76
    {
77 44
        $this->total = $total;
78
79 44
        return $this;
80
    }
81
82
    /**
83
     * Determines the current percentage we are at and re-writes the progress bar
84
     *
85
     * @param integer $current
86
     * @param mixed   $label
87
     * @throws \Exception
88
     */
89 48
    public function current($current, $label = null)
90
    {
91 48
        if ($this->total == 0) {
92
            // Avoid dividing by 0
93 4
            throw new \Exception('The progress total must be greater than zero.');
94
        }
95
96 44
        if ($current > $this->total) {
97 4
            throw new \Exception('The current is greater than the total.');
98
        }
99
100 40
        $this->drawProgressBar($current, $label);
101
102 40
        $this->current = $current;
103 40
        $this->label   = $label;
104 40
    }
105
106
    /**
107
     * Increments the current position we are at and re-writes the progress bar
108
     *
109
     * @param integer $increment The number of items to increment by
110
     * @param string $label
111
     */
112 12
    public function advance($increment = 1, $label = null)
113
    {
114 12
        $this->current($this->current + $increment, $label);
115 12
    }
116
117
    /**
118
     * Force the progress bar to redraw every time regardless of whether it has changed or not
119
     *
120
     * @param boolean $force
121
     * @return Progress
122
     */
123 8
    public function forceRedraw($force = true)
124
    {
125 8
        $this->force_redraw = !!$force;
126
127 8
        return $this;
128
    }
129
130
    /**
131
     * Loop through the data and self manage the progress bar advancement
132
     *
133
     * @param mixed $data Array or any other iterable object
134
     * @param callable $callback
135
     */
136 4
    public function each($data, callable $callback)
137
    {
138 4
        if (!$this->total) {
139 4
            $this->total(count($data));
140 1
        }
141
142 4
        foreach ($data as $item) {
143 4
            $callback($item);
144 4
            $this->advance();
145 1
        }
146 4
    }
147
148
    /**
149
     * Draw the progress bar, if necessary
150
     *
151
     * @param string $current
152
     * @param string $label
153
     */
154 40
    protected function drawProgressBar($current, $label)
155
    {
156 40
        $percentage = $this->percentageFormatted($current / $this->total);
157
158 40
        if ($this->shouldRedraw($percentage, $label)) {
159 40
            $progress_bar = $this->getProgressBar($current, $label);
160 40
            $this->output->write($this->parser->apply($progress_bar));
161 10
        }
162
163 40
        $this->current_percentage = $percentage;
164 40
    }
165
166
    /**
167
     * Build the progress bar str and return it
168
     *
169
     * @param integer $current
170
     * @param string $label
171
     *
172
     * @return string
173
     */
174 40
    protected function getProgressBar($current, $label)
175
    {
176 40
        if ($this->first_line) {
177
            // Drop down a line, we are about to
178
            // re-write this line for the progress bar
179 40
            $this->output->write('');
180 40
            $this->first_line = false;
181 10
        }
182
183
        // Move the cursor up one line and clear it to the end
184 40
        $line_count    = (strlen($label) > 0) ? 2 : 1;
185
186 40
        $progress_bar  = $this->util->cursor->up($line_count);
187 40
        $progress_bar .= $this->util->cursor->startOfCurrentLine();
188 40
        $progress_bar .= $this->util->cursor->deleteCurrentLine();
189 40
        $progress_bar .= $this->getProgressBarStr($current, $label);
190
191 40
        return $progress_bar;
192
    }
193
194
    /**
195
     * Get the progress bar string, basically:
196
     * =============>             50% label
197
     *
198
     * @param integer $current
199
     * @param string $label
200
     *
201
     * @return string
202
     */
203 40
    protected function getProgressBarStr($current, $label)
204
    {
205 40
        $percentage = $current / $this->total;
206 40
        $bar_length = round($this->getBarStrLen() * $percentage);
207
208 40
        $bar        = $this->getBar($bar_length);
209 40
        $number     = $this->percentageFormatted($percentage);
210
211 40
        if ($label) {
212 8
            $label = $this->labelFormatted($label);
213 2
        }
214
215 40
        return trim("{$bar} {$number}{$label}");
216
    }
217
218
    /**
219
     * Get the string for the actual bar based on the current length
220
     *
221
     * @param integer $length
222
     *
223
     * @return string
224
     */
225 40
    protected function getBar($length)
226
    {
227 40
        $bar     = str_repeat('=', $length);
228 40
        $padding = str_repeat(' ', $this->getBarStrLen() - $length);
229
230 40
        return "{$bar}>{$padding}";
231
    }
232
233
    /**
234
     * Get the length of the bar string based on the width of the terminal window
235
     *
236
     * @return integer
237
     */
238 40
    protected function getBarStrLen()
239
    {
240 40
        if (!$this->bar_str_len) {
241
            // Subtract 10 because of the '> 100%' plus some padding, max 100
242 40
            $this->bar_str_len = min($this->util->width() - 10, 100);
243 10
        }
244
245 40
        return $this->bar_str_len;
246
    }
247
248
    /**
249
     * Format the percentage so it looks pretty
250
     *
251
     * @param integer $percentage
252
     * @return float
253
     */
254 40
    protected function percentageFormatted($percentage)
255
    {
256 40
        return round($percentage * 100) . '%';
257
    }
258
259
    /**
260
     * Format the label so it is positioned correctly
261
     *
262
     * @param string $label
263
     * @return string
264
     */
265 8
    protected function labelFormatted($label)
266
    {
267 8
        return "\n" . $this->util->cursor->startOfCurrentLine() . $this->util->cursor->deleteCurrentLine() . $label;
268
    }
269
270
    /**
271
     * Determine whether the progress bar has changed and we need to redrew
272
     *
273
     * @param string $percentage
274
     * @param string $label
275
     *
276
     * @return boolean
277
     */
278 40
    protected function shouldRedraw($percentage, $label)
279
    {
280 40
        return ($this->force_redraw || $percentage != $this->current_percentage || $label != $this->label);
281
    }
282
}
283