SymfonyStyle.php 11 KB

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