PageRenderTime 48ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/symfony/symfony/src/Symfony/Component/Console/Helper/ProgressBar.php

https://gitlab.com/Marwamimo/Crowdrise_Web
PHP | 559 lines | 320 code | 67 blank | 172 comment | 35 complexity | d85db95d2f65c90e5651dd86d0de33b2 MD5 | raw file
  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\NullOutput;
  12. use Symfony\Component\Console\Output\OutputInterface;
  13. /**
  14. * The ProgressBar provides helpers to display progress output.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. * @author Chris Jones <leeked@gmail.com>
  18. */
  19. class ProgressBar
  20. {
  21. // options
  22. private $barWidth = 28;
  23. private $barChar = '=';
  24. private $emptyBarChar = '-';
  25. private $progressChar = '>';
  26. private $format = null;
  27. private $redrawFreq = 1;
  28. /**
  29. * @var OutputInterface
  30. */
  31. private $output;
  32. private $step;
  33. private $max;
  34. private $startTime;
  35. private $stepWidth;
  36. private $percent;
  37. private $lastMessagesLength;
  38. private $barCharOriginal;
  39. private $formatLineCount;
  40. private $messages;
  41. private static $formatters;
  42. private static $formats;
  43. /**
  44. * Constructor.
  45. *
  46. * @param OutputInterface $output An OutputInterface instance
  47. * @param int $max Maximum steps (0 if unknown)
  48. */
  49. public function __construct(OutputInterface $output, $max = 0)
  50. {
  51. // Disabling output when it does not support ANSI codes as it would result in a broken display anyway.
  52. $this->output = $output->isDecorated() ? $output : new NullOutput();
  53. $this->max = (int) $max;
  54. $this->stepWidth = $this->max > 0 ? Helper::strlen($this->max) : 4;
  55. if (!self::$formatters) {
  56. self::$formatters = self::initPlaceholderFormatters();
  57. }
  58. if (!self::$formats) {
  59. self::$formats = self::initFormats();
  60. }
  61. $this->setFormat($this->determineBestFormat());
  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. * @return int The progress bar step
  151. */
  152. public function getStep()
  153. {
  154. return $this->step;
  155. }
  156. /**
  157. * Gets the progress bar step width.
  158. *
  159. * @return int The progress bar step width
  160. */
  161. public function getStepWidth()
  162. {
  163. return $this->stepWidth;
  164. }
  165. /**
  166. * Gets the current progress bar percent.
  167. *
  168. * @return int The current progress bar percent
  169. */
  170. public function getProgressPercent()
  171. {
  172. return $this->percent;
  173. }
  174. /**
  175. * Sets the progress bar width.
  176. *
  177. * @param int $size The progress bar size
  178. */
  179. public function setBarWidth($size)
  180. {
  181. $this->barWidth = (int) $size;
  182. }
  183. /**
  184. * Gets the progress bar width.
  185. *
  186. * @return int The progress bar size
  187. */
  188. public function getBarWidth()
  189. {
  190. return $this->barWidth;
  191. }
  192. /**
  193. * Sets the bar character.
  194. *
  195. * @param string $char A character
  196. */
  197. public function setBarCharacter($char)
  198. {
  199. $this->barChar = $char;
  200. }
  201. /**
  202. * Gets the bar character.
  203. *
  204. * @return string A character
  205. */
  206. public function getBarCharacter()
  207. {
  208. return $this->barChar;
  209. }
  210. /**
  211. * Sets the empty bar character.
  212. *
  213. * @param string $char A character
  214. */
  215. public function setEmptyBarCharacter($char)
  216. {
  217. $this->emptyBarChar = $char;
  218. }
  219. /**
  220. * Gets the empty bar character.
  221. *
  222. * @return string A character
  223. */
  224. public function getEmptyBarCharacter()
  225. {
  226. return $this->emptyBarChar;
  227. }
  228. /**
  229. * Sets the progress bar character.
  230. *
  231. * @param string $char A character
  232. */
  233. public function setProgressCharacter($char)
  234. {
  235. $this->progressChar = $char;
  236. }
  237. /**
  238. * Gets the progress bar character.
  239. *
  240. * @return string A character
  241. */
  242. public function getProgressCharacter()
  243. {
  244. return $this->progressChar;
  245. }
  246. /**
  247. * Sets the progress bar format.
  248. *
  249. * @param string $format The format
  250. */
  251. public function setFormat($format)
  252. {
  253. // try to use the _nomax variant if available
  254. if (!$this->max && isset(self::$formats[$format.'_nomax'])) {
  255. $this->format = self::$formats[$format.'_nomax'];
  256. } elseif (isset(self::$formats[$format])) {
  257. $this->format = self::$formats[$format];
  258. } else {
  259. $this->format = $format;
  260. }
  261. $this->formatLineCount = substr_count($this->format, "\n");
  262. }
  263. /**
  264. * Sets the redraw frequency.
  265. *
  266. * @param int $freq The frequency in steps
  267. */
  268. public function setRedrawFrequency($freq)
  269. {
  270. $this->redrawFreq = (int) $freq;
  271. }
  272. /**
  273. * Starts the progress output.
  274. */
  275. public function start()
  276. {
  277. $this->startTime = time();
  278. $this->step = 0;
  279. $this->percent = 0;
  280. $this->lastMessagesLength = 0;
  281. $this->barCharOriginal = '';
  282. if (!$this->max) {
  283. $this->barCharOriginal = $this->barChar;
  284. $this->barChar = $this->emptyBarChar;
  285. }
  286. $this->display();
  287. }
  288. /**
  289. * Advances the progress output X steps.
  290. *
  291. * @param int $step Number of steps to advance
  292. *
  293. * @throws \LogicException
  294. */
  295. public function advance($step = 1)
  296. {
  297. $this->setCurrent($this->step + $step);
  298. }
  299. /**
  300. * Sets the current progress.
  301. *
  302. * @param int $step The current progress
  303. *
  304. * @throws \LogicException
  305. */
  306. public function setCurrent($step)
  307. {
  308. if (null === $this->startTime) {
  309. throw new \LogicException('You must start the progress bar before calling setCurrent().');
  310. }
  311. $step = (int) $step;
  312. if ($step < $this->step) {
  313. throw new \LogicException('You can\'t regress the progress bar.');
  314. }
  315. if ($this->max > 0 && $step > $this->max) {
  316. throw new \LogicException('You can\'t advance the progress bar past the max value.');
  317. }
  318. $prevPeriod = intval($this->step / $this->redrawFreq);
  319. $currPeriod = intval($step / $this->redrawFreq);
  320. $this->step = $step;
  321. $this->percent = $this->max > 0 ? (float) $this->step / $this->max : 0;
  322. if ($prevPeriod !== $currPeriod || $this->max === $step) {
  323. $this->display();
  324. }
  325. }
  326. /**
  327. * Finishes the progress output.
  328. */
  329. public function finish()
  330. {
  331. if (null === $this->startTime) {
  332. throw new \LogicException('You must start the progress bar before calling finish().');
  333. }
  334. if (!$this->max) {
  335. $this->barChar = $this->barCharOriginal;
  336. $this->max = $this->step;
  337. $this->setCurrent($this->max);
  338. $this->max = 0;
  339. $this->barChar = $this->emptyBarChar;
  340. } else {
  341. $this->setCurrent($this->max);
  342. }
  343. $this->startTime = null;
  344. }
  345. /**
  346. * Outputs the current progress string.
  347. *
  348. * @throws \LogicException
  349. */
  350. public function display()
  351. {
  352. if (null === $this->startTime) {
  353. throw new \LogicException('You must start the progress bar before calling display().');
  354. }
  355. // these 3 variables can be removed in favor of using $this in the closure when support for PHP 5.3 will be dropped.
  356. $self = $this;
  357. $output = $this->output;
  358. $messages = $this->messages;
  359. $this->overwrite(preg_replace_callback("{%([a-z\-_]+)(?:\:([^%]+))?%}i", function ($matches) use ($self, $output, $messages) {
  360. if ($formatter = $self::getPlaceholderFormatterDefinition($matches[1])) {
  361. $text = call_user_func($formatter, $self, $output);
  362. } elseif (isset($messages[$matches[1]])) {
  363. $text = $messages[$matches[1]];
  364. } else {
  365. return $matches[0];
  366. }
  367. if (isset($matches[2])) {
  368. $text = sprintf('%'.$matches[2], $text);
  369. }
  370. return $text;
  371. }, $this->format));
  372. }
  373. /**
  374. * Removes the progress bar from the current line.
  375. *
  376. * This is useful if you wish to write some output
  377. * while a progress bar is running.
  378. * Call display() to show the progress bar again.
  379. */
  380. public function clear()
  381. {
  382. $this->overwrite(str_repeat("\n", $this->formatLineCount));
  383. }
  384. /**
  385. * Overwrites a previous message to the output.
  386. *
  387. * @param string $message The message
  388. */
  389. private function overwrite($message)
  390. {
  391. $lines = explode("\n", $message);
  392. // append whitespace to match the line's length
  393. if (null !== $this->lastMessagesLength) {
  394. foreach ($lines as $i => $line) {
  395. if ($this->lastMessagesLength > Helper::strlenWithoutDecoration($this->output->getFormatter(), $line)) {
  396. $lines[$i] = str_pad($line, $this->lastMessagesLength, "\x20", STR_PAD_RIGHT);
  397. }
  398. }
  399. }
  400. // move back to the beginning of the progress bar before redrawing it
  401. $this->output->write("\x0D");
  402. if ($this->formatLineCount) {
  403. $this->output->write(sprintf("\033[%dA", $this->formatLineCount));
  404. }
  405. $this->output->write(implode("\n", $lines));
  406. $this->lastMessagesLength = 0;
  407. foreach ($lines as $line) {
  408. $len = Helper::strlenWithoutDecoration($this->output->getFormatter(), $line);
  409. if ($len > $this->lastMessagesLength) {
  410. $this->lastMessagesLength = $len;
  411. }
  412. }
  413. }
  414. private function determineBestFormat()
  415. {
  416. switch ($this->output->getVerbosity()) {
  417. // OutputInterface::VERBOSITY_QUIET: display is disabled anyway
  418. case OutputInterface::VERBOSITY_VERBOSE:
  419. return $this->max > 0 ? 'verbose' : 'verbose_nomax';
  420. case OutputInterface::VERBOSITY_VERY_VERBOSE:
  421. return $this->max > 0 ? 'very_verbose' : 'very_verbose_nomax';
  422. case OutputInterface::VERBOSITY_DEBUG:
  423. return $this->max > 0 ? 'debug' : 'debug_nomax';
  424. default:
  425. return $this->max > 0 ? 'normal' : 'normal_nomax';
  426. }
  427. }
  428. private static function initPlaceholderFormatters()
  429. {
  430. return array(
  431. 'bar' => function (ProgressBar $bar, OutputInterface $output) {
  432. $completeBars = floor($bar->getMaxSteps() > 0 ? $bar->getProgressPercent() * $bar->getBarWidth() : $bar->getStep() % $bar->getBarWidth());
  433. $display = str_repeat($bar->getBarCharacter(), $completeBars);
  434. if ($completeBars < $bar->getBarWidth()) {
  435. $emptyBars = $bar->getBarWidth() - $completeBars - Helper::strlenWithoutDecoration($output->getFormatter(), $bar->getProgressCharacter());
  436. $display .= $bar->getProgressCharacter().str_repeat($bar->getEmptyBarCharacter(), $emptyBars);
  437. }
  438. return $display;
  439. },
  440. 'elapsed' => function (ProgressBar $bar) {
  441. return Helper::formatTime(time() - $bar->getStartTime());
  442. },
  443. 'remaining' => function (ProgressBar $bar) {
  444. if (!$bar->getMaxSteps()) {
  445. throw new \LogicException('Unable to display the remaining time if the maximum number of steps is not set.');
  446. }
  447. if (!$bar->getStep()) {
  448. $remaining = 0;
  449. } else {
  450. $remaining = round((time() - $bar->getStartTime()) / $bar->getStep() * ($bar->getMaxSteps() - $bar->getStep()));
  451. }
  452. return Helper::formatTime($remaining);
  453. },
  454. 'estimated' => function (ProgressBar $bar) {
  455. if (!$bar->getMaxSteps()) {
  456. throw new \LogicException('Unable to display the estimated time if the maximum number of steps is not set.');
  457. }
  458. if (!$bar->getStep()) {
  459. $estimated = 0;
  460. } else {
  461. $estimated = round((time() - $bar->getStartTime()) / $bar->getStep() * $bar->getMaxSteps());
  462. }
  463. return Helper::formatTime($estimated);
  464. },
  465. 'memory' => function (ProgressBar $bar) {
  466. return Helper::formatMemory(memory_get_usage(true));
  467. },
  468. 'current' => function (ProgressBar $bar) {
  469. return str_pad($bar->getStep(), $bar->getStepWidth(), ' ', STR_PAD_LEFT);
  470. },
  471. 'max' => function (ProgressBar $bar) {
  472. return $bar->getMaxSteps();
  473. },
  474. 'percent' => function (ProgressBar $bar) {
  475. return floor($bar->getProgressPercent() * 100);
  476. },
  477. );
  478. }
  479. private static function initFormats()
  480. {
  481. return array(
  482. 'normal' => ' %current%/%max% [%bar%] %percent:3s%%',
  483. 'normal_nomax' => ' %current% [%bar%]',
  484. 'verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%',
  485. 'verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
  486. 'very_verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%',
  487. 'very_verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
  488. 'debug' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%',
  489. 'debug_nomax' => ' %current% [%bar%] %elapsed:6s% %memory:6s%',
  490. );
  491. }
  492. }