ProgressBar.php 17 KB

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