ProgressBar.php 18 KB

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