ProgressIndicator.php 7.5 KB

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