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: * Raw output constant - no modification of output text.
50: *
51: * @var int
52: */
53: const RAW = 0;
54:
55: /**
56: * Plain output - tags will be stripped.
57: *
58: * @var int
59: */
60: const PLAIN = 1;
61:
62: /**
63: * Color output - Convert known tags in to ANSI color escape codes.
64: *
65: * @var int
66: */
67: const COLOR = 2;
68:
69: /**
70: * Constant for a newline.
71: *
72: * @var string
73: */
74: const LF = PHP_EOL;
75:
76: /**
77: * File handle for output.
78: *
79: * @var resource
80: */
81: protected $_output;
82:
83: /**
84: * The current output type.
85: *
86: * @see setOutputAs() For manipulation.
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: /** @var array $style */
224: $style = $this->styles($matches['tag']);
225: if (empty($style)) {
226: return '<' . $matches['tag'] . '>' . $matches['text'] . '</' . $matches['tag'] . '>';
227: }
228:
229: $styleInfo = [];
230: if (!empty($style['text']) && isset(static::$_foregroundColors[$style['text']])) {
231: $styleInfo[] = static::$_foregroundColors[$style['text']];
232: }
233: if (!empty($style['background']) && isset(static::$_backgroundColors[$style['background']])) {
234: $styleInfo[] = static::$_backgroundColors[$style['background']];
235: }
236: unset($style['text'], $style['background']);
237: foreach ($style as $option => $value) {
238: if ($value) {
239: $styleInfo[] = static::$_options[$option];
240: }
241: }
242:
243: return "\033[" . implode(';', $styleInfo) . 'm' . $matches['text'] . "\033[0m";
244: }
245:
246: /**
247: * Writes a message to the output stream.
248: *
249: * @param string $message Message to write.
250: * @return int|bool The number of bytes returned from writing to output.
251: */
252: protected function _write($message)
253: {
254: return fwrite($this->_output, $message);
255: }
256:
257: /**
258: * Get the current styles offered, or append new ones in.
259: *
260: * ### Get a style definition
261: *
262: * ```
263: * $output->styles('error');
264: * ```
265: *
266: * ### Get all the style definitions
267: *
268: * ```
269: * $output->styles();
270: * ```
271: *
272: * ### Create or modify an existing style
273: *
274: * ```
275: * $output->styles('annoy', ['text' => 'purple', 'background' => 'yellow', 'blink' => true]);
276: * ```
277: *
278: * ### Remove a style
279: *
280: * ```
281: * $this->output->styles('annoy', false);
282: * ```
283: *
284: * @param string|null $style The style to get or create.
285: * @param array|false|null $definition The array definition of the style to change or create a style
286: * or false to remove a style.
287: * @return array|true|null If you are getting styles, the style or null will be returned. If you are creating/modifying
288: * styles true will be returned.
289: */
290: public function styles($style = null, $definition = null)
291: {
292: if ($style === null && $definition === null) {
293: return static::$_styles;
294: }
295: if (is_string($style) && $definition === null) {
296: return isset(static::$_styles[$style]) ? static::$_styles[$style] : null;
297: }
298: if ($definition === false) {
299: unset(static::$_styles[$style]);
300:
301: return true;
302: }
303: static::$_styles[$style] = $definition;
304:
305: return true;
306: }
307:
308: /**
309: * Get the output type on how formatting tags are treated.
310: *
311: * @return int
312: */
313: public function getOutputAs()
314: {
315: return $this->_outputAs;
316: }
317:
318: /**
319: * Set the output type on how formatting tags are treated.
320: *
321: * @param int $type The output type to use. Should be one of the class constants.
322: * @return void
323: * @throws \InvalidArgumentException in case of a not supported output type.
324: */
325: public function setOutputAs($type)
326: {
327: if (!in_array($type, [self::RAW, self::PLAIN, self::COLOR], true)) {
328: throw new InvalidArgumentException(sprintf('Invalid output type "%s".', $type));
329: }
330:
331: $this->_outputAs = $type;
332: }
333:
334: /**
335: * Get/Set the output type to use. The output type how formatting tags are treated.
336: *
337: * @deprecated 3.5.0 Use getOutputAs()/setOutputAs() instead.
338: * @param int|null $type The output type to use. Should be one of the class constants.
339: * @return int|null Either null or the value if getting.
340: */
341: public function outputAs($type = null)
342: {
343: deprecationWarning(
344: 'ConsoleOutput::outputAs() is deprecated. ' .
345: 'Use ConsoleOutput::setOutputAs()/getOutputAs() instead.'
346: );
347: if ($type === null) {
348: return $this->_outputAs;
349: }
350: $this->_outputAs = $type;
351: }
352:
353: /**
354: * Clean up and close handles
355: */
356: public function __destruct()
357: {
358: if (is_resource($this->_output)) {
359: fclose($this->_output);
360: }
361: }
362: }
363: