ProgressIndicator.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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\Exception\InvalidArgumentException;
  12. use Symfony\Component\Console\Exception\LogicException;
  13. use Symfony\Component\Console\Output\OutputInterface;
  14. /**
  15. * @author Kevin Bond <kevinbond@gmail.com>
  16. */
  17. class ProgressIndicator
  18. {
  19. private const FORMATS = [
  20. 'normal' => ' %indicator% %message%',
  21. 'normal_no_ansi' => ' %message%',
  22. 'verbose' => ' %indicator% %message% (%elapsed:6s%)',
  23. 'verbose_no_ansi' => ' %message% (%elapsed:6s%)',
  24. 'very_verbose' => ' %indicator% %message% (%elapsed:6s%, %memory:6s%)',
  25. 'very_verbose_no_ansi' => ' %message% (%elapsed:6s%, %memory:6s%)',
  26. ];
  27. private int $startTime;
  28. private ?string $format = null;
  29. private ?string $message = null;
  30. private array $indicatorValues;
  31. private int $indicatorCurrent;
  32. private float $indicatorUpdateTime;
  33. private bool $started = false;
  34. /**
  35. * @var array<string, callable>
  36. */
  37. private static array $formatters;
  38. /**
  39. * @param int $indicatorChangeInterval Change interval in milliseconds
  40. * @param array|null $indicatorValues Animated indicator characters
  41. */
  42. public function __construct(
  43. private OutputInterface $output,
  44. ?string $format = null,
  45. private int $indicatorChangeInterval = 100,
  46. ?array $indicatorValues = null,
  47. ) {
  48. $format ??= $this->determineBestFormat();
  49. $indicatorValues ??= ['-', '\\', '|', '/'];
  50. $indicatorValues = array_values($indicatorValues);
  51. if (2 > \count($indicatorValues)) {
  52. throw new InvalidArgumentException('Must have at least 2 indicator value characters.');
  53. }
  54. $this->format = self::getFormatDefinition($format);
  55. $this->indicatorValues = $indicatorValues;
  56. $this->startTime = time();
  57. }
  58. /**
  59. * Sets the current indicator message.
  60. */
  61. public function setMessage(?string $message): void
  62. {
  63. $this->message = $message;
  64. $this->display();
  65. }
  66. /**
  67. * Starts the indicator output.
  68. */
  69. public function start(string $message): void
  70. {
  71. if ($this->started) {
  72. throw new LogicException('Progress indicator already started.');
  73. }
  74. $this->message = $message;
  75. $this->started = true;
  76. $this->startTime = time();
  77. $this->indicatorUpdateTime = $this->getCurrentTimeInMilliseconds() + $this->indicatorChangeInterval;
  78. $this->indicatorCurrent = 0;
  79. $this->display();
  80. }
  81. /**
  82. * Advances the indicator.
  83. */
  84. public function advance(): void
  85. {
  86. if (!$this->started) {
  87. throw new LogicException('Progress indicator has not yet been started.');
  88. }
  89. if (!$this->output->isDecorated()) {
  90. return;
  91. }
  92. $currentTime = $this->getCurrentTimeInMilliseconds();
  93. if ($currentTime < $this->indicatorUpdateTime) {
  94. return;
  95. }
  96. $this->indicatorUpdateTime = $currentTime + $this->indicatorChangeInterval;
  97. ++$this->indicatorCurrent;
  98. $this->display();
  99. }
  100. /**
  101. * Finish the indicator with message.
  102. */
  103. public function finish(string $message): void
  104. {
  105. if (!$this->started) {
  106. throw new LogicException('Progress indicator has not yet been started.');
  107. }
  108. $this->message = $message;
  109. $this->display();
  110. $this->output->writeln('');
  111. $this->started = false;
  112. }
  113. /**
  114. * Gets the format for a given name.
  115. */
  116. public static function getFormatDefinition(string $name): ?string
  117. {
  118. return self::FORMATS[$name] ?? null;
  119. }
  120. /**
  121. * Sets a placeholder formatter for a given name.
  122. *
  123. * This method also allow you to override an existing placeholder.
  124. */
  125. public static function setPlaceholderFormatterDefinition(string $name, callable $callable): void
  126. {
  127. self::$formatters ??= self::initPlaceholderFormatters();
  128. self::$formatters[$name] = $callable;
  129. }
  130. /**
  131. * Gets the placeholder formatter for a given name (including the delimiter char like %).
  132. */
  133. public static function getPlaceholderFormatterDefinition(string $name): ?callable
  134. {
  135. self::$formatters ??= self::initPlaceholderFormatters();
  136. return self::$formatters[$name] ?? null;
  137. }
  138. private function display(): void
  139. {
  140. if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) {
  141. return;
  142. }
  143. $this->overwrite(preg_replace_callback("{%([a-z\-_]+)(?:\:([^%]+))?%}i", function ($matches) {
  144. if ($formatter = self::getPlaceholderFormatterDefinition($matches[1])) {
  145. return $formatter($this);
  146. }
  147. return $matches[0];
  148. }, $this->format ?? ''));
  149. }
  150. private function determineBestFormat(): string
  151. {
  152. return match ($this->output->getVerbosity()) {
  153. // OutputInterface::VERBOSITY_QUIET: display is disabled anyway
  154. OutputInterface::VERBOSITY_VERBOSE => $this->output->isDecorated() ? 'verbose' : 'verbose_no_ansi',
  155. OutputInterface::VERBOSITY_VERY_VERBOSE,
  156. OutputInterface::VERBOSITY_DEBUG => $this->output->isDecorated() ? 'very_verbose' : 'very_verbose_no_ansi',
  157. default => $this->output->isDecorated() ? 'normal' : 'normal_no_ansi',
  158. };
  159. }
  160. /**
  161. * Overwrites a previous message to the output.
  162. */
  163. private function overwrite(string $message): void
  164. {
  165. if ($this->output->isDecorated()) {
  166. $this->output->write("\x0D\x1B[2K");
  167. $this->output->write($message);
  168. } else {
  169. $this->output->writeln($message);
  170. }
  171. }
  172. private function getCurrentTimeInMilliseconds(): float
  173. {
  174. return round(microtime(true) * 1000);
  175. }
  176. /**
  177. * @return array<string, \Closure>
  178. */
  179. private static function initPlaceholderFormatters(): array
  180. {
  181. return [
  182. 'indicator' => fn (self $indicator) => $indicator->indicatorValues[$indicator->indicatorCurrent % \count($indicator->indicatorValues)],
  183. 'message' => fn (self $indicator) => $indicator->message,
  184. 'elapsed' => fn (self $indicator) => Helper::formatTime(time() - $indicator->startTime, 2),
  185. 'memory' => fn () => Helper::formatMemory(memory_get_usage(true)),
  186. ];
  187. }
  188. }