ProgressIndicator.php 7.7 KB

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