ProgressHelper.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. * The Progress class provides helpers to display progress output.
  14. *
  15. * @author Chris Jones <leeked@gmail.com>
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. */
  18. class ProgressHelper extends Helper
  19. {
  20. const FORMAT_QUIET = ' %percent%%';
  21. const FORMAT_NORMAL = ' %current%/%max% [%bar%] %percent%%';
  22. const FORMAT_VERBOSE = ' %current%/%max% [%bar%] %percent%% Elapsed: %elapsed%';
  23. const FORMAT_QUIET_NOMAX = ' %current%';
  24. const FORMAT_NORMAL_NOMAX = ' %current% [%bar%]';
  25. const FORMAT_VERBOSE_NOMAX = ' %current% [%bar%] Elapsed: %elapsed%';
  26. // options
  27. private $barWidth = 28;
  28. private $barChar = '=';
  29. private $emptyBarChar = '-';
  30. private $progressChar = '>';
  31. private $format = null;
  32. private $redrawFreq = 1;
  33. private $lastMessagesLength;
  34. private $barCharOriginal;
  35. /**
  36. * @var OutputInterface
  37. */
  38. private $output;
  39. /**
  40. * Current step
  41. *
  42. * @var integer
  43. */
  44. private $current;
  45. /**
  46. * Maximum number of steps
  47. *
  48. * @var integer
  49. */
  50. private $max;
  51. /**
  52. * Start time of the progress bar
  53. *
  54. * @var integer
  55. */
  56. private $startTime;
  57. /**
  58. * List of formatting variables
  59. *
  60. * @var array
  61. */
  62. private $defaultFormatVars = array(
  63. 'current',
  64. 'max',
  65. 'bar',
  66. 'percent',
  67. 'elapsed',
  68. );
  69. /**
  70. * Available formatting variables
  71. *
  72. * @var array
  73. */
  74. private $formatVars;
  75. /**
  76. * Stored format part widths (used for padding)
  77. *
  78. * @var array
  79. */
  80. private $widths = array(
  81. 'current' => 4,
  82. 'max' => 4,
  83. 'percent' => 3,
  84. 'elapsed' => 6,
  85. );
  86. /**
  87. * Various time formats
  88. *
  89. * @var array
  90. */
  91. private $timeFormats = array(
  92. array(0, '???'),
  93. array(2, '1 sec'),
  94. array(59, 'secs', 1),
  95. array(60, '1 min'),
  96. array(3600, 'mins', 60),
  97. array(5400, '1 hr'),
  98. array(86400, 'hrs', 3600),
  99. array(129600, '1 day'),
  100. array(604800, 'days', 86400),
  101. );
  102. /**
  103. * Sets the progress bar width.
  104. *
  105. * @param int $size The progress bar size
  106. */
  107. public function setBarWidth($size)
  108. {
  109. $this->barWidth = (int) $size;
  110. }
  111. /**
  112. * Sets the bar character.
  113. *
  114. * @param string $char A character
  115. */
  116. public function setBarCharacter($char)
  117. {
  118. $this->barChar = $char;
  119. }
  120. /**
  121. * Sets the empty bar character.
  122. *
  123. * @param string $char A character
  124. */
  125. public function setEmptyBarCharacter($char)
  126. {
  127. $this->emptyBarChar = $char;
  128. }
  129. /**
  130. * Sets the progress bar character.
  131. *
  132. * @param string $char A character
  133. */
  134. public function setProgressCharacter($char)
  135. {
  136. $this->progressChar = $char;
  137. }
  138. /**
  139. * Sets the progress bar format.
  140. *
  141. * @param string $format The format
  142. */
  143. public function setFormat($format)
  144. {
  145. $this->format = $format;
  146. }
  147. /**
  148. * Sets the redraw frequency.
  149. *
  150. * @param int $freq The frequency in steps
  151. */
  152. public function setRedrawFrequency($freq)
  153. {
  154. $this->redrawFreq = (int) $freq;
  155. }
  156. /**
  157. * Starts the progress output.
  158. *
  159. * @param OutputInterface $output An Output instance
  160. * @param integer $max Maximum steps
  161. */
  162. public function start(OutputInterface $output, $max = null)
  163. {
  164. $this->startTime = time();
  165. $this->current = 0;
  166. $this->max = (int) $max;
  167. $this->output = $output;
  168. $this->lastMessagesLength = 0;
  169. $this->barCharOriginal = '';
  170. if (null === $this->format) {
  171. switch ($output->getVerbosity()) {
  172. case OutputInterface::VERBOSITY_QUIET:
  173. $this->format = self::FORMAT_QUIET_NOMAX;
  174. if ($this->max > 0) {
  175. $this->format = self::FORMAT_QUIET;
  176. }
  177. break;
  178. case OutputInterface::VERBOSITY_VERBOSE:
  179. case OutputInterface::VERBOSITY_VERY_VERBOSE:
  180. case OutputInterface::VERBOSITY_DEBUG:
  181. $this->format = self::FORMAT_VERBOSE_NOMAX;
  182. if ($this->max > 0) {
  183. $this->format = self::FORMAT_VERBOSE;
  184. }
  185. break;
  186. default:
  187. $this->format = self::FORMAT_NORMAL_NOMAX;
  188. if ($this->max > 0) {
  189. $this->format = self::FORMAT_NORMAL;
  190. }
  191. break;
  192. }
  193. }
  194. $this->initialize();
  195. }
  196. /**
  197. * Advances the progress output X steps.
  198. *
  199. * @param integer $step Number of steps to advance
  200. * @param Boolean $redraw Whether to redraw or not
  201. *
  202. * @throws \LogicException
  203. */
  204. public function advance($step = 1, $redraw = false)
  205. {
  206. if (null === $this->startTime) {
  207. throw new \LogicException('You must start the progress bar before calling advance().');
  208. }
  209. if (0 === $this->current) {
  210. $redraw = true;
  211. }
  212. $this->current += $step;
  213. if ($redraw || 0 === $this->current % $this->redrawFreq) {
  214. $this->display();
  215. }
  216. }
  217. /**
  218. * Sets the current progress.
  219. *
  220. * @param integer $current The current progress
  221. * @param Boolean $redraw Whether to redraw or not
  222. *
  223. * @throws \LogicException
  224. */
  225. public function setCurrent($current, $redraw = false)
  226. {
  227. if (null === $this->startTime) {
  228. throw new \LogicException('You must start the progress bar before calling setCurrent().');
  229. }
  230. $current = (int) $current;
  231. if ($current < $this->current) {
  232. throw new \LogicException('You can\'t regress the progress bar');
  233. }
  234. if (0 === $this->current) {
  235. $redraw = true;
  236. }
  237. $this->current = $current;
  238. if ($redraw || 0 === $this->current % $this->redrawFreq) {
  239. $this->display();
  240. }
  241. }
  242. /**
  243. * Outputs the current progress string.
  244. *
  245. * @param Boolean $finish Forces the end result
  246. *
  247. * @throws \LogicException
  248. */
  249. public function display($finish = false)
  250. {
  251. if (null === $this->startTime) {
  252. throw new \LogicException('You must start the progress bar before calling display().');
  253. }
  254. $message = $this->format;
  255. foreach ($this->generate($finish) as $name => $value) {
  256. $message = str_replace("%{$name}%", $value, $message);
  257. }
  258. $this->overwrite($this->output, $message);
  259. }
  260. /**
  261. * Finishes the progress output.
  262. */
  263. public function finish()
  264. {
  265. if (null === $this->startTime) {
  266. throw new \LogicException('You must start the progress bar before calling finish().');
  267. }
  268. if (null !== $this->startTime) {
  269. if (!$this->max) {
  270. $this->barChar = $this->barCharOriginal;
  271. $this->display(true);
  272. }
  273. $this->startTime = null;
  274. $this->output->writeln('');
  275. $this->output = null;
  276. }
  277. }
  278. /**
  279. * Initializes the progress helper.
  280. */
  281. private function initialize()
  282. {
  283. $this->formatVars = array();
  284. foreach ($this->defaultFormatVars as $var) {
  285. if (false !== strpos($this->format, "%{$var}%")) {
  286. $this->formatVars[$var] = true;
  287. }
  288. }
  289. if ($this->max > 0) {
  290. $this->widths['max'] = $this->strlen($this->max);
  291. $this->widths['current'] = $this->widths['max'];
  292. } else {
  293. $this->barCharOriginal = $this->barChar;
  294. $this->barChar = $this->emptyBarChar;
  295. }
  296. }
  297. /**
  298. * Generates the array map of format variables to values.
  299. *
  300. * @param Boolean $finish Forces the end result
  301. *
  302. * @return array Array of format vars and values
  303. */
  304. private function generate($finish = false)
  305. {
  306. $vars = array();
  307. $percent = 0;
  308. if ($this->max > 0) {
  309. $percent = (double) $this->current / $this->max;
  310. }
  311. if (isset($this->formatVars['bar'])) {
  312. $completeBars = 0;
  313. if ($this->max > 0) {
  314. $completeBars = floor($percent * $this->barWidth);
  315. } else {
  316. if (!$finish) {
  317. $completeBars = floor($this->current % $this->barWidth);
  318. } else {
  319. $completeBars = $this->barWidth;
  320. }
  321. }
  322. $emptyBars = $this->barWidth - $completeBars - $this->strlen($this->progressChar);
  323. $bar = str_repeat($this->barChar, $completeBars);
  324. if ($completeBars < $this->barWidth) {
  325. $bar .= $this->progressChar;
  326. $bar .= str_repeat($this->emptyBarChar, $emptyBars);
  327. }
  328. $vars['bar'] = $bar;
  329. }
  330. if (isset($this->formatVars['elapsed'])) {
  331. $elapsed = time() - $this->startTime;
  332. $vars['elapsed'] = str_pad($this->humaneTime($elapsed), $this->widths['elapsed'], ' ', STR_PAD_LEFT);
  333. }
  334. if (isset($this->formatVars['current'])) {
  335. $vars['current'] = str_pad($this->current, $this->widths['current'], ' ', STR_PAD_LEFT);
  336. }
  337. if (isset($this->formatVars['max'])) {
  338. $vars['max'] = $this->max;
  339. }
  340. if (isset($this->formatVars['percent'])) {
  341. $vars['percent'] = str_pad(floor($percent * 100), $this->widths['percent'], ' ', STR_PAD_LEFT);
  342. }
  343. return $vars;
  344. }
  345. /**
  346. * Converts seconds into human-readable format.
  347. *
  348. * @param integer $secs Number of seconds
  349. *
  350. * @return string Time in readable format
  351. */
  352. private function humaneTime($secs)
  353. {
  354. $text = '';
  355. foreach ($this->timeFormats as $format) {
  356. if ($secs < $format[0]) {
  357. if (count($format) == 2) {
  358. $text = $format[1];
  359. break;
  360. } else {
  361. $text = ceil($secs / $format[2]).' '.$format[1];
  362. break;
  363. }
  364. }
  365. }
  366. return $text;
  367. }
  368. /**
  369. * Overwrites a previous message to the output.
  370. *
  371. * @param OutputInterface $output An Output instance
  372. * @param string $message The message
  373. */
  374. private function overwrite(OutputInterface $output, $message)
  375. {
  376. $length = $this->strlen($message);
  377. // append whitespace to match the last line's length
  378. if (null !== $this->lastMessagesLength && $this->lastMessagesLength > $length) {
  379. $message = str_pad($message, $this->lastMessagesLength, "\x20", STR_PAD_RIGHT);
  380. }
  381. // carriage return
  382. $output->write("\x0D");
  383. $output->write($message);
  384. $this->lastMessagesLength = $this->strlen($message);
  385. }
  386. /**
  387. * {@inheritDoc}
  388. */
  389. public function getName()
  390. {
  391. return 'progress';
  392. }
  393. }