ProgressBar.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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 $formatLineCount;
  40. private $messages = array();
  41. private $overwrite = true;
  42. private $firstRun = 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 $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. /**
  125. * Associates a text with a named placeholder.
  126. *
  127. * The text is displayed when the progress bar is rendered but only
  128. * when the corresponding placeholder is part of the custom format line
  129. * (by wrapping the name with %).
  130. *
  131. * @param string $message The text to associate with the placeholder
  132. * @param string $name The name of the placeholder
  133. */
  134. public function setMessage($message, $name = 'message')
  135. {
  136. $this->messages[$name] = $message;
  137. }
  138. public function getMessage($name = 'message')
  139. {
  140. return $this->messages[$name];
  141. }
  142. /**
  143. * Gets the progress bar start time.
  144. *
  145. * @return int The progress bar start time
  146. */
  147. public function getStartTime()
  148. {
  149. return $this->startTime;
  150. }
  151. /**
  152. * Gets the progress bar maximal steps.
  153. *
  154. * @return int The progress bar max steps
  155. */
  156. public function getMaxSteps()
  157. {
  158. return $this->max;
  159. }
  160. /**
  161. * Gets the current step position.
  162. *
  163. * @return int The progress bar step
  164. */
  165. public function getProgress()
  166. {
  167. return $this->step;
  168. }
  169. /**
  170. * Gets the progress bar step width.
  171. *
  172. * @return int The progress bar step width
  173. */
  174. private 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. $this->format = null;
  270. $this->internalFormat = $format;
  271. }
  272. /**
  273. * Sets the redraw frequency.
  274. *
  275. * @param int|float $freq The frequency in steps
  276. */
  277. public function setRedrawFrequency($freq)
  278. {
  279. $this->redrawFreq = max((int) $freq, 1);
  280. }
  281. /**
  282. * Starts the progress output.
  283. *
  284. * @param int|null $max Number of steps to complete the bar (0 if indeterminate), null to leave unchanged
  285. */
  286. public function start($max = null)
  287. {
  288. $this->startTime = time();
  289. $this->step = 0;
  290. $this->percent = 0.0;
  291. if (null !== $max) {
  292. $this->setMaxSteps($max);
  293. }
  294. $this->display();
  295. }
  296. /**
  297. * Advances the progress output X steps.
  298. *
  299. * @param int $step Number of steps to advance
  300. *
  301. * @throws LogicException
  302. */
  303. public function advance($step = 1)
  304. {
  305. $this->setProgress($this->step + $step);
  306. }
  307. /**
  308. * Sets whether to overwrite the progressbar, false for new line.
  309. *
  310. * @param bool $overwrite
  311. */
  312. public function setOverwrite($overwrite)
  313. {
  314. $this->overwrite = (bool) $overwrite;
  315. }
  316. /**
  317. * Sets the current progress.
  318. *
  319. * @param int $step The current progress
  320. *
  321. * @throws LogicException
  322. */
  323. public function setProgress($step)
  324. {
  325. $step = (int) $step;
  326. if ($step < $this->step) {
  327. throw new LogicException('You can\'t regress the progress bar.');
  328. }
  329. if ($this->max && $step > $this->max) {
  330. $this->max = $step;
  331. }
  332. $prevPeriod = (int) ($this->step / $this->redrawFreq);
  333. $currPeriod = (int) ($step / $this->redrawFreq);
  334. $this->step = $step;
  335. $this->percent = $this->max ? (float) $this->step / $this->max : 0;
  336. if ($prevPeriod !== $currPeriod || $this->max === $step) {
  337. $this->display();
  338. }
  339. }
  340. /**
  341. * Finishes the progress output.
  342. */
  343. public function finish()
  344. {
  345. if (!$this->max) {
  346. $this->max = $this->step;
  347. }
  348. if ($this->step === $this->max && !$this->overwrite) {
  349. // prevent double 100% output
  350. return;
  351. }
  352. $this->setProgress($this->max);
  353. }
  354. /**
  355. * Outputs the current progress string.
  356. */
  357. public function display()
  358. {
  359. if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) {
  360. return;
  361. }
  362. if (null === $this->format) {
  363. $this->setRealFormat($this->internalFormat ?: $this->determineBestFormat());
  364. }
  365. $this->overwrite(preg_replace_callback("{%([a-z\-_]+)(?:\:([^%]+))?%}i", function ($matches) {
  366. if ($formatter = $this::getPlaceholderFormatterDefinition($matches[1])) {
  367. $text = call_user_func($formatter, $this, $this->output);
  368. } elseif (isset($this->messages[$matches[1]])) {
  369. $text = $this->messages[$matches[1]];
  370. } else {
  371. return $matches[0];
  372. }
  373. if (isset($matches[2])) {
  374. $text = sprintf('%'.$matches[2], $text);
  375. }
  376. return $text;
  377. }, $this->format));
  378. }
  379. /**
  380. * Removes the progress bar from the current line.
  381. *
  382. * This is useful if you wish to write some output
  383. * while a progress bar is running.
  384. * Call display() to show the progress bar again.
  385. */
  386. public function clear()
  387. {
  388. if (!$this->overwrite) {
  389. return;
  390. }
  391. if (null === $this->format) {
  392. $this->setRealFormat($this->internalFormat ?: $this->determineBestFormat());
  393. }
  394. $this->overwrite('');
  395. }
  396. /**
  397. * Sets the progress bar format.
  398. *
  399. * @param string $format The format
  400. */
  401. private function setRealFormat($format)
  402. {
  403. // try to use the _nomax variant if available
  404. if (!$this->max && null !== self::getFormatDefinition($format.'_nomax')) {
  405. $this->format = self::getFormatDefinition($format.'_nomax');
  406. } elseif (null !== self::getFormatDefinition($format)) {
  407. $this->format = self::getFormatDefinition($format);
  408. } else {
  409. $this->format = $format;
  410. }
  411. $this->formatLineCount = substr_count($this->format, "\n");
  412. }
  413. /**
  414. * Sets the progress bar maximal steps.
  415. *
  416. * @param int $max The progress bar max steps
  417. */
  418. private function setMaxSteps($max)
  419. {
  420. $this->max = max(0, (int) $max);
  421. $this->stepWidth = $this->max ? Helper::strlen($this->max) : 4;
  422. }
  423. /**
  424. * Overwrites a previous message to the output.
  425. *
  426. * @param string $message The message
  427. */
  428. private function overwrite($message)
  429. {
  430. if ($this->overwrite) {
  431. if (!$this->firstRun) {
  432. // Move the cursor to the beginning of the line
  433. $this->output->write("\x0D");
  434. // Erase the line
  435. $this->output->write("\x1B[2K");
  436. // Erase previous lines
  437. if ($this->formatLineCount > 0) {
  438. $this->output->write(str_repeat("\x1B[1A\x1B[2K", $this->formatLineCount));
  439. }
  440. }
  441. } elseif ($this->step > 0) {
  442. $this->output->writeln('');
  443. }
  444. $this->firstRun = false;
  445. $this->output->write($message);
  446. }
  447. private function determineBestFormat()
  448. {
  449. switch ($this->output->getVerbosity()) {
  450. // OutputInterface::VERBOSITY_QUIET: display is disabled anyway
  451. case OutputInterface::VERBOSITY_VERBOSE:
  452. return $this->max ? 'verbose' : 'verbose_nomax';
  453. case OutputInterface::VERBOSITY_VERY_VERBOSE:
  454. return $this->max ? 'very_verbose' : 'very_verbose_nomax';
  455. case OutputInterface::VERBOSITY_DEBUG:
  456. return $this->max ? 'debug' : 'debug_nomax';
  457. default:
  458. return $this->max ? 'normal' : 'normal_nomax';
  459. }
  460. }
  461. private static function initPlaceholderFormatters()
  462. {
  463. return array(
  464. 'bar' => function (ProgressBar $bar, OutputInterface $output) {
  465. $completeBars = floor($bar->getMaxSteps() > 0 ? $bar->getProgressPercent() * $bar->getBarWidth() : $bar->getProgress() % $bar->getBarWidth());
  466. $display = str_repeat($bar->getBarCharacter(), $completeBars);
  467. if ($completeBars < $bar->getBarWidth()) {
  468. $emptyBars = $bar->getBarWidth() - $completeBars - Helper::strlenWithoutDecoration($output->getFormatter(), $bar->getProgressCharacter());
  469. $display .= $bar->getProgressCharacter().str_repeat($bar->getEmptyBarCharacter(), $emptyBars);
  470. }
  471. return $display;
  472. },
  473. 'elapsed' => function (ProgressBar $bar) {
  474. return Helper::formatTime(time() - $bar->getStartTime());
  475. },
  476. 'remaining' => function (ProgressBar $bar) {
  477. if (!$bar->getMaxSteps()) {
  478. throw new LogicException('Unable to display the remaining time if the maximum number of steps is not set.');
  479. }
  480. if (!$bar->getProgress()) {
  481. $remaining = 0;
  482. } else {
  483. $remaining = round((time() - $bar->getStartTime()) / $bar->getProgress() * ($bar->getMaxSteps() - $bar->getProgress()));
  484. }
  485. return Helper::formatTime($remaining);
  486. },
  487. 'estimated' => function (ProgressBar $bar) {
  488. if (!$bar->getMaxSteps()) {
  489. throw new LogicException('Unable to display the estimated time if the maximum number of steps is not set.');
  490. }
  491. if (!$bar->getProgress()) {
  492. $estimated = 0;
  493. } else {
  494. $estimated = round((time() - $bar->getStartTime()) / $bar->getProgress() * $bar->getMaxSteps());
  495. }
  496. return Helper::formatTime($estimated);
  497. },
  498. 'memory' => function (ProgressBar $bar) {
  499. return Helper::formatMemory(memory_get_usage(true));
  500. },
  501. 'current' => function (ProgressBar $bar) {
  502. return str_pad($bar->getProgress(), $bar->getStepWidth(), ' ', STR_PAD_LEFT);
  503. },
  504. 'max' => function (ProgressBar $bar) {
  505. return $bar->getMaxSteps();
  506. },
  507. 'percent' => function (ProgressBar $bar) {
  508. return floor($bar->getProgressPercent() * 100);
  509. },
  510. );
  511. }
  512. private static function initFormats()
  513. {
  514. return array(
  515. 'normal' => ' %current%/%max% [%bar%] %percent:3s%%',
  516. 'normal_nomax' => ' %current% [%bar%]',
  517. 'verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%',
  518. 'verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
  519. 'very_verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%',
  520. 'very_verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
  521. 'debug' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%',
  522. 'debug_nomax' => ' %current% [%bar%] %elapsed:6s% %memory:6s%',
  523. );
  524. }
  525. }