ConsoleOutput.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Console;
  16. use InvalidArgumentException;
  17. /**
  18. * Object wrapper for outputting information from a shell application.
  19. * Can be connected to any stream resource that can be used with fopen()
  20. *
  21. * Can generate colorized output on consoles that support it. There are a few
  22. * built in styles
  23. *
  24. * - `error` Error messages.
  25. * - `warning` Warning messages.
  26. * - `info` Informational messages.
  27. * - `comment` Additional text.
  28. * - `question` Magenta text used for user prompts
  29. *
  30. * By defining styles with addStyle() you can create custom console styles.
  31. *
  32. * ### Using styles in output
  33. *
  34. * You can format console output using tags with the name of the style to apply. From inside a shell object
  35. *
  36. * ```
  37. * $this->out('<warning>Overwrite:</warning> foo.php was overwritten.');
  38. * ```
  39. *
  40. * This would create orange 'Overwrite:' text, while the rest of the text would remain the normal color.
  41. * See ConsoleOutput::styles() to learn more about defining your own styles. Nested styles are not supported
  42. * at this time.
  43. */
  44. class ConsoleOutput
  45. {
  46. /**
  47. * Raw output constant - no modification of output text.
  48. *
  49. * @var int
  50. */
  51. const RAW = 0;
  52. /**
  53. * Plain output - tags will be stripped.
  54. *
  55. * @var int
  56. */
  57. const PLAIN = 1;
  58. /**
  59. * Color output - Convert known tags in to ANSI color escape codes.
  60. *
  61. * @var int
  62. */
  63. const COLOR = 2;
  64. /**
  65. * Constant for a newline.
  66. *
  67. * @var string
  68. */
  69. const LF = PHP_EOL;
  70. /**
  71. * File handle for output.
  72. *
  73. * @var resource
  74. */
  75. protected $_output;
  76. /**
  77. * The current output type.
  78. *
  79. * @see setOutputAs() For manipulation.
  80. * @var int
  81. */
  82. protected $_outputAs = self::COLOR;
  83. /**
  84. * text colors used in colored output.
  85. *
  86. * @var array
  87. */
  88. protected static $_foregroundColors = [
  89. 'black' => 30,
  90. 'red' => 31,
  91. 'green' => 32,
  92. 'yellow' => 33,
  93. 'blue' => 34,
  94. 'magenta' => 35,
  95. 'cyan' => 36,
  96. 'white' => 37
  97. ];
  98. /**
  99. * background colors used in colored output.
  100. *
  101. * @var array
  102. */
  103. protected static $_backgroundColors = [
  104. 'black' => 40,
  105. 'red' => 41,
  106. 'green' => 42,
  107. 'yellow' => 43,
  108. 'blue' => 44,
  109. 'magenta' => 45,
  110. 'cyan' => 46,
  111. 'white' => 47
  112. ];
  113. /**
  114. * Formatting options for colored output.
  115. *
  116. * @var array
  117. */
  118. protected static $_options = [
  119. 'bold' => 1,
  120. 'underline' => 4,
  121. 'blink' => 5,
  122. 'reverse' => 7,
  123. ];
  124. /**
  125. * Styles that are available as tags in console output.
  126. * You can modify these styles with ConsoleOutput::styles()
  127. *
  128. * @var array
  129. */
  130. protected static $_styles = [
  131. 'emergency' => ['text' => 'red'],
  132. 'alert' => ['text' => 'red'],
  133. 'critical' => ['text' => 'red'],
  134. 'error' => ['text' => 'red'],
  135. 'warning' => ['text' => 'yellow'],
  136. 'info' => ['text' => 'cyan'],
  137. 'debug' => ['text' => 'yellow'],
  138. 'success' => ['text' => 'green'],
  139. 'comment' => ['text' => 'blue'],
  140. 'question' => ['text' => 'magenta'],
  141. 'notice' => ['text' => 'cyan']
  142. ];
  143. /**
  144. * Construct the output object.
  145. *
  146. * Checks for a pretty console environment. Ansicon and ConEmu allows
  147. * pretty consoles on windows, and is supported.
  148. *
  149. * @param string $stream The identifier of the stream to write output to.
  150. */
  151. public function __construct($stream = 'php://stdout')
  152. {
  153. $this->_output = fopen($stream, 'wb');
  154. if ((DIRECTORY_SEPARATOR === '\\' && !(bool)env('ANSICON') && env('ConEmuANSI') !== 'ON') ||
  155. (function_exists('posix_isatty') && !posix_isatty($this->_output))
  156. ) {
  157. $this->_outputAs = self::PLAIN;
  158. }
  159. }
  160. /**
  161. * Outputs a single or multiple messages to stdout or stderr. If no parameters
  162. * are passed, outputs just a newline.
  163. *
  164. * @param string|array $message A string or an array of strings to output
  165. * @param int $newlines Number of newlines to append
  166. * @return int|bool The number of bytes returned from writing to output.
  167. */
  168. public function write($message, $newlines = 1)
  169. {
  170. if (is_array($message)) {
  171. $message = implode(static::LF, $message);
  172. }
  173. return $this->_write($this->styleText($message . str_repeat(static::LF, $newlines)));
  174. }
  175. /**
  176. * Apply styling to text.
  177. *
  178. * @param string $text Text with styling tags.
  179. * @return string String with color codes added.
  180. */
  181. public function styleText($text)
  182. {
  183. if ($this->_outputAs == static::RAW) {
  184. return $text;
  185. }
  186. if ($this->_outputAs == static::PLAIN) {
  187. $tags = implode('|', array_keys(static::$_styles));
  188. return preg_replace('#</?(?:' . $tags . ')>#', '', $text);
  189. }
  190. return preg_replace_callback(
  191. '/<(?P<tag>[a-z0-9-_]+)>(?P<text>.*?)<\/(\1)>/ims',
  192. [$this, '_replaceTags'],
  193. $text
  194. );
  195. }
  196. /**
  197. * Replace tags with color codes.
  198. *
  199. * @param array $matches An array of matches to replace.
  200. * @return string
  201. */
  202. protected function _replaceTags($matches)
  203. {
  204. /** @var array $style */
  205. $style = $this->styles($matches['tag']);
  206. if (empty($style)) {
  207. return '<' . $matches['tag'] . '>' . $matches['text'] . '</' . $matches['tag'] . '>';
  208. }
  209. $styleInfo = [];
  210. if (!empty($style['text']) && isset(static::$_foregroundColors[$style['text']])) {
  211. $styleInfo[] = static::$_foregroundColors[$style['text']];
  212. }
  213. if (!empty($style['background']) && isset(static::$_backgroundColors[$style['background']])) {
  214. $styleInfo[] = static::$_backgroundColors[$style['background']];
  215. }
  216. unset($style['text'], $style['background']);
  217. foreach ($style as $option => $value) {
  218. if ($value) {
  219. $styleInfo[] = static::$_options[$option];
  220. }
  221. }
  222. return "\033[" . implode(';', $styleInfo) . 'm' . $matches['text'] . "\033[0m";
  223. }
  224. /**
  225. * Writes a message to the output stream.
  226. *
  227. * @param string $message Message to write.
  228. * @return int|bool The number of bytes returned from writing to output.
  229. */
  230. protected function _write($message)
  231. {
  232. return fwrite($this->_output, $message);
  233. }
  234. /**
  235. * Get the current styles offered, or append new ones in.
  236. *
  237. * ### Get a style definition
  238. *
  239. * ```
  240. * $output->styles('error');
  241. * ```
  242. *
  243. * ### Get all the style definitions
  244. *
  245. * ```
  246. * $output->styles();
  247. * ```
  248. *
  249. * ### Create or modify an existing style
  250. *
  251. * ```
  252. * $output->styles('annoy', ['text' => 'purple', 'background' => 'yellow', 'blink' => true]);
  253. * ```
  254. *
  255. * ### Remove a style
  256. *
  257. * ```
  258. * $this->output->styles('annoy', false);
  259. * ```
  260. *
  261. * @param string|null $style The style to get or create.
  262. * @param array|false|null $definition The array definition of the style to change or create a style
  263. * or false to remove a style.
  264. * @return array|true|null If you are getting styles, the style or null will be returned. If you are creating/modifying
  265. * styles true will be returned.
  266. */
  267. public function styles($style = null, $definition = null)
  268. {
  269. if ($style === null && $definition === null) {
  270. return static::$_styles;
  271. }
  272. if (is_string($style) && $definition === null) {
  273. return isset(static::$_styles[$style]) ? static::$_styles[$style] : null;
  274. }
  275. if ($definition === false) {
  276. unset(static::$_styles[$style]);
  277. return true;
  278. }
  279. static::$_styles[$style] = $definition;
  280. return true;
  281. }
  282. /**
  283. * Get the output type on how formatting tags are treated.
  284. *
  285. * @return int
  286. */
  287. public function getOutputAs()
  288. {
  289. return $this->_outputAs;
  290. }
  291. /**
  292. * Set the output type on how formatting tags are treated.
  293. *
  294. * @param int $type The output type to use. Should be one of the class constants.
  295. * @return void
  296. * @throws \InvalidArgumentException in case of a not supported output type.
  297. */
  298. public function setOutputAs($type)
  299. {
  300. if (!in_array($type, [self::RAW, self::PLAIN, self::COLOR], true)) {
  301. throw new InvalidArgumentException(sprintf('Invalid output type "%s".', $type));
  302. }
  303. $this->_outputAs = $type;
  304. }
  305. /**
  306. * Get/Set the output type to use. The output type how formatting tags are treated.
  307. *
  308. * @deprecated 3.5.0 Use getOutputAs()/setOutputAs() instead.
  309. * @param int|null $type The output type to use. Should be one of the class constants.
  310. * @return int|null Either null or the value if getting.
  311. */
  312. public function outputAs($type = null)
  313. {
  314. deprecationWarning(
  315. 'ConsoleOutput::outputAs() is deprecated. ' .
  316. 'Use ConsoleOutput::setOutputAs()/getOutputAs() instead.'
  317. );
  318. if ($type === null) {
  319. return $this->_outputAs;
  320. }
  321. $this->_outputAs = $type;
  322. }
  323. /**
  324. * Clean up and close handles
  325. */
  326. public function __destruct()
  327. {
  328. if (is_resource($this->_output)) {
  329. fclose($this->_output);
  330. }
  331. }
  332. }