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