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: /**
52: * Plain output - tags will be stripped.
53: */
54: const PLAIN = 1;
55:
56: /**
57: * Color output - Convert known tags in to ANSI color escape codes.
58: */
59: const COLOR = 2;
60:
61: /**
62: * Constant for a newline.
63: */
64: const LF = PHP_EOL;
65:
66: /**
67: * File handle for output.
68: *
69: * @var resource
70: */
71: protected $_output;
72:
73: /**
74: * The current output type. Manipulated with ConsoleOutput::outputAs();
75: *
76: * @var integer.
77: */
78: protected $_outputAs = self::COLOR;
79:
80: /**
81: * text colors used in colored output.
82: *
83: * @var array
84: */
85: protected static $_foregroundColors = array(
86: 'black' => 30,
87: 'red' => 31,
88: 'green' => 32,
89: 'yellow' => 33,
90: 'blue' => 34,
91: 'magenta' => 35,
92: 'cyan' => 36,
93: 'white' => 37
94: );
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: /**
113: * formatting options for colored output
114: *
115: * @var string
116: */
117: protected static $_options = array(
118: 'bold' => 1,
119: 'underline' => 4,
120: 'blink' => 5,
121: 'reverse' => 7,
122: );
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 = array(
131: 'emergency' => array('text' => 'red', 'underline' => true),
132: 'alert' => array('text' => 'red', 'underline' => true),
133: 'critical' => array('text' => 'red', 'underline' => true),
134: 'error' => array('text' => 'red', 'underline' => true),
135: 'warning' => array('text' => 'yellow'),
136: 'info' => array('text' => 'cyan'),
137: 'debug' => array('text' => 'yellow'),
138: 'success' => array('text' => 'green'),
139: 'comment' => array('text' => 'blue'),
140: 'question' => array('text' => 'magenta'),
141: );
142:
143: /**
144: * Construct the output object.
145: *
146: * Checks for a pretty console environment. Ansicon allows pretty consoles
147: * 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: $this->_output = fopen($stream, 'w');
153:
154: if (DS == '\\' && !(bool)env('ANSICON')) {
155: $this->_outputAs = self::PLAIN;
156: }
157: }
158:
159: /**
160: * Outputs a single or multiple messages to stdout. If no parameters
161: * are passed, outputs just a newline.
162: *
163: * @param string|array $message A string or a an array of strings to output
164: * @param integer $newlines Number of newlines to append
165: * @return integer Returns the number of bytes returned from writing to stdout.
166: */
167: public function write($message, $newlines = 1) {
168: if (is_array($message)) {
169: $message = implode(self::LF, $message);
170: }
171: return $this->_write($this->styleText($message . str_repeat(self::LF, $newlines)));
172: }
173:
174: /**
175: * Apply styling to text.
176: *
177: * @param string $text Text with styling tags.
178: * @return string String with color codes added.
179: */
180: public function styleText($text) {
181: if ($this->_outputAs == self::RAW) {
182: return $text;
183: }
184: if ($this->_outputAs == self::PLAIN) {
185: $tags = implode('|', array_keys(self::$_styles));
186: return preg_replace('#</?(?:' . $tags . ')>#', '', $text);
187: }
188: return preg_replace_callback(
189: '/<(?P<tag>[a-z0-9-_]+)>(?P<text>.*?)<\/(\1)>/ims', array($this, '_replaceTags'), $text
190: );
191: }
192:
193: /**
194: * Replace tags with color codes.
195: *
196: * @param array $matches.
197: * @return string
198: */
199: protected function _replaceTags($matches) {
200: $style = $this->styles($matches['tag']);
201: if (empty($style)) {
202: return '<' . $matches['tag'] . '>' . $matches['text'] . '</' . $matches['tag'] . '>';
203: }
204:
205: $styleInfo = array();
206: if (!empty($style['text']) && isset(self::$_foregroundColors[$style['text']])) {
207: $styleInfo[] = self::$_foregroundColors[$style['text']];
208: }
209: if (!empty($style['background']) && isset(self::$_backgroundColors[$style['background']])) {
210: $styleInfo[] = self::$_backgroundColors[$style['background']];
211: }
212: unset($style['text'], $style['background']);
213: foreach ($style as $option => $value) {
214: if ($value) {
215: $styleInfo[] = self::$_options[$option];
216: }
217: }
218: return "\033[" . implode($styleInfo, ';') . 'm' . $matches['text'] . "\033[0m";
219: }
220:
221: /**
222: * Writes a message to the output stream.
223: *
224: * @param string $message Message to write.
225: * @return boolean success
226: */
227: protected function _write($message) {
228: return fwrite($this->_output, $message);
229: }
230:
231: /**
232: * Get the current styles offered, or append new ones in.
233: *
234: * ### Get a style definition
235: *
236: * `$this->output->styles('error');`
237: *
238: * ### Get all the style definitions
239: *
240: * `$this->output->styles();`
241: *
242: * ### Create or modify an existing style
243: *
244: * `$this->output->styles('annoy', array('text' => 'purple', 'background' => 'yellow', 'blink' => true));`
245: *
246: * ### Remove a style
247: *
248: * `$this->output->styles('annoy', false);`
249: *
250: * @param string $style The style to get or create.
251: * @param array $definition The array definition of the style to change or create a style
252: * or false to remove a style.
253: * @return mixed If you are getting styles, the style or null will be returned. If you are creating/modifying
254: * styles true will be returned.
255: */
256: public function styles($style = null, $definition = null) {
257: if ($style === null && $definition === null) {
258: return self::$_styles;
259: }
260: if (is_string($style) && $definition === null) {
261: return isset(self::$_styles[$style]) ? self::$_styles[$style] : null;
262: }
263: if ($definition === false) {
264: unset(self::$_styles[$style]);
265: return true;
266: }
267: self::$_styles[$style] = $definition;
268: return true;
269: }
270:
271: /**
272: * Get/Set the output type to use. The output type how formatting tags are treated.
273: *
274: * @param integer $type The output type to use. Should be one of the class constants.
275: * @return mixed Either null or the value if getting.
276: */
277: public function outputAs($type = null) {
278: if ($type === null) {
279: return $this->_outputAs;
280: }
281: $this->_outputAs = $type;
282: }
283:
284: /**
285: * clean up and close handles
286: *
287: */
288: public function __destruct() {
289: fclose($this->_output);
290: }
291:
292: }
293: