ProgressBar.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. // Erase previous lines
  329. if ($this->formatLineCount > 0) {
  330. $message = str_repeat("\x1B[1A\x1B[2K", $this->formatLineCount).$message;
  331. }
  332. // Move the cursor to the beginning of the line and erase the line
  333. $message = "\x0D\x1B[2K$message";
  334. }
  335. }
  336. } elseif ($this->step > 0) {
  337. $message = PHP_EOL.$message;
  338. }
  339. $this->firstRun = false;
  340. $this->output->write($message);
  341. }
  342. private function determineBestFormat(): string
  343. {
  344. switch ($this->output->getVerbosity()) {
  345. // OutputInterface::VERBOSITY_QUIET: display is disabled anyway
  346. case OutputInterface::VERBOSITY_VERBOSE:
  347. return $this->max ? 'verbose' : 'verbose_nomax';
  348. case OutputInterface::VERBOSITY_VERY_VERBOSE:
  349. return $this->max ? 'very_verbose' : 'very_verbose_nomax';
  350. case OutputInterface::VERBOSITY_DEBUG:
  351. return $this->max ? 'debug' : 'debug_nomax';
  352. default:
  353. return $this->max ? 'normal' : 'normal_nomax';
  354. }
  355. }
  356. private static function initPlaceholderFormatters(): array
  357. {
  358. return [
  359. 'bar' => function (self $bar, OutputInterface $output) {
  360. $completeBars = floor($bar->getMaxSteps() > 0 ? $bar->getProgressPercent() * $bar->getBarWidth() : $bar->getProgress() % $bar->getBarWidth());
  361. $display = str_repeat($bar->getBarCharacter(), $completeBars);
  362. if ($completeBars < $bar->getBarWidth()) {
  363. $emptyBars = $bar->getBarWidth() - $completeBars - Helper::strlenWithoutDecoration($output->getFormatter(), $bar->getProgressCharacter());
  364. $display .= $bar->getProgressCharacter().str_repeat($bar->getEmptyBarCharacter(), $emptyBars);
  365. }
  366. return $display;
  367. },
  368. 'elapsed' => function (self $bar) {
  369. return Helper::formatTime(time() - $bar->getStartTime());
  370. },
  371. 'remaining' => function (self $bar) {
  372. if (!$bar->getMaxSteps()) {
  373. throw new LogicException('Unable to display the remaining time if the maximum number of steps is not set.');
  374. }
  375. if (!$bar->getProgress()) {
  376. $remaining = 0;
  377. } else {
  378. $remaining = round((time() - $bar->getStartTime()) / $bar->getProgress() * ($bar->getMaxSteps() - $bar->getProgress()));
  379. }
  380. return Helper::formatTime($remaining);
  381. },
  382. 'estimated' => function (self $bar) {
  383. if (!$bar->getMaxSteps()) {
  384. throw new LogicException('Unable to display the estimated time if the maximum number of steps is not set.');
  385. }
  386. if (!$bar->getProgress()) {
  387. $estimated = 0;
  388. } else {
  389. $estimated = round((time() - $bar->getStartTime()) / $bar->getProgress() * $bar->getMaxSteps());
  390. }
  391. return Helper::formatTime($estimated);
  392. },
  393. 'memory' => function (self $bar) {
  394. return Helper::formatMemory(memory_get_usage(true));
  395. },
  396. 'current' => function (self $bar) {
  397. return str_pad($bar->getProgress(), $bar->getStepWidth(), ' ', STR_PAD_LEFT);
  398. },
  399. 'max' => function (self $bar) {
  400. return $bar->getMaxSteps();
  401. },
  402. 'percent' => function (self $bar) {
  403. return floor($bar->getProgressPercent() * 100);
  404. },
  405. ];
  406. }
  407. private static function initFormats(): array
  408. {
  409. return [
  410. 'normal' => ' %current%/%max% [%bar%] %percent:3s%%',
  411. 'normal_nomax' => ' %current% [%bar%]',
  412. 'verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%',
  413. 'verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
  414. 'very_verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%',
  415. 'very_verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
  416. 'debug' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%',
  417. 'debug_nomax' => ' %current% [%bar%] %elapsed:6s% %memory:6s%',
  418. ];
  419. }
  420. private function buildLine(): string
  421. {
  422. $regex = "{%([a-z\-_]+)(?:\:([^%]+))?%}i";
  423. $callback = function ($matches) {
  424. if ($formatter = $this::getPlaceholderFormatterDefinition($matches[1])) {
  425. $text = $formatter($this, $this->output);
  426. } elseif (isset($this->messages[$matches[1]])) {
  427. $text = $this->messages[$matches[1]];
  428. } else {
  429. return $matches[0];
  430. }
  431. if (isset($matches[2])) {
  432. $text = sprintf('%'.$matches[2], $text);
  433. }
  434. return $text;
  435. };
  436. $line = preg_replace_callback($regex, $callback, $this->format);
  437. // gets string length for each sub line with multiline format
  438. $linesLength = array_map(function ($subLine) {
  439. return Helper::strlenWithoutDecoration($this->output->getFormatter(), rtrim($subLine, "\r"));
  440. }, explode("\n", $line));
  441. $linesWidth = max($linesLength);
  442. $terminalWidth = $this->terminal->getWidth();
  443. if ($linesWidth <= $terminalWidth) {
  444. return $line;
  445. }
  446. $this->setBarWidth($this->barWidth - $linesWidth + $terminalWidth);
  447. return preg_replace_callback($regex, $callback, $this->format);
  448. }
  449. }