ConsoleOutput.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. <?php
  2. /**
  3. * ConsoleOutput file.
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @since CakePHP(tm) v 2.0
  15. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  16. */
  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. * `$this->out('<warning>Overwrite:</warning> foo.php was overwritten.');`
  37. *
  38. * This would create orange 'Overwrite:' text, while the rest of the text would remain the normal color.
  39. * See ConsoleOutput::styles() to learn more about defining your own styles. Nested styles are not supported
  40. * at this time.
  41. *
  42. * @package Cake.Console
  43. */
  44. class ConsoleOutput {
  45. /**
  46. * Raw output constant - no modification of output text.
  47. *
  48. * @var integer
  49. */
  50. const RAW = 0;
  51. /**
  52. * Plain output - tags will be stripped.
  53. *
  54. * @var integer
  55. */
  56. const PLAIN = 1;
  57. /**
  58. * Color output - Convert known tags in to ANSI color escape codes.
  59. *
  60. * @var integer
  61. */
  62. const COLOR = 2;
  63. /**
  64. * Constant for a newline.
  65. *
  66. * @var string
  67. */
  68. const LF = PHP_EOL;
  69. /**
  70. * File handle for output.
  71. *
  72. * @var resource
  73. */
  74. protected $_output;
  75. /**
  76. * The current output type. Manipulated with ConsoleOutput::outputAs();
  77. *
  78. * @var integer
  79. */
  80. protected $_outputAs = self::COLOR;
  81. /**
  82. * text colors used in colored output.
  83. *
  84. * @var array
  85. */
  86. protected static $_foregroundColors = array(
  87. 'black' => 30,
  88. 'red' => 31,
  89. 'green' => 32,
  90. 'yellow' => 33,
  91. 'blue' => 34,
  92. 'magenta' => 35,
  93. 'cyan' => 36,
  94. 'white' => 37
  95. );
  96. /**
  97. * background colors used in colored output.
  98. *
  99. * @var array
  100. */
  101. protected static $_backgroundColors = array(
  102. 'black' => 40,
  103. 'red' => 41,
  104. 'green' => 42,
  105. 'yellow' => 43,
  106. 'blue' => 44,
  107. 'magenta' => 45,
  108. 'cyan' => 46,
  109. 'white' => 47
  110. );
  111. /**
  112. * formatting options for colored output
  113. *
  114. * @var string
  115. */
  116. protected static $_options = array(
  117. 'bold' => 1,
  118. 'underline' => 4,
  119. 'blink' => 5,
  120. 'reverse' => 7,
  121. );
  122. /**
  123. * Styles that are available as tags in console output.
  124. * You can modify these styles with ConsoleOutput::styles()
  125. *
  126. * @var array
  127. */
  128. protected static $_styles = array(
  129. 'emergency' => array('text' => 'red', 'underline' => true),
  130. 'alert' => array('text' => 'red', 'underline' => true),
  131. 'critical' => array('text' => 'red', 'underline' => true),
  132. 'error' => array('text' => 'red', 'underline' => true),
  133. 'warning' => array('text' => 'yellow'),
  134. 'info' => array('text' => 'cyan'),
  135. 'debug' => array('text' => 'yellow'),
  136. 'success' => array('text' => 'green'),
  137. 'comment' => array('text' => 'blue'),
  138. 'question' => array('text' => 'magenta'),
  139. 'notice' => array('text' => 'cyan')
  140. );
  141. /**
  142. * Construct the output object.
  143. *
  144. * Checks for a pretty console environment. Ansicon allows pretty consoles
  145. * on windows, and is supported.
  146. *
  147. * @param string $stream The identifier of the stream to write output to.
  148. */
  149. public function __construct($stream = 'php://stdout') {
  150. $this->_output = fopen($stream, 'w');
  151. if (DS === '\\' && !(bool)env('ANSICON')) {
  152. $this->_outputAs = self::PLAIN;
  153. }
  154. }
  155. /**
  156. * Outputs a single or multiple messages to stdout. If no parameters
  157. * are passed, outputs just a newline.
  158. *
  159. * @param string|array $message A string or a an array of strings to output
  160. * @param integer $newlines Number of newlines to append
  161. * @return integer Returns the number of bytes returned from writing to stdout.
  162. */
  163. public function write($message, $newlines = 1) {
  164. if (is_array($message)) {
  165. $message = implode(self::LF, $message);
  166. }
  167. return $this->_write($this->styleText($message . str_repeat(self::LF, $newlines)));
  168. }
  169. /**
  170. * Apply styling to text.
  171. *
  172. * @param string $text Text with styling tags.
  173. * @return string String with color codes added.
  174. */
  175. public function styleText($text) {
  176. if ($this->_outputAs == self::RAW) {
  177. return $text;
  178. }
  179. if ($this->_outputAs == self::PLAIN) {
  180. $tags = implode('|', array_keys(self::$_styles));
  181. return preg_replace('#</?(?:' . $tags . ')>#', '', $text);
  182. }
  183. return preg_replace_callback(
  184. '/<(?P<tag>[a-z0-9-_]+)>(?P<text>.*?)<\/(\1)>/ims', array($this, '_replaceTags'), $text
  185. );
  186. }
  187. /**
  188. * Replace tags with color codes.
  189. *
  190. * @param array $matches.
  191. * @return string
  192. */
  193. protected function _replaceTags($matches) {
  194. $style = $this->styles($matches['tag']);
  195. if (empty($style)) {
  196. return '<' . $matches['tag'] . '>' . $matches['text'] . '</' . $matches['tag'] . '>';
  197. }
  198. $styleInfo = array();
  199. if (!empty($style['text']) && isset(self::$_foregroundColors[$style['text']])) {
  200. $styleInfo[] = self::$_foregroundColors[$style['text']];
  201. }
  202. if (!empty($style['background']) && isset(self::$_backgroundColors[$style['background']])) {
  203. $styleInfo[] = self::$_backgroundColors[$style['background']];
  204. }
  205. unset($style['text'], $style['background']);
  206. foreach ($style as $option => $value) {
  207. if ($value) {
  208. $styleInfo[] = self::$_options[$option];
  209. }
  210. }
  211. return "\033[" . implode($styleInfo, ';') . 'm' . $matches['text'] . "\033[0m";
  212. }
  213. /**
  214. * Writes a message to the output stream.
  215. *
  216. * @param string $message Message to write.
  217. * @return boolean success
  218. */
  219. protected function _write($message) {
  220. return fwrite($this->_output, $message);
  221. }
  222. /**
  223. * Get the current styles offered, or append new ones in.
  224. *
  225. * ### Get a style definition
  226. *
  227. * `$this->output->styles('error');`
  228. *
  229. * ### Get all the style definitions
  230. *
  231. * `$this->output->styles();`
  232. *
  233. * ### Create or modify an existing style
  234. *
  235. * `$this->output->styles('annoy', array('text' => 'purple', 'background' => 'yellow', 'blink' => true));`
  236. *
  237. * ### Remove a style
  238. *
  239. * `$this->output->styles('annoy', false);`
  240. *
  241. * @param string $style The style to get or create.
  242. * @param array $definition The array definition of the style to change or create a style
  243. * or false to remove a style.
  244. * @return mixed If you are getting styles, the style or null will be returned. If you are creating/modifying
  245. * styles true will be returned.
  246. */
  247. public function styles($style = null, $definition = null) {
  248. if ($style === null && $definition === null) {
  249. return self::$_styles;
  250. }
  251. if (is_string($style) && $definition === null) {
  252. return isset(self::$_styles[$style]) ? self::$_styles[$style] : null;
  253. }
  254. if ($definition === false) {
  255. unset(self::$_styles[$style]);
  256. return true;
  257. }
  258. self::$_styles[$style] = $definition;
  259. return true;
  260. }
  261. /**
  262. * Get/Set the output type to use. The output type how formatting tags are treated.
  263. *
  264. * @param integer $type The output type to use. Should be one of the class constants.
  265. * @return mixed Either null or the value if getting.
  266. */
  267. public function outputAs($type = null) {
  268. if ($type === null) {
  269. return $this->_outputAs;
  270. }
  271. $this->_outputAs = $type;
  272. }
  273. /**
  274. * Clean up and close handles
  275. */
  276. public function __destruct() {
  277. if (is_resource($this->_output)) {
  278. fclose($this->_output);
  279. }
  280. }
  281. }