Aucune description

SymfonyStyle.php 12KB

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