ProgressBar.php 18 KB

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