ProgressIndicator.php 9.0 KB

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