ProgressBar.php 17 KB

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