ProgressIndicator.php 7.5 KB

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