ProgressIndicator.php 7.4 KB

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