ProgressBar.php 18 KB

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