ProgressIndicator.php 7.0 KB

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