ConsoleOutput.php 7.2 KB

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