SymfonyStyle.php 11 KB

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