No Description

ProgressBar.php 17KB

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