ProgressBar.php 16 KB

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