ConsoleOutput.php 7.5 KB

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