ProgressIndicator.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 $startTime;
  29. private $format;
  30. private $message;
  31. private $indicatorValues;
  32. private $indicatorCurrent;
  33. private $indicatorChangeInterval;
  34. private $indicatorUpdateTime;
  35. private $started = false;
  36. /**
  37. * @var array<string, callable>
  38. */
  39. private static $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. * @return string|null
  123. */
  124. public static function getFormatDefinition(string $name)
  125. {
  126. return self::FORMATS[$name] ?? null;
  127. }
  128. /**
  129. * Sets a placeholder formatter for a given name.
  130. *
  131. * This method also allow you to override an existing placeholder.
  132. */
  133. public static function setPlaceholderFormatterDefinition(string $name, callable $callable)
  134. {
  135. if (!self::$formatters) {
  136. self::$formatters = self::initPlaceholderFormatters();
  137. }
  138. self::$formatters[$name] = $callable;
  139. }
  140. /**
  141. * Gets the placeholder formatter for a given name (including the delimiter char like %).
  142. *
  143. * @return callable|null
  144. */
  145. public static function getPlaceholderFormatterDefinition(string $name)
  146. {
  147. if (!self::$formatters) {
  148. self::$formatters = self::initPlaceholderFormatters();
  149. }
  150. return self::$formatters[$name] ?? null;
  151. }
  152. private function display()
  153. {
  154. if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) {
  155. return;
  156. }
  157. $this->overwrite(preg_replace_callback("{%([a-z\-_]+)(?:\:([^%]+))?%}i", function ($matches) {
  158. if ($formatter = self::getPlaceholderFormatterDefinition($matches[1])) {
  159. return $formatter($this);
  160. }
  161. return $matches[0];
  162. }, $this->format ?? ''));
  163. }
  164. private function determineBestFormat(): string
  165. {
  166. switch ($this->output->getVerbosity()) {
  167. // OutputInterface::VERBOSITY_QUIET: display is disabled anyway
  168. case OutputInterface::VERBOSITY_VERBOSE:
  169. return $this->output->isDecorated() ? 'verbose' : 'verbose_no_ansi';
  170. case OutputInterface::VERBOSITY_VERY_VERBOSE:
  171. case OutputInterface::VERBOSITY_DEBUG:
  172. return $this->output->isDecorated() ? 'very_verbose' : 'very_verbose_no_ansi';
  173. default:
  174. return $this->output->isDecorated() ? 'normal' : 'normal_no_ansi';
  175. }
  176. }
  177. /**
  178. * Overwrites a previous message to the output.
  179. */
  180. private function overwrite(string $message)
  181. {
  182. if ($this->output->isDecorated()) {
  183. $this->output->write("\x0D\x1B[2K");
  184. $this->output->write($message);
  185. } else {
  186. $this->output->writeln($message);
  187. }
  188. }
  189. private function getCurrentTimeInMilliseconds(): float
  190. {
  191. return round(microtime(true) * 1000);
  192. }
  193. private static function initPlaceholderFormatters(): array
  194. {
  195. return [
  196. 'indicator' => function (self $indicator) {
  197. return $indicator->indicatorValues[$indicator->indicatorCurrent % \count($indicator->indicatorValues)];
  198. },
  199. 'message' => function (self $indicator) {
  200. return $indicator->message;
  201. },
  202. 'elapsed' => function (self $indicator) {
  203. return Helper::formatTime(time() - $indicator->startTime);
  204. },
  205. 'memory' => function () {
  206. return Helper::formatMemory(memory_get_usage(true));
  207. },
  208. ];
  209. }
  210. }