ProgressBar.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. * Returns an iterator that will automatically update the progress bar when iterated.
  211. *
  212. * @param int|null $max Number of steps to complete the bar (0 if indeterminate), if null it will be inferred from $iterable
  213. */
  214. public function iterate(iterable $iterable, int $max = null): iterable
  215. {
  216. $this->start($max ?? (is_countable($iterable) ? \count($iterable) : 0));
  217. foreach ($iterable as $key => $value) {
  218. yield $key => $value;
  219. $this->advance();
  220. }
  221. $this->finish();
  222. }
  223. /**
  224. * Starts the progress output.
  225. *
  226. * @param int|null $max Number of steps to complete the bar (0 if indeterminate), null to leave unchanged
  227. */
  228. public function start(int $max = null)
  229. {
  230. $this->startTime = time();
  231. $this->step = 0;
  232. $this->percent = 0.0;
  233. if (null !== $max) {
  234. $this->setMaxSteps($max);
  235. }
  236. $this->display();
  237. }
  238. /**
  239. * Advances the progress output X steps.
  240. *
  241. * @param int $step Number of steps to advance
  242. */
  243. public function advance(int $step = 1)
  244. {
  245. $this->setProgress($this->step + $step);
  246. }
  247. /**
  248. * Sets whether to overwrite the progressbar, false for new line.
  249. */
  250. public function setOverwrite(bool $overwrite)
  251. {
  252. $this->overwrite = $overwrite;
  253. }
  254. public function setProgress(int $step)
  255. {
  256. if ($this->max && $step > $this->max) {
  257. $this->max = $step;
  258. } elseif ($step < 0) {
  259. $step = 0;
  260. }
  261. $prevPeriod = (int) ($this->step / $this->redrawFreq);
  262. $currPeriod = (int) ($step / $this->redrawFreq);
  263. $this->step = $step;
  264. $this->percent = $this->max ? (float) $this->step / $this->max : 0;
  265. if ($prevPeriod !== $currPeriod || $this->max === $step) {
  266. $this->display();
  267. }
  268. }
  269. public function setMaxSteps(int $max)
  270. {
  271. $this->format = null;
  272. $this->max = max(0, $max);
  273. $this->stepWidth = $this->max ? Helper::strlen((string) $this->max) : 4;
  274. }
  275. /**
  276. * Finishes the progress output.
  277. */
  278. public function finish(): void
  279. {
  280. if (!$this->max) {
  281. $this->max = $this->step;
  282. }
  283. if ($this->step === $this->max && !$this->overwrite) {
  284. // prevent double 100% output
  285. return;
  286. }
  287. $this->setProgress($this->max);
  288. }
  289. /**
  290. * Outputs the current progress string.
  291. */
  292. public function display(): void
  293. {
  294. if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) {
  295. return;
  296. }
  297. if (null === $this->format) {
  298. $this->setRealFormat($this->internalFormat ?: $this->determineBestFormat());
  299. }
  300. $this->overwrite($this->buildLine());
  301. }
  302. /**
  303. * Removes the progress bar from the current line.
  304. *
  305. * This is useful if you wish to write some output
  306. * while a progress bar is running.
  307. * Call display() to show the progress bar again.
  308. */
  309. public function clear(): void
  310. {
  311. if (!$this->overwrite) {
  312. return;
  313. }
  314. if (null === $this->format) {
  315. $this->setRealFormat($this->internalFormat ?: $this->determineBestFormat());
  316. }
  317. $this->overwrite('');
  318. }
  319. private function setRealFormat(string $format)
  320. {
  321. // try to use the _nomax variant if available
  322. if (!$this->max && null !== self::getFormatDefinition($format.'_nomax')) {
  323. $this->format = self::getFormatDefinition($format.'_nomax');
  324. } elseif (null !== self::getFormatDefinition($format)) {
  325. $this->format = self::getFormatDefinition($format);
  326. } else {
  327. $this->format = $format;
  328. }
  329. $this->formatLineCount = substr_count($this->format, "\n");
  330. }
  331. /**
  332. * Overwrites a previous message to the output.
  333. */
  334. private function overwrite(string $message): void
  335. {
  336. if ($this->overwrite) {
  337. if (!$this->firstRun) {
  338. if ($this->output instanceof ConsoleSectionOutput) {
  339. $lines = floor(Helper::strlen($message) / $this->terminal->getWidth()) + $this->formatLineCount + 1;
  340. $this->output->clear($lines);
  341. } else {
  342. // Erase previous lines
  343. if ($this->formatLineCount > 0) {
  344. $message = str_repeat("\x1B[1A\x1B[2K", $this->formatLineCount).$message;
  345. }
  346. // Move the cursor to the beginning of the line and erase the line
  347. $message = "\x0D\x1B[2K$message";
  348. }
  349. }
  350. } elseif ($this->step > 0) {
  351. $message = PHP_EOL.$message;
  352. }
  353. $this->firstRun = false;
  354. $this->output->write($message);
  355. }
  356. private function determineBestFormat(): string
  357. {
  358. switch ($this->output->getVerbosity()) {
  359. // OutputInterface::VERBOSITY_QUIET: display is disabled anyway
  360. case OutputInterface::VERBOSITY_VERBOSE:
  361. return $this->max ? 'verbose' : 'verbose_nomax';
  362. case OutputInterface::VERBOSITY_VERY_VERBOSE:
  363. return $this->max ? 'very_verbose' : 'very_verbose_nomax';
  364. case OutputInterface::VERBOSITY_DEBUG:
  365. return $this->max ? 'debug' : 'debug_nomax';
  366. default:
  367. return $this->max ? 'normal' : 'normal_nomax';
  368. }
  369. }
  370. private static function initPlaceholderFormatters(): array
  371. {
  372. return [
  373. 'bar' => function (self $bar, OutputInterface $output) {
  374. $completeBars = floor($bar->getMaxSteps() > 0 ? $bar->getProgressPercent() * $bar->getBarWidth() : $bar->getProgress() % $bar->getBarWidth());
  375. $display = str_repeat($bar->getBarCharacter(), $completeBars);
  376. if ($completeBars < $bar->getBarWidth()) {
  377. $emptyBars = $bar->getBarWidth() - $completeBars - Helper::strlenWithoutDecoration($output->getFormatter(), $bar->getProgressCharacter());
  378. $display .= $bar->getProgressCharacter().str_repeat($bar->getEmptyBarCharacter(), $emptyBars);
  379. }
  380. return $display;
  381. },
  382. 'elapsed' => function (self $bar) {
  383. return Helper::formatTime(time() - $bar->getStartTime());
  384. },
  385. 'remaining' => function (self $bar) {
  386. if (!$bar->getMaxSteps()) {
  387. throw new LogicException('Unable to display the remaining time if the maximum number of steps is not set.');
  388. }
  389. if (!$bar->getProgress()) {
  390. $remaining = 0;
  391. } else {
  392. $remaining = round((time() - $bar->getStartTime()) / $bar->getProgress() * ($bar->getMaxSteps() - $bar->getProgress()));
  393. }
  394. return Helper::formatTime($remaining);
  395. },
  396. 'estimated' => function (self $bar) {
  397. if (!$bar->getMaxSteps()) {
  398. throw new LogicException('Unable to display the estimated time if the maximum number of steps is not set.');
  399. }
  400. if (!$bar->getProgress()) {
  401. $estimated = 0;
  402. } else {
  403. $estimated = round((time() - $bar->getStartTime()) / $bar->getProgress() * $bar->getMaxSteps());
  404. }
  405. return Helper::formatTime($estimated);
  406. },
  407. 'memory' => function (self $bar) {
  408. return Helper::formatMemory(memory_get_usage(true));
  409. },
  410. 'current' => function (self $bar) {
  411. return str_pad($bar->getProgress(), $bar->getStepWidth(), ' ', STR_PAD_LEFT);
  412. },
  413. 'max' => function (self $bar) {
  414. return $bar->getMaxSteps();
  415. },
  416. 'percent' => function (self $bar) {
  417. return floor($bar->getProgressPercent() * 100);
  418. },
  419. ];
  420. }
  421. private static function initFormats(): array
  422. {
  423. return [
  424. 'normal' => ' %current%/%max% [%bar%] %percent:3s%%',
  425. 'normal_nomax' => ' %current% [%bar%]',
  426. 'verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%',
  427. 'verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
  428. 'very_verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%',
  429. 'very_verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
  430. 'debug' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%',
  431. 'debug_nomax' => ' %current% [%bar%] %elapsed:6s% %memory:6s%',
  432. ];
  433. }
  434. private function buildLine(): string
  435. {
  436. $regex = "{%([a-z\-_]+)(?:\:([^%]+))?%}i";
  437. $callback = function ($matches) {
  438. if ($formatter = $this::getPlaceholderFormatterDefinition($matches[1])) {
  439. $text = $formatter($this, $this->output);
  440. } elseif (isset($this->messages[$matches[1]])) {
  441. $text = $this->messages[$matches[1]];
  442. } else {
  443. return $matches[0];
  444. }
  445. if (isset($matches[2])) {
  446. $text = sprintf('%'.$matches[2], $text);
  447. }
  448. return $text;
  449. };
  450. $line = preg_replace_callback($regex, $callback, $this->format);
  451. // gets string length for each sub line with multiline format
  452. $linesLength = array_map(function ($subLine) {
  453. return Helper::strlenWithoutDecoration($this->output->getFormatter(), rtrim($subLine, "\r"));
  454. }, explode("\n", $line));
  455. $linesWidth = max($linesLength);
  456. $terminalWidth = $this->terminal->getWidth();
  457. if ($linesWidth <= $terminalWidth) {
  458. return $line;
  459. }
  460. $this->setBarWidth($this->barWidth - $linesWidth + $terminalWidth);
  461. return preg_replace_callback($regex, $callback, $this->format);
  462. }
  463. }