ProgressBar.php 20 KB

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