PageRenderTime 61ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/console/Helper/ProgressBar.php

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