ProgressBar::getBarOffset()   A
last analyzed

Complexity

Conditions 3
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 3
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Symfony\Component\Console\Helper;
13
14
use Symfony\Component\Console\Cursor;
15
use Symfony\Component\Console\Exception\LogicException;
16
use Symfony\Component\Console\Output\ConsoleOutputInterface;
17
use Symfony\Component\Console\Output\ConsoleSectionOutput;
18
use Symfony\Component\Console\Output\OutputInterface;
19
use Symfony\Component\Console\Terminal;
20
21
/**
22
 * The ProgressBar provides helpers to display progress output.
23
 *
24
 * @author Fabien Potencier <[email protected]>
25
 * @author Chris Jones <[email protected]>
26
 */
27
final class ProgressBar
28
{
29
    public const FORMAT_VERBOSE = 'verbose';
30
    public const FORMAT_VERY_VERBOSE = 'very_verbose';
31
    public const FORMAT_DEBUG = 'debug';
32
    public const FORMAT_NORMAL = 'normal';
33
34
    private const FORMAT_VERBOSE_NOMAX = 'verbose_nomax';
35
    private const FORMAT_VERY_VERBOSE_NOMAX = 'very_verbose_nomax';
36
    private const FORMAT_DEBUG_NOMAX = 'debug_nomax';
37
    private const FORMAT_NORMAL_NOMAX = 'normal_nomax';
38
39
    private $barWidth = 28;
40
    private $barChar;
41
    private $emptyBarChar = '-';
42
    private $progressChar = '>';
43
    private $format;
44
    private $internalFormat;
45
    private $redrawFreq = 1;
46
    private $writeCount;
47
    private $lastWriteTime;
48
    private $minSecondsBetweenRedraws = 0;
49
    private $maxSecondsBetweenRedraws = 1;
50
    private $output;
51
    private $step = 0;
52
    private $max;
53
    private $startTime;
54
    private $stepWidth;
55
    private $percent = 0.0;
56
    private $formatLineCount;
57
    private $messages = [];
58
    private $overwrite = true;
59
    private $terminal;
60
    private $previousMessage;
61
    private $cursor;
62
63
    private static $formatters;
64
    private static $formats;
65
66
    /**
67
     * @param int $max Maximum steps (0 if unknown)
68
     */
69
    public function __construct(OutputInterface $output, int $max = 0, float $minSecondsBetweenRedraws = 1 / 25)
70
    {
71
        if ($output instanceof ConsoleOutputInterface) {
72
            $output = $output->getErrorOutput();
73
        }
74
75
        $this->output = $output;
76
        $this->setMaxSteps($max);
77
        $this->terminal = new Terminal();
78
79
        if (0 < $minSecondsBetweenRedraws) {
80
            $this->redrawFreq = null;
81
            $this->minSecondsBetweenRedraws = $minSecondsBetweenRedraws;
82
        }
83
84
        if (!$this->output->isDecorated()) {
85
            // disable overwrite when output does not support ANSI codes.
86
            $this->overwrite = false;
87
88
            // set a reasonable redraw frequency so output isn't flooded
89
            $this->redrawFreq = null;
90
        }
91
92
        $this->startTime = time();
93
        $this->cursor = new Cursor($output);
94
    }
95
96
    /**
97
     * Sets a placeholder formatter for a given name.
98
     *
99
     * This method also allow you to override an existing placeholder.
100
     *
101
     * @param string   $name     The placeholder name (including the delimiter char like %)
102
     * @param callable $callable A PHP callable
103
     */
104
    public static function setPlaceholderFormatterDefinition(string $name, callable $callable): void
105
    {
106
        if (!self::$formatters) {
107
            self::$formatters = self::initPlaceholderFormatters();
108
        }
109
110
        self::$formatters[$name] = $callable;
111
    }
112
113
    /**
114
     * Gets the placeholder formatter for a given name.
115
     *
116
     * @param string $name The placeholder name (including the delimiter char like %)
117
     *
118
     * @return callable|null A PHP callable
119
     */
120
    public static function getPlaceholderFormatterDefinition(string $name): ?callable
121
    {
122
        if (!self::$formatters) {
123
            self::$formatters = self::initPlaceholderFormatters();
124
        }
125
126
        return self::$formatters[$name] ?? null;
127
    }
128
129
    /**
130
     * Sets a format for a given name.
131
     *
132
     * This method also allow you to override an existing format.
133
     *
134
     * @param string $name   The format name
135
     * @param string $format A format string
136
     */
137
    public static function setFormatDefinition(string $name, string $format): void
138
    {
139
        if (!self::$formats) {
140
            self::$formats = self::initFormats();
141
        }
142
143
        self::$formats[$name] = $format;
144
    }
145
146
    /**
147
     * Gets the format for a given name.
148
     *
149
     * @param string $name The format name
150
     *
151
     * @return string|null A format string
152
     */
153
    public static function getFormatDefinition(string $name): ?string
154
    {
155
        if (!self::$formats) {
156
            self::$formats = self::initFormats();
157
        }
158
159
        return self::$formats[$name] ?? null;
160
    }
161
162
    /**
163
     * Associates a text with a named placeholder.
164
     *
165
     * The text is displayed when the progress bar is rendered but only
166
     * when the corresponding placeholder is part of the custom format line
167
     * (by wrapping the name with %).
168
     *
169
     * @param string $message The text to associate with the placeholder
170
     * @param string $name    The name of the placeholder
171
     */
172
    public function setMessage(string $message, string $name = 'message')
173
    {
174
        $this->messages[$name] = $message;
175
    }
176
177
    public function getMessage(string $name = 'message')
178
    {
179
        return $this->messages[$name];
180
    }
181
182
    public function getStartTime(): int
183
    {
184
        return $this->startTime;
185
    }
186
187
    public function getMaxSteps(): int
188
    {
189
        return $this->max;
190
    }
191
192
    public function getProgress(): int
193
    {
194
        return $this->step;
195
    }
196
197
    private function getStepWidth(): int
198
    {
199
        return $this->stepWidth;
200
    }
201
202
    public function getProgressPercent(): float
203
    {
204
        return $this->percent;
205
    }
206
207
    public function getBarOffset(): float
208
    {
209
        return floor($this->max ? $this->percent * $this->barWidth : (null === $this->redrawFreq ? min(5, $this->barWidth / 15) * $this->writeCount : $this->step) % $this->barWidth);
210
    }
211
212
    public function getEstimated(): float
213
    {
214
        if (!$this->step) {
215
            return 0;
216
        }
217
218
        return round((time() - $this->startTime) / $this->step * $this->max);
219
    }
220
221
    public function getRemaining(): float
222
    {
223
        if (!$this->step) {
224
            return 0;
225
        }
226
227
        return round((time() - $this->startTime) / $this->step * ($this->max - $this->step));
228
    }
229
230
    public function setBarWidth(int $size)
231
    {
232
        $this->barWidth = max(1, $size);
233
    }
234
235
    public function getBarWidth(): int
236
    {
237
        return $this->barWidth;
238
    }
239
240
    public function setBarCharacter(string $char)
241
    {
242
        $this->barChar = $char;
243
    }
244
245
    public function getBarCharacter(): string
246
    {
247
        if (null === $this->barChar) {
248
            return $this->max ? '=' : $this->emptyBarChar;
249
        }
250
251
        return $this->barChar;
252
    }
253
254
    public function setEmptyBarCharacter(string $char)
255
    {
256
        $this->emptyBarChar = $char;
257
    }
258
259
    public function getEmptyBarCharacter(): string
260
    {
261
        return $this->emptyBarChar;
262
    }
263
264
    public function setProgressCharacter(string $char)
265
    {
266
        $this->progressChar = $char;
267
    }
268
269
    public function getProgressCharacter(): string
270
    {
271
        return $this->progressChar;
272
    }
273
274
    public function setFormat(string $format)
275
    {
276
        $this->format = null;
277
        $this->internalFormat = $format;
278
    }
279
280
    /**
281
     * Sets the redraw frequency.
282
     *
283
     * @param int|float $freq The frequency in steps
284
     */
285
    public function setRedrawFrequency(?int $freq)
286
    {
287
        $this->redrawFreq = null !== $freq ? max(1, $freq) : null;
288
    }
289
290
    public function minSecondsBetweenRedraws(float $seconds): void
291
    {
292
        $this->minSecondsBetweenRedraws = $seconds;
293
    }
294
295
    public function maxSecondsBetweenRedraws(float $seconds): void
296
    {
297
        $this->maxSecondsBetweenRedraws = $seconds;
298
    }
299
300
    /**
301
     * Returns an iterator that will automatically update the progress bar when iterated.
302
     *
303
     * @param int|null $max Number of steps to complete the bar (0 if indeterminate), if null it will be inferred from $iterable
304
     */
305
    public function iterate(iterable $iterable, int $max = null): iterable
306
    {
307
        $this->start($max ?? (is_countable($iterable) ? \count($iterable) : 0));
308
309
        foreach ($iterable as $key => $value) {
310
            yield $key => $value;
311
312
            $this->advance();
313
        }
314
315
        $this->finish();
316
    }
317
318
    /**
319
     * Starts the progress output.
320
     *
321
     * @param int|null $max Number of steps to complete the bar (0 if indeterminate), null to leave unchanged
322
     */
323
    public function start(int $max = null)
324
    {
325
        $this->startTime = time();
326
        $this->step = 0;
327
        $this->percent = 0.0;
328
329
        if (null !== $max) {
330
            $this->setMaxSteps($max);
331
        }
332
333
        $this->display();
334
    }
335
336
    /**
337
     * Advances the progress output X steps.
338
     *
339
     * @param int $step Number of steps to advance
340
     */
341
    public function advance(int $step = 1)
342
    {
343
        $this->setProgress($this->step + $step);
344
    }
345
346
    /**
347
     * Sets whether to overwrite the progressbar, false for new line.
348
     */
349
    public function setOverwrite(bool $overwrite)
350
    {
351
        $this->overwrite = $overwrite;
352
    }
353
354
    public function setProgress(int $step)
355
    {
356
        if ($this->max && $step > $this->max) {
357
            $this->max = $step;
358
        } elseif ($step < 0) {
359
            $step = 0;
360
        }
361
362
        $redrawFreq = $this->redrawFreq ?? (($this->max ?: 10) / 10);
363
        $prevPeriod = (int) ($this->step / $redrawFreq);
364
        $currPeriod = (int) ($step / $redrawFreq);
365
        $this->step = $step;
366
        $this->percent = $this->max ? (float) $this->step / $this->max : 0;
367
        $timeInterval = microtime(true) - $this->lastWriteTime;
368
369
        // Draw regardless of other limits
370
        if ($this->max === $step) {
371
            $this->display();
372
373
            return;
374
        }
375
376
        // Throttling
377
        if ($timeInterval < $this->minSecondsBetweenRedraws) {
378
            return;
379
        }
380
381
        // Draw each step period, but not too late
382
        if ($prevPeriod !== $currPeriod || $timeInterval >= $this->maxSecondsBetweenRedraws) {
383
            $this->display();
384
        }
385
    }
386
387
    public function setMaxSteps(int $max)
388
    {
389
        $this->format = null;
390
        $this->max = max(0, $max);
391
        $this->stepWidth = $this->max ? Helper::width((string) $this->max) : 4;
392
    }
393
394
    /**
395
     * Finishes the progress output.
396
     */
397
    public function finish(): void
398
    {
399
        if (!$this->max) {
400
            $this->max = $this->step;
401
        }
402
403
        if ($this->step === $this->max && !$this->overwrite) {
404
            // prevent double 100% output
405
            return;
406
        }
407
408
        $this->setProgress($this->max);
409
    }
410
411
    /**
412
     * Outputs the current progress string.
413
     */
414
    public function display(): void
415
    {
416
        if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) {
417
            return;
418
        }
419
420
        if (null === $this->format) {
421
            $this->setRealFormat($this->internalFormat ?: $this->determineBestFormat());
422
        }
423
424
        $this->overwrite($this->buildLine());
425
    }
426
427
    /**
428
     * Removes the progress bar from the current line.
429
     *
430
     * This is useful if you wish to write some output
431
     * while a progress bar is running.
432
     * Call display() to show the progress bar again.
433
     */
434
    public function clear(): void
435
    {
436
        if (!$this->overwrite) {
437
            return;
438
        }
439
440
        if (null === $this->format) {
441
            $this->setRealFormat($this->internalFormat ?: $this->determineBestFormat());
442
        }
443
444
        $this->overwrite('');
445
    }
446
447
    private function setRealFormat(string $format)
448
    {
449
        // try to use the _nomax variant if available
450
        if (!$this->max && null !== self::getFormatDefinition($format.'_nomax')) {
451
            $this->format = self::getFormatDefinition($format.'_nomax');
452
        } elseif (null !== self::getFormatDefinition($format)) {
453
            $this->format = self::getFormatDefinition($format);
454
        } else {
455
            $this->format = $format;
456
        }
457
458
        $this->formatLineCount = substr_count($this->format, "\n");
0 ignored issues
show
Bug introduced by
It seems like $this->format can also be of type null; however, parameter $haystack of substr_count() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

458
        $this->formatLineCount = substr_count(/** @scrutinizer ignore-type */ $this->format, "\n");
Loading history...
459
    }
460
461
    /**
462
     * Overwrites a previous message to the output.
463
     */
464
    private function overwrite(string $message): void
465
    {
466
        if ($this->previousMessage === $message) {
467
            return;
468
        }
469
470
        $originalMessage = $message;
471
472
        if ($this->overwrite) {
473
            if (null !== $this->previousMessage) {
474
                if ($this->output instanceof ConsoleSectionOutput) {
475
                    $messageLines = explode("\n", $message);
476
                    $lineCount = \count($messageLines);
477
                    foreach ($messageLines as $messageLine) {
478
                        $messageLineLength = Helper::width(Helper::removeDecoration($this->output->getFormatter(), $messageLine));
479
                        if ($messageLineLength > $this->terminal->getWidth()) {
480
                            $lineCount += floor($messageLineLength / $this->terminal->getWidth());
481
                        }
482
                    }
483
                    $this->output->clear($lineCount);
0 ignored issues
show
Bug introduced by
It seems like $lineCount can also be of type double; however, parameter $lines of Symfony\Component\Consol...eSectionOutput::clear() does only seem to accept integer|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

483
                    $this->output->clear(/** @scrutinizer ignore-type */ $lineCount);
Loading history...
484
                } else {
485
                    if ($this->formatLineCount > 0) {
486
                        $this->cursor->moveUp($this->formatLineCount);
487
                    }
488
489
                    $this->cursor->moveToColumn(1);
490
                    $this->cursor->clearLine();
491
                }
492
            }
493
        } elseif ($this->step > 0) {
494
            $message = \PHP_EOL.$message;
495
        }
496
497
        $this->previousMessage = $originalMessage;
498
        $this->lastWriteTime = microtime(true);
499
500
        $this->output->write($message);
501
        ++$this->writeCount;
502
    }
503
504
    private function determineBestFormat(): string
505
    {
506
        switch ($this->output->getVerbosity()) {
507
            // OutputInterface::VERBOSITY_QUIET: display is disabled anyway
508
            case OutputInterface::VERBOSITY_VERBOSE:
509
                return $this->max ? self::FORMAT_VERBOSE : self::FORMAT_VERBOSE_NOMAX;
510
            case OutputInterface::VERBOSITY_VERY_VERBOSE:
511
                return $this->max ? self::FORMAT_VERY_VERBOSE : self::FORMAT_VERY_VERBOSE_NOMAX;
512
            case OutputInterface::VERBOSITY_DEBUG:
513
                return $this->max ? self::FORMAT_DEBUG : self::FORMAT_DEBUG_NOMAX;
514
            default:
515
                return $this->max ? self::FORMAT_NORMAL : self::FORMAT_NORMAL_NOMAX;
516
        }
517
    }
518
519
    private static function initPlaceholderFormatters(): array
520
    {
521
        return [
522
            'bar' => function (self $bar, OutputInterface $output) {
523
                $completeBars = $bar->getBarOffset();
524
                $display = str_repeat($bar->getBarCharacter(), $completeBars);
0 ignored issues
show
Bug introduced by
$completeBars of type double is incompatible with the type integer expected by parameter $times of str_repeat(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

524
                $display = str_repeat($bar->getBarCharacter(), /** @scrutinizer ignore-type */ $completeBars);
Loading history...
525
                if ($completeBars < $bar->getBarWidth()) {
526
                    $emptyBars = $bar->getBarWidth() - $completeBars - Helper::length(Helper::removeDecoration($output->getFormatter(), $bar->getProgressCharacter()));
527
                    $display .= $bar->getProgressCharacter().str_repeat($bar->getEmptyBarCharacter(), $emptyBars);
528
                }
529
530
                return $display;
531
            },
532
            'elapsed' => function (self $bar) {
533
                return Helper::formatTime(time() - $bar->getStartTime());
534
            },
535
            'remaining' => function (self $bar) {
536
                if (!$bar->getMaxSteps()) {
537
                    throw new LogicException('Unable to display the remaining time if the maximum number of steps is not set.');
538
                }
539
540
                return Helper::formatTime($bar->getRemaining());
541
            },
542
            'estimated' => function (self $bar) {
543
                if (!$bar->getMaxSteps()) {
544
                    throw new LogicException('Unable to display the estimated time if the maximum number of steps is not set.');
545
                }
546
547
                return Helper::formatTime($bar->getEstimated());
548
            },
549
            'memory' => function (self $bar) {
0 ignored issues
show
Unused Code introduced by
The parameter $bar is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

549
            'memory' => function (/** @scrutinizer ignore-unused */ self $bar) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
550
                return Helper::formatMemory(memory_get_usage(true));
551
            },
552
            'current' => function (self $bar) {
553
                return str_pad($bar->getProgress(), $bar->getStepWidth(), ' ', \STR_PAD_LEFT);
554
            },
555
            'max' => function (self $bar) {
556
                return $bar->getMaxSteps();
557
            },
558
            'percent' => function (self $bar) {
559
                return floor($bar->getProgressPercent() * 100);
560
            },
561
        ];
562
    }
563
564
    private static function initFormats(): array
565
    {
566
        return [
567
            self::FORMAT_NORMAL => ' %current%/%max% [%bar%] %percent:3s%%',
568
            self::FORMAT_NORMAL_NOMAX => ' %current% [%bar%]',
569
570
            self::FORMAT_VERBOSE => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%',
571
            self::FORMAT_VERBOSE_NOMAX => ' %current% [%bar%] %elapsed:6s%',
572
573
            self::FORMAT_VERY_VERBOSE => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%',
574
            self::FORMAT_VERY_VERBOSE_NOMAX => ' %current% [%bar%] %elapsed:6s%',
575
576
            self::FORMAT_DEBUG => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%',
577
            self::FORMAT_DEBUG_NOMAX => ' %current% [%bar%] %elapsed:6s% %memory:6s%',
578
        ];
579
    }
580
581
    private function buildLine(): string
582
    {
583
        $regex = "{%([a-z\-_]+)(?:\:([^%]+))?%}i";
584
        $callback = function ($matches) {
585
            if ($formatter = $this::getPlaceholderFormatterDefinition($matches[1])) {
586
                $text = $formatter($this, $this->output);
587
            } elseif (isset($this->messages[$matches[1]])) {
588
                $text = $this->messages[$matches[1]];
589
            } else {
590
                return $matches[0];
591
            }
592
593
            if (isset($matches[2])) {
594
                $text = sprintf('%'.$matches[2], $text);
595
            }
596
597
            return $text;
598
        };
599
        $line = preg_replace_callback($regex, $callback, $this->format);
600
601
        // gets string length for each sub line with multiline format
602
        $linesLength = array_map(function ($subLine) {
603
            return Helper::width(Helper::removeDecoration($this->output->getFormatter(), rtrim($subLine, "\r")));
604
        }, explode("\n", $line));
605
606
        $linesWidth = max($linesLength);
607
608
        $terminalWidth = $this->terminal->getWidth();
609
        if ($linesWidth <= $terminalWidth) {
610
            return $line;
611
        }
612
613
        $this->setBarWidth($this->barWidth - $linesWidth + $terminalWidth);
614
615
        return preg_replace_callback($regex, $callback, $this->format);
616
    }
617
}
618