1: <?php
2: /**
3: * ConsoleOutput file.
4: *
5: * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
6: * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
7: *
8: * Licensed under The MIT License
9: * For full copyright and license information, please see the LICENSE.txt
10: * Redistributions of files must retain the above copyright notice.
11: *
12: * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
13: * @link https://cakephp.org CakePHP(tm) Project
14: * @since CakePHP(tm) v 2.0
15: * @license https://opensource.org/licenses/mit-license.php MIT License
16: */
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: /**
48: * Raw output constant - no modification of output text.
49: *
50: * @var int
51: */
52: const RAW = 0;
53:
54: /**
55: * Plain output - tags will be stripped.
56: *
57: * @var int
58: */
59: const PLAIN = 1;
60:
61: /**
62: * Color output - Convert known tags in to ANSI color escape codes.
63: *
64: * @var int
65: */
66: const COLOR = 2;
67:
68: /**
69: * Constant for a newline.
70: *
71: * @var string
72: */
73: const LF = PHP_EOL;
74:
75: /**
76: * File handle for output.
77: *
78: * @var resource
79: */
80: protected $_output;
81:
82: /**
83: * The number of bytes last written to the output stream
84: * used when overwriting the previous message.
85: *
86: * @var int
87: */
88: protected $_lastWritten = 0;
89:
90: /**
91: * The current output type. Manipulated with ConsoleOutput::outputAs();
92: *
93: * @var int
94: */
95: protected $_outputAs = self::COLOR;
96:
97: /**
98: * text colors used in colored output.
99: *
100: * @var array
101: */
102: protected static $_foregroundColors = array(
103: 'black' => 30,
104: 'red' => 31,
105: 'green' => 32,
106: 'yellow' => 33,
107: 'blue' => 34,
108: 'magenta' => 35,
109: 'cyan' => 36,
110: 'white' => 37
111: );
112:
113: /**
114: * background colors used in colored output.
115: *
116: * @var array
117: */
118: protected static $_backgroundColors = array(
119: 'black' => 40,
120: 'red' => 41,
121: 'green' => 42,
122: 'yellow' => 43,
123: 'blue' => 44,
124: 'magenta' => 45,
125: 'cyan' => 46,
126: 'white' => 47
127: );
128:
129: /**
130: * formatting options for colored output
131: *
132: * @var string
133: */
134: protected static $_options = array(
135: 'bold' => 1,
136: 'underline' => 4,
137: 'blink' => 5,
138: 'reverse' => 7,
139: );
140:
141: /**
142: * Styles that are available as tags in console output.
143: * You can modify these styles with ConsoleOutput::styles()
144: *
145: * @var array
146: */
147: protected static $_styles = array(
148: 'emergency' => array('text' => 'red', 'underline' => true),
149: 'alert' => array('text' => 'red', 'underline' => true),
150: 'critical' => array('text' => 'red', 'underline' => true),
151: 'error' => array('text' => 'red', 'underline' => true),
152: 'warning' => array('text' => 'yellow'),
153: 'info' => array('text' => 'cyan'),
154: 'debug' => array('text' => 'yellow'),
155: 'success' => array('text' => 'green'),
156: 'comment' => array('text' => 'blue'),
157: 'question' => array('text' => 'magenta'),
158: 'notice' => array('text' => 'cyan')
159: );
160:
161: /**
162: * Construct the output object.
163: *
164: * Checks for a pretty console environment. Ansicon and ConEmu allows
165: * pretty consoles on Windows, and is supported.
166: *
167: * @param string $stream The identifier of the stream to write output to.
168: */
169: public function __construct($stream = 'php://stdout') {
170: $this->_output = fopen($stream, 'w');
171:
172: if ((DS === '\\' && !(bool)env('ANSICON') && env('ConEmuANSI') !== 'ON') ||
173: $stream === 'php://output' ||
174: (function_exists('posix_isatty') && !posix_isatty($this->_output))
175: ) {
176: $this->_outputAs = static::PLAIN;
177: }
178: }
179:
180: /**
181: * Outputs a single or multiple messages to stdout. If no parameters
182: * are passed, outputs just a newline.
183: *
184: * @param string|array $message A string or an array of strings to output
185: * @param int $newlines Number of newlines to append
186: * @return int Returns the number of bytes returned from writing to stdout.
187: */
188: public function write($message, $newlines = 1) {
189: if (is_array($message)) {
190: $message = implode(static::LF, $message);
191: }
192: return $this->_write($this->styleText($message . str_repeat(static::LF, $newlines)));
193: }
194:
195: /**
196: * Overwrite some already output text.
197: *
198: * Useful for building progress bars, or when you want to replace
199: * text already output to the screen with new text.
200: *
201: * **Warning** You cannot overwrite text that contains newlines.
202: *
203: * @param array|string $message The message to output.
204: * @param int $newlines Number of newlines to append.
205: * @param int|null $size The number of bytes to overwrite. Defaults to the
206: * length of the last message output.
207: * @return void
208: */
209: public function overwrite($message, $newlines = 1, $size = null) {
210: $size = $size ?: $this->_lastWritten;
211: // Output backspaces.
212: $this->write(str_repeat("\x08", $size), 0);
213: $newBytes = $this->write($message, 0);
214: // Fill any remaining bytes with spaces.
215: $fill = $size - $newBytes;
216: if ($fill > 0) {
217: $this->write(str_repeat(' ', $fill), 0);
218: }
219: if ($newlines) {
220: $this->write("", $newlines);
221: }
222: }
223:
224: /**
225: * Apply styling to text.
226: *
227: * @param string $text Text with styling tags.
228: * @return string String with color codes added.
229: */
230: public function styleText($text) {
231: if ($this->_outputAs == static::RAW) {
232: return $text;
233: }
234: if ($this->_outputAs == static::PLAIN) {
235: $tags = implode('|', array_keys(static::$_styles));
236: return preg_replace('#</?(?:' . $tags . ')>#', '', $text);
237: }
238: return preg_replace_callback(
239: '/<(?P<tag>[a-z0-9-_]+)>(?P<text>.*?)<\/(\1)>/ims', array($this, '_replaceTags'), $text
240: );
241: }
242:
243: /**
244: * Replace tags with color codes.
245: *
246: * @param array $matches An array of matches to replace.
247: * @return string
248: */
249: protected function _replaceTags($matches) {
250: $style = $this->styles($matches['tag']);
251: if (empty($style)) {
252: return '<' . $matches['tag'] . '>' . $matches['text'] . '</' . $matches['tag'] . '>';
253: }
254:
255: $styleInfo = array();
256: if (!empty($style['text']) && isset(static::$_foregroundColors[$style['text']])) {
257: $styleInfo[] = static::$_foregroundColors[$style['text']];
258: }
259: if (!empty($style['background']) && isset(static::$_backgroundColors[$style['background']])) {
260: $styleInfo[] = static::$_backgroundColors[$style['background']];
261: }
262: unset($style['text'], $style['background']);
263: foreach ($style as $option => $value) {
264: if ($value) {
265: $styleInfo[] = static::$_options[$option];
266: }
267: }
268: return "\033[" . implode(';', $styleInfo) . 'm' . $matches['text'] . "\033[0m";
269: }
270:
271: /**
272: * Writes a message to the output stream.
273: *
274: * @param string $message Message to write.
275: * @return bool success
276: */
277: protected function _write($message) {
278: $this->_lastWritten = fwrite($this->_output, $message);
279: return $this->_lastWritten;
280: }
281:
282: /**
283: * Get the current styles offered, or append new ones in.
284: *
285: * ### Get a style definition
286: *
287: * `$this->output->styles('error');`
288: *
289: * ### Get all the style definitions
290: *
291: * `$this->output->styles();`
292: *
293: * ### Create or modify an existing style
294: *
295: * `$this->output->styles('annoy', array('text' => 'purple', 'background' => 'yellow', 'blink' => true));`
296: *
297: * ### Remove a style
298: *
299: * `$this->output->styles('annoy', false);`
300: *
301: * @param string $style The style to get or create.
302: * @param array $definition The array definition of the style to change or create a style
303: * or false to remove a style.
304: * @return mixed If you are getting styles, the style or null will be returned. If you are creating/modifying
305: * styles true will be returned.
306: */
307: public function styles($style = null, $definition = null) {
308: if ($style === null && $definition === null) {
309: return static::$_styles;
310: }
311: if (is_string($style) && $definition === null) {
312: return isset(static::$_styles[$style]) ? static::$_styles[$style] : null;
313: }
314: if ($definition === false) {
315: unset(static::$_styles[$style]);
316: return true;
317: }
318: static::$_styles[$style] = $definition;
319: return true;
320: }
321:
322: /**
323: * Get/Set the output type to use. The output type how formatting tags are treated.
324: *
325: * @param int $type The output type to use. Should be one of the class constants.
326: * @return mixed Either null or the value if getting.
327: */
328: public function outputAs($type = null) {
329: if ($type === null) {
330: return $this->_outputAs;
331: }
332: $this->_outputAs = $type;
333: }
334:
335: /**
336: * Clean up and close handles
337: */
338: public function __destruct() {
339: if (is_resource($this->_output)) {
340: fclose($this->_output);
341: }
342: }
343:
344: }
345: