ProgressBar.php 18 KB

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