SymfonyStyle.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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\Style;
  11. use Symfony\Component\Console\Application;
  12. use Symfony\Component\Console\Exception\RuntimeException;
  13. use Symfony\Component\Console\Formatter\OutputFormatter;
  14. use Symfony\Component\Console\Helper\Helper;
  15. use Symfony\Component\Console\Helper\ProgressBar;
  16. use Symfony\Component\Console\Helper\SymfonyQuestionHelper;
  17. use Symfony\Component\Console\Helper\Table;
  18. use Symfony\Component\Console\Input\InputInterface;
  19. use Symfony\Component\Console\Output\BufferedOutput;
  20. use Symfony\Component\Console\Output\OutputInterface;
  21. use Symfony\Component\Console\Question\ChoiceQuestion;
  22. use Symfony\Component\Console\Question\ConfirmationQuestion;
  23. use Symfony\Component\Console\Question\Question;
  24. /**
  25. * Output decorator helpers for the Symfony Style Guide.
  26. *
  27. * @author Kevin Bond <kevinbond@gmail.com>
  28. */
  29. class SymfonyStyle extends OutputStyle
  30. {
  31. const MAX_LINE_LENGTH = 120;
  32. private $input;
  33. private $questionHelper;
  34. private $progressBar;
  35. private $lineLength;
  36. private $bufferedOutput;
  37. public function __construct(InputInterface $input, OutputInterface $output)
  38. {
  39. $this->input = $input;
  40. $this->bufferedOutput = new BufferedOutput($output->getVerbosity(), false, clone $output->getFormatter());
  41. // Windows cmd wraps lines as soon as the terminal width is reached, whether there are following chars or not.
  42. $this->lineLength = min($this->getTerminalWidth() - (int) (DIRECTORY_SEPARATOR === '\\'), self::MAX_LINE_LENGTH);
  43. parent::__construct($output);
  44. }
  45. /**
  46. * Formats a message as a block of text.
  47. *
  48. * @param string|array $messages The message to write in the block
  49. * @param string|null $type The block type (added in [] on first line)
  50. * @param string|null $style The style to apply to the whole block
  51. * @param string $prefix The prefix for the block
  52. * @param bool $padding Whether to add vertical padding
  53. */
  54. public function block($messages, $type = null, $style = null, $prefix = ' ', $padding = false)
  55. {
  56. $messages = is_array($messages) ? array_values($messages) : array($messages);
  57. $this->autoPrependBlock();
  58. $this->writeln($this->createBlock($messages, $type, $style, $prefix, $padding, true));
  59. $this->newLine();
  60. }
  61. /**
  62. * {@inheritdoc}
  63. */
  64. public function title($message)
  65. {
  66. $this->autoPrependBlock();
  67. $this->writeln(array(
  68. sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
  69. sprintf('<comment>%s</>', str_repeat('=', Helper::strlenWithoutDecoration($this->getFormatter(), $message))),
  70. ));
  71. $this->newLine();
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function section($message)
  77. {
  78. $this->autoPrependBlock();
  79. $this->writeln(array(
  80. sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
  81. sprintf('<comment>%s</>', str_repeat('-', Helper::strlenWithoutDecoration($this->getFormatter(), $message))),
  82. ));
  83. $this->newLine();
  84. }
  85. /**
  86. * {@inheritdoc}
  87. */
  88. public function listing(array $elements)
  89. {
  90. $this->autoPrependText();
  91. $elements = array_map(function ($element) {
  92. return sprintf(' * %s', $element);
  93. }, $elements);
  94. $this->writeln($elements);
  95. $this->newLine();
  96. }
  97. /**
  98. * {@inheritdoc}
  99. */
  100. public function text($message)
  101. {
  102. $this->autoPrependText();
  103. $messages = is_array($message) ? array_values($message) : array($message);
  104. foreach ($messages as $message) {
  105. $this->writeln(sprintf(' %s', $message));
  106. }
  107. }
  108. /**
  109. * Formats a command comment.
  110. *
  111. * @param string|array $message
  112. */
  113. public function comment($message)
  114. {
  115. $messages = is_array($message) ? array_values($message) : array($message);
  116. $this->autoPrependBlock();
  117. $this->writeln($this->createBlock($messages, null, null, '<fg=default;bg=default> // </>'));
  118. $this->newLine();
  119. }
  120. /**
  121. * {@inheritdoc}
  122. */
  123. public function success($message)
  124. {
  125. $this->block($message, 'OK', 'fg=black;bg=green', ' ', true);
  126. }
  127. /**
  128. * {@inheritdoc}
  129. */
  130. public function error($message)
  131. {
  132. $this->block($message, 'ERROR', 'fg=white;bg=red', ' ', true);
  133. }
  134. /**
  135. * {@inheritdoc}
  136. */
  137. public function warning($message)
  138. {
  139. $this->block($message, 'WARNING', 'fg=white;bg=red', ' ', true);
  140. }
  141. /**
  142. * {@inheritdoc}
  143. */
  144. public function note($message)
  145. {
  146. $this->block($message, 'NOTE', 'fg=yellow', ' ! ');
  147. }
  148. /**
  149. * {@inheritdoc}
  150. */
  151. public function caution($message)
  152. {
  153. $this->block($message, 'CAUTION', 'fg=white;bg=red', ' ! ', true);
  154. }
  155. /**
  156. * {@inheritdoc}
  157. */
  158. public function table(array $headers, array $rows)
  159. {
  160. $style = clone Table::getStyleDefinition('symfony-style-guide');
  161. $style->setCellHeaderFormat('<info>%s</info>');
  162. $table = new Table($this);
  163. $table->setHeaders($headers);
  164. $table->setRows($rows);
  165. $table->setStyle($style);
  166. $table->render();
  167. $this->newLine();
  168. }
  169. /**
  170. * {@inheritdoc}
  171. */
  172. public function ask($question, $default = null, $validator = null)
  173. {
  174. $question = new Question($question, $default);
  175. $question->setValidator($validator);
  176. return $this->askQuestion($question);
  177. }
  178. /**
  179. * {@inheritdoc}
  180. */
  181. public function askHidden($question, $validator = null)
  182. {
  183. $question = new Question($question);
  184. $question->setHidden(true);
  185. $question->setValidator($validator);
  186. return $this->askQuestion($question);
  187. }
  188. /**
  189. * {@inheritdoc}
  190. */
  191. public function confirm($question, $default = true)
  192. {
  193. return $this->askQuestion(new ConfirmationQuestion($question, $default));
  194. }
  195. /**
  196. * {@inheritdoc}
  197. */
  198. public function choice($question, array $choices, $default = null)
  199. {
  200. if (null !== $default) {
  201. $values = array_flip($choices);
  202. $default = $values[$default];
  203. }
  204. return $this->askQuestion(new ChoiceQuestion($question, $choices, $default));
  205. }
  206. /**
  207. * {@inheritdoc}
  208. */
  209. public function progressStart($max = 0)
  210. {
  211. $this->progressBar = $this->createProgressBar($max);
  212. $this->progressBar->start();
  213. }
  214. /**
  215. * {@inheritdoc}
  216. */
  217. public function progressAdvance($step = 1)
  218. {
  219. $this->getProgressBar()->advance($step);
  220. }
  221. /**
  222. * {@inheritdoc}
  223. */
  224. public function progressFinish()
  225. {
  226. $this->getProgressBar()->finish();
  227. $this->newLine(2);
  228. $this->progressBar = null;
  229. }
  230. /**
  231. * {@inheritdoc}
  232. */
  233. public function createProgressBar($max = 0)
  234. {
  235. $progressBar = parent::createProgressBar($max);
  236. if ('\\' !== DIRECTORY_SEPARATOR) {
  237. $progressBar->setEmptyBarCharacter('░'); // light shade character \u2591
  238. $progressBar->setProgressCharacter('');
  239. $progressBar->setBarCharacter('▓'); // dark shade character \u2593
  240. }
  241. return $progressBar;
  242. }
  243. /**
  244. * @return mixed
  245. */
  246. public function askQuestion(Question $question)
  247. {
  248. if ($this->input->isInteractive()) {
  249. $this->autoPrependBlock();
  250. }
  251. if (!$this->questionHelper) {
  252. $this->questionHelper = new SymfonyQuestionHelper();
  253. }
  254. $answer = $this->questionHelper->ask($this->input, $this, $question);
  255. if ($this->input->isInteractive()) {
  256. $this->newLine();
  257. $this->bufferedOutput->write("\n");
  258. }
  259. return $answer;
  260. }
  261. /**
  262. * {@inheritdoc}
  263. */
  264. public function writeln($messages, $type = self::OUTPUT_NORMAL)
  265. {
  266. parent::writeln($messages, $type);
  267. $this->bufferedOutput->writeln($this->reduceBuffer($messages), $type);
  268. }
  269. /**
  270. * {@inheritdoc}
  271. */
  272. public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
  273. {
  274. parent::write($messages, $newline, $type);
  275. $this->bufferedOutput->write($this->reduceBuffer($messages), $newline, $type);
  276. }
  277. /**
  278. * {@inheritdoc}
  279. */
  280. public function newLine($count = 1)
  281. {
  282. parent::newLine($count);
  283. $this->bufferedOutput->write(str_repeat("\n", $count));
  284. }
  285. /**
  286. * @return ProgressBar
  287. */
  288. private function getProgressBar()
  289. {
  290. if (!$this->progressBar) {
  291. throw new RuntimeException('The ProgressBar is not started.');
  292. }
  293. return $this->progressBar;
  294. }
  295. private function getTerminalWidth()
  296. {
  297. $application = new Application();
  298. $dimensions = $application->getTerminalDimensions();
  299. return $dimensions[0] ?: self::MAX_LINE_LENGTH;
  300. }
  301. private function autoPrependBlock()
  302. {
  303. $chars = substr(str_replace(PHP_EOL, "\n", $this->bufferedOutput->fetch()), -2);
  304. if (!isset($chars[0])) {
  305. return $this->newLine(); //empty history, so we should start with a new line.
  306. }
  307. //Prepend new line for each non LF chars (This means no blank line was output before)
  308. $this->newLine(2 - substr_count($chars, "\n"));
  309. }
  310. private function autoPrependText()
  311. {
  312. $fetched = $this->bufferedOutput->fetch();
  313. //Prepend new line if last char isn't EOL:
  314. if ("\n" !== substr($fetched, -1)) {
  315. $this->newLine();
  316. }
  317. }
  318. private function reduceBuffer($messages)
  319. {
  320. // We need to know if the two last chars are PHP_EOL
  321. // Preserve the last 4 chars inserted (PHP_EOL on windows is two chars) in the history buffer
  322. return array_map(function ($value) {
  323. return substr($value, -4);
  324. }, array_merge(array($this->bufferedOutput->fetch()), (array) $messages));
  325. }
  326. private function createBlock($messages, $type = null, $style = null, $prefix = ' ', $padding = false, $escape = false)
  327. {
  328. $indentLength = 0;
  329. $prefixLength = Helper::strlenWithoutDecoration($this->getFormatter(), $prefix);
  330. $lines = array();
  331. if (null !== $type) {
  332. $type = sprintf('[%s] ', $type);
  333. $indentLength = strlen($type);
  334. $lineIndentation = str_repeat(' ', $indentLength);
  335. }
  336. // wrap and add newlines for each element
  337. foreach ($messages as $key => $message) {
  338. if ($escape) {
  339. $message = OutputFormatter::escape($message);
  340. }
  341. $lines = array_merge($lines, explode(PHP_EOL, wordwrap($message, $this->lineLength - $prefixLength - $indentLength, PHP_EOL, true)));
  342. if (count($messages) > 1 && $key < count($messages) - 1) {
  343. $lines[] = '';
  344. }
  345. }
  346. $firstLineIndex = 0;
  347. if ($padding && $this->isDecorated()) {
  348. $firstLineIndex = 1;
  349. array_unshift($lines, '');
  350. $lines[] = '';
  351. }
  352. foreach ($lines as $i => &$line) {
  353. if (null !== $type) {
  354. $line = $firstLineIndex === $i ? $type.$line : $lineIndentation.$line;
  355. }
  356. $line = $prefix.$line;
  357. $line .= str_repeat(' ', $this->lineLength - Helper::strlenWithoutDecoration($this->getFormatter(), $line));
  358. if ($style) {
  359. $line = sprintf('<%s>%s</>', $style, $line);
  360. }
  361. }
  362. return $lines;
  363. }
  364. }