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: 'error' => array('text' => 'red', 'underline' => true),
132: 'warning' => array('text' => 'yellow'),
133: 'info' => array('text' => 'cyan'),
134: 'success' => array('text' => 'green'),
135: 'comment' => array('text' => 'blue'),
136: 'question' => array('text' => "magenta"),
137: );
138:
139: /**
140: * Construct the output object.
141: *
142: * Checks for a pretty console environment. Ansicon allows pretty consoles
143: * on windows, and is supported.
144: *
145: * @param string $stream The identifier of the stream to write output to.
146: */
147: public function __construct($stream = 'php://stdout') {
148: $this->_output = fopen($stream, 'w');
149:
150: if (DS == '\\' && !(bool)env('ANSICON')) {
151: $this->_outputAs = self::PLAIN;
152: }
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 mixed $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: /**
171: * Apply styling to text.
172: *
173: * @param string $text Text with styling tags.
174: * @return string String with color codes added.
175: */
176: public function styleText($text) {
177: if ($this->_outputAs == self::RAW) {
178: return $text;
179: }
180: if ($this->_outputAs == self::PLAIN) {
181: $tags = implode('|', array_keys(self::$_styles));
182: return preg_replace('#</?(?:' . $tags . ')>#', '', $text);
183: }
184: return preg_replace_callback(
185: '/<(?P<tag>[a-z0-9-_]+)>(?P<text>.*?)<\/(\1)>/ims', array($this, '_replaceTags'), $text
186: );
187: }
188:
189: /**
190: * Replace tags with color codes.
191: *
192: * @param array $matches.
193: * @return string
194: */
195: protected function _replaceTags($matches) {
196: $style = $this->styles($matches['tag']);
197: if (empty($style)) {
198: return '<' . $matches['tag'] . '>' . $matches['text'] . '</' . $matches['tag'] . '>';
199: }
200:
201: $styleInfo = array();
202: if (!empty($style['text']) && isset(self::$_foregroundColors[$style['text']])) {
203: $styleInfo[] = self::$_foregroundColors[$style['text']];
204: }
205: if (!empty($style['background']) && isset(self::$_backgroundColors[$style['background']])) {
206: $styleInfo[] = self::$_backgroundColors[$style['background']];
207: }
208: unset($style['text'], $style['background']);
209: foreach ($style as $option => $value) {
210: if ($value) {
211: $styleInfo[] = self::$_options[$option];
212: }
213: }
214: return "\033[" . implode($styleInfo, ';') . 'm' . $matches['text'] . "\033[0m";
215: }
216:
217: /**
218: * Writes a message to the output stream.
219: *
220: * @param string $message Message to write.
221: * @return boolean success
222: */
223: protected function _write($message) {
224: return fwrite($this->_output, $message);
225: }
226:
227: /**
228: * Get the current styles offered, or append new ones in.
229: *
230: * ### Get a style definition
231: *
232: * `$this->output->styles('error');`
233: *
234: * ### Get all the style definitions
235: *
236: * `$this->output->styles();`
237: *
238: * ### Create or modify an existing style
239: *
240: * `$this->output->styles('annoy', array('text' => 'purple', 'background' => 'yellow', 'blink' => true));`
241: *
242: * ### Remove a style
243: *
244: * `$this->output->styles('annoy', false);`
245: *
246: * @param string $style The style to get or create.
247: * @param mixed $definition The array definition of the style to change or create a style
248: * or false to remove a style.
249: * @return mixed If you are getting styles, the style or null will be returned. If you are creating/modifying
250: * styles true will be returned.
251: */
252: public function styles($style = null, $definition = null) {
253: if ($style === null && $definition === null) {
254: return self::$_styles;
255: }
256: if (is_string($style) && $definition === null) {
257: return isset(self::$_styles[$style]) ? self::$_styles[$style] : null;
258: }
259: if ($definition === false) {
260: unset(self::$_styles[$style]);
261: return true;
262: }
263: self::$_styles[$style] = $definition;
264: return true;
265: }
266:
267: /**
268: * Get/Set the output type to use. The output type how formatting tags are treated.
269: *
270: * @param integer $type The output type to use. Should be one of the class constants.
271: * @return mixed Either null or the value if getting.
272: */
273: public function outputAs($type = null) {
274: if ($type === null) {
275: return $this->_outputAs;
276: }
277: $this->_outputAs = $type;
278: }
279:
280: /**
281: * clean up and close handles
282: *
283: */
284: public function __destruct() {
285: fclose($this->_output);
286: }
287:
288: }
289: