ConsoleOutput.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. <?php
  2. /**
  3. * ConsoleOutput file.
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * For full copyright and license information, please see the LICENSE.txt
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @since CakePHP(tm) v 2.0
  17. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  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
  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. 'emergency' => array('text' => 'red', 'underline' => true),
  124. 'alert' => array('text' => 'red', 'underline' => true),
  125. 'critical' => array('text' => 'red', 'underline' => true),
  126. 'error' => array('text' => 'red', 'underline' => true),
  127. 'warning' => array('text' => 'yellow'),
  128. 'info' => array('text' => 'cyan'),
  129. 'debug' => array('text' => 'yellow'),
  130. 'success' => array('text' => 'green'),
  131. 'comment' => array('text' => 'blue'),
  132. 'question' => array('text' => 'magenta'),
  133. 'notice' => array('text' => 'cyan')
  134. );
  135. /**
  136. * Construct the output object.
  137. *
  138. * Checks for a pretty console environment. Ansicon allows pretty consoles
  139. * on windows, and is supported.
  140. *
  141. * @param string $stream The identifier of the stream to write output to.
  142. */
  143. public function __construct($stream = 'php://stdout') {
  144. $this->_output = fopen($stream, 'w');
  145. if (DS === '\\' && !(bool)env('ANSICON')) {
  146. $this->_outputAs = self::PLAIN;
  147. }
  148. }
  149. /**
  150. * Outputs a single or multiple messages to stdout. If no parameters
  151. * are passed, outputs just a newline.
  152. *
  153. * @param string|array $message A string or a an array of strings to output
  154. * @param integer $newlines Number of newlines to append
  155. * @return integer Returns the number of bytes returned from writing to stdout.
  156. */
  157. public function write($message, $newlines = 1) {
  158. if (is_array($message)) {
  159. $message = implode(self::LF, $message);
  160. }
  161. return $this->_write($this->styleText($message . str_repeat(self::LF, $newlines)));
  162. }
  163. /**
  164. * Apply styling to text.
  165. *
  166. * @param string $text Text with styling tags.
  167. * @return string String with color codes added.
  168. */
  169. public function styleText($text) {
  170. if ($this->_outputAs == self::RAW) {
  171. return $text;
  172. }
  173. if ($this->_outputAs == self::PLAIN) {
  174. $tags = implode('|', array_keys(self::$_styles));
  175. return preg_replace('#</?(?:' . $tags . ')>#', '', $text);
  176. }
  177. return preg_replace_callback(
  178. '/<(?P<tag>[a-z0-9-_]+)>(?P<text>.*?)<\/(\1)>/ims', array($this, '_replaceTags'), $text
  179. );
  180. }
  181. /**
  182. * Replace tags with color codes.
  183. *
  184. * @param array $matches.
  185. * @return string
  186. */
  187. protected function _replaceTags($matches) {
  188. $style = $this->styles($matches['tag']);
  189. if (empty($style)) {
  190. return '<' . $matches['tag'] . '>' . $matches['text'] . '</' . $matches['tag'] . '>';
  191. }
  192. $styleInfo = array();
  193. if (!empty($style['text']) && isset(self::$_foregroundColors[$style['text']])) {
  194. $styleInfo[] = self::$_foregroundColors[$style['text']];
  195. }
  196. if (!empty($style['background']) && isset(self::$_backgroundColors[$style['background']])) {
  197. $styleInfo[] = self::$_backgroundColors[$style['background']];
  198. }
  199. unset($style['text'], $style['background']);
  200. foreach ($style as $option => $value) {
  201. if ($value) {
  202. $styleInfo[] = self::$_options[$option];
  203. }
  204. }
  205. return "\033[" . implode($styleInfo, ';') . 'm' . $matches['text'] . "\033[0m";
  206. }
  207. /**
  208. * Writes a message to the output stream.
  209. *
  210. * @param string $message Message to write.
  211. * @return boolean success
  212. */
  213. protected function _write($message) {
  214. return fwrite($this->_output, $message);
  215. }
  216. /**
  217. * Get the current styles offered, or append new ones in.
  218. *
  219. * ### Get a style definition
  220. *
  221. * `$this->output->styles('error');`
  222. *
  223. * ### Get all the style definitions
  224. *
  225. * `$this->output->styles();`
  226. *
  227. * ### Create or modify an existing style
  228. *
  229. * `$this->output->styles('annoy', array('text' => 'purple', 'background' => 'yellow', 'blink' => true));`
  230. *
  231. * ### Remove a style
  232. *
  233. * `$this->output->styles('annoy', false);`
  234. *
  235. * @param string $style The style to get or create.
  236. * @param array $definition The array definition of the style to change or create a style
  237. * or false to remove a style.
  238. * @return mixed If you are getting styles, the style or null will be returned. If you are creating/modifying
  239. * styles true will be returned.
  240. */
  241. public function styles($style = null, $definition = null) {
  242. if ($style === null && $definition === null) {
  243. return self::$_styles;
  244. }
  245. if (is_string($style) && $definition === null) {
  246. return isset(self::$_styles[$style]) ? self::$_styles[$style] : null;
  247. }
  248. if ($definition === false) {
  249. unset(self::$_styles[$style]);
  250. return true;
  251. }
  252. self::$_styles[$style] = $definition;
  253. return true;
  254. }
  255. /**
  256. * Get/Set the output type to use. The output type how formatting tags are treated.
  257. *
  258. * @param integer $type The output type to use. Should be one of the class constants.
  259. * @return mixed Either null or the value if getting.
  260. */
  261. public function outputAs($type = null) {
  262. if ($type === null) {
  263. return $this->_outputAs;
  264. }
  265. $this->_outputAs = $type;
  266. }
  267. /**
  268. * clean up and close handles
  269. *
  270. */
  271. public function __destruct() {
  272. fclose($this->_output);
  273. }
  274. }