ProgressIndicator.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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, $format = null, $indicatorChangeInterval = 100, $indicatorValues = null)
  37. {
  38. $this->output = $output;
  39. if (null === $format) {
  40. $format = $this->determineBestFormat();
  41. }
  42. if (null === $indicatorValues) {
  43. $indicatorValues = array('-', '\\', '|', '/');
  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. * Gets the current indicator message.
  66. *
  67. * @return string|null
  68. *
  69. * @internal for PHP 5.3 compatibility
  70. */
  71. public function getMessage()
  72. {
  73. return $this->message;
  74. }
  75. /**
  76. * Gets the progress bar start time.
  77. *
  78. * @return int The progress bar start time
  79. *
  80. * @internal for PHP 5.3 compatibility
  81. */
  82. public function getStartTime()
  83. {
  84. return $this->startTime;
  85. }
  86. /**
  87. * Gets the current animated indicator character.
  88. *
  89. * @return string
  90. *
  91. * @internal for PHP 5.3 compatibility
  92. */
  93. public function getCurrentValue()
  94. {
  95. return $this->indicatorValues[$this->indicatorCurrent % count($this->indicatorValues)];
  96. }
  97. /**
  98. * Starts the indicator output.
  99. *
  100. * @param $message
  101. */
  102. public function start($message)
  103. {
  104. if ($this->started) {
  105. throw new LogicException('Progress indicator already started.');
  106. }
  107. $this->message = $message;
  108. $this->started = true;
  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. if ($this->output->isDecorated()) {
  225. $this->output->write("\x0D\x1B[2K");
  226. $this->output->write($message);
  227. } else {
  228. $this->output->writeln($message);
  229. }
  230. }
  231. private function getCurrentTimeInMilliseconds()
  232. {
  233. return round(microtime(true) * 1000);
  234. }
  235. private static function initPlaceholderFormatters()
  236. {
  237. return array(
  238. 'indicator' => function (ProgressIndicator $indicator) {
  239. return $indicator->getCurrentValue();
  240. },
  241. 'message' => function (ProgressIndicator $indicator) {
  242. return $indicator->getMessage();
  243. },
  244. 'elapsed' => function (ProgressIndicator $indicator) {
  245. return Helper::formatTime(time() - $indicator->getStartTime());
  246. },
  247. 'memory' => function () {
  248. return Helper::formatMemory(memory_get_usage(true));
  249. },
  250. );
  251. }
  252. private static function initFormats()
  253. {
  254. return array(
  255. 'normal' => ' %indicator% %message%',
  256. 'normal_no_ansi' => ' %message%',
  257. 'verbose' => ' %indicator% %message% (%elapsed:6s%)',
  258. 'verbose_no_ansi' => ' %message% (%elapsed:6s%)',
  259. 'very_verbose' => ' %indicator% %message% (%elapsed:6s%, %memory:6s%)',
  260. 'very_verbose_no_ansi' => ' %message% (%elapsed:6s%, %memory:6s%)',
  261. );
  262. }
  263. }