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