## Apache Zeta Components Manual :: File Source for output.php

## Source for file output.php

Documentation is available at output.php

1. <?php
2. /**
3. * File containing the ezcConsoleOutput class.
4. *
5. * Licensed to the Apache Software Foundation (ASF) under one
6. * or more contributor license agreements. See the NOTICE file
7. * distributed with this work for additional information
8. * regarding copyright ownership. The ASF licenses this file
9. * to you under the Apache License, Version 2.0 (the
10. * "License"); you may not use this file except in compliance
11. * with the License. You may obtain a copy of the License at
12. *
13. * http://www.apache.org/licenses/LICENSE-2.0
14. *
15. * Unless required by applicable law or agreed to in writing,
16. * software distributed under the License is distributed on an
17. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
18. * KIND, either express or implied. See the License for the
19. * specific language governing permissions and limitations
20. * under the License.
21. *
22. * @package ConsoleTools
23. * @version //autogentag//
24. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
25. * @filesource
26. */
28. /**
29. * Class for handling console output.
30. *
31. * The ezcConsoleOutput class provides an interface to output text to the console. It deals with formating
32. * text in different ways and offers some comfortable options to deal
33. * with console text output.
34. *
35. * <code>
36. * // Create the output handler
37. * $out = new ezcConsoleOutput();
38. *
39. * // Set the verbosity to level 10
40. * $out->options->verbosityLevel = 10;
41. * // Enable auto wrapping of lines after 40 characters
42. * $out->options->autobreak = 40;
43. *
44. * // Set the color of the default output format to green
45. * $out->formats->default->color = 'green';
46. *
47. * // Set the color of the output format named 'success' to white
48. * $out->formats->success->color = 'white';
49. * // Set the style of the output format named 'success' to bold
50. * $out->formats->success->style = array( 'bold' );
51. *
52. * // Set the color of the output format named 'failure' to red
53. * $out->formats->failure->color = 'red';
54. * // Set the style of the output format named 'failure' to bold
55. * $out->formats->failure->style = array( 'bold' );
56. * // Set the background color of the output format named 'failure' to blue
57. * $out->formats->failure->bgcolor = 'blue';
58. *
59. * // Output text with default format
60. * $out->outputText( 'This is default text ' );
61. * // Output text with format 'success'
62. * $out->outputText( 'including success message', 'success' );
63. * // Some more output with default output.
64. * $out->outputText( "and a manual linebreak.\n" );
65. *
66. * // Manipulate the later output
67. * $out->formats->success->color = 'green';
68. * $out->formats->default->color = 'blue';
69. *
70. * // This is visible, since we set verbosityLevel to 10, and printed in default format (now blue)
71. * $out->outputText( "Some verbose output.\n", null, 10 );
72. * // This is not visible, since we set verbosityLevel to 10
73. * $out->outputText( "Some more verbose output.\n", null, 20 );
74. * // This is visible, since we set verbosityLevel to 10, and printed in format 'failure'
75. * $out->outputText( "And some not so verbose, failure output.\n", 'failure', 5 );
76. * </code>
77. *
78. * For a list of valid colors, style attributes and background colors, please
79. * refer to {@link ezcConsoleOutputFormat}.
80. *
81. * ATTENTION: Windows operating systems do not support styling of text on the
82. * console. Therefore no styling sequences are generated on any version of
83. * this operating system.
84. *
85. * @property ezcConsoleOutputOptions $options
86. * Contains the options for this class.
87. * @property ezcConsoleOutputFormats $formats
88. * Contains the output formats.
89. *
90. * @package ConsoleTools
91. * @version //autogen//
92. * @mainclass
93. */
94. class ezcConsoleOutput
95. {
97. /**
98. * Target to print to standard out, with output buffering possibility.
99. */
100. const TARGET_OUTPUT = "php://output";
102. /**
103. * Target to print to standard out.
104. */
105. const TARGET_STDOUT = "php://stdout";
107. /**
108. * Target to print to standard error.
109. */
110. const TARGET_STDERR = "php://stderr";
112. /**
113. * Container to hold the properties
114. *
115. * @var array(string=>mixed)
116. */
117. protected $properties ;
119. /**
120. * Whether a position has been stored before, using the storePos() method.
121. *
122. * @see ezcConsoleOutput::storePos()
123. * @var bool
124. */
125. protected $positionStored = false;
127. /**
128. * Stores the mapping of color names to their escape
129. * sequence values.
130. *
131. * @var array(string=>int)
132. */
133. protected static $color = array(
134. 'gray' => 30,
135. 'black' => 30, // Alias black to gray (Bug #8478)
136. 'red' => 31,
137. 'green' => 32,
138. 'yellow' => 33,
139. 'blue' => 34,
140. 'magenta' => 35,
141. 'cyan' => 36,
142. 'white' => 37,
143. 'default' => 39
144. );
146. /**
147. * Stores the mapping of bgcolor names to their escape
148. * sequence values.
149. *
150. * @var array(string=>int)
151. */
152. protected static $bgcolor = array(
153. 'gray' => 40, // Alias gray to black (Bug #8478)
154. 'black' => 40,
155. 'red' => 41,
156. 'green' => 42,
157. 'yellow' => 43,
158. 'blue' => 44,
159. 'magenta' => 45,
160. 'cyan' => 46,
161. 'white' => 47,
162. 'default' => 49,
163. );
165. /**
166. * Stores the mapping of styles names to their escape
167. * sequence values.
168. *
169. * @var array(string=>int)
170. */
171. protected static $style = array(
172. 'default' => '0',
174. 'bold' => 1,
175. 'faint' => 2,
176. 'normal' => 22,
178. 'italic' => 3,
179. 'notitalic' => 23,
181. 'underlined' => 4,
182. 'doubleunderlined' => 21,
183. 'notunderlined' => 24,
185. 'blink' => 5,
186. 'blinkfast' => 6,
187. 'noblink' => 25,
189. 'negative' => 7,
190. 'positive' => 27,
191. );
193. /**
194. * Basic escape sequence string. Use sprintf() to insert escape codes.
195. *
196. * @var string
197. */
198. private $escapeSequence = "\033[%sm";
200. /**
201. * Collection of targets to print to.
202. *
203. * @var array
204. */
205. private $targets = array();
207. /**
208. * Create a new console output handler.
209. *
210. * @see ezcConsoleOutput::$options
211. * @see ezcConsoleOutputOptions
212. * @see ezcConsoleOutput::$formats
213. * @see ezcConsoleOutputFormats
214. *
215. * @param ezcConsoleOutputFormats $formats Formats to be used for output.
216. * @param array(string=>string) $options Options to set.
217. */
218. public function __construct ( ezcConsoleOutputFormats $formats = null, array $options = array() )
219. {
220. $options = isset( $options ) ? $options : new ezcConsoleOutputOptions ();
221. $formats = isset( $formats ) ? $formats : new ezcConsoleOutputFormats ();
222. $this-> properties ['options'] = new ezcConsoleOutputOptions ( $options );
223. $this-> properties ['formats'] = $formats;
224. }
226. /**
227. * Set new options.
228. * This method allows you to change the options of an output handler.
229. *
230. * @param ezcConsoleOutputOptions $options The options to set.
231. *
232. * @throws ezcBaseSettingNotFoundException
233. * If you tried to set a non-existent option value.
234. * @throws ezcBaseSettingValueException
235. * If the value is not valid for the desired option.
236. * @throws ezcBaseValueException
237. * If you submit neither an array nor an instance of
238. * ezcConsoleOutputOptions.
239. */
240. public function setOptions ( $options )
241. {
242. if ( is_array ( $options ) )
243. {
244. $this-> properties ['options']->merge( $options );
245. }
246. else if ( $options instanceof ezcConsoleOutputOptions )
247. {
248. $this-> properties ['options'] = $options;
249. }
250. else
251. {
252. throw new ezcBaseValueException ( "options", $options, "instance of ezcConsoleOutputOptions" );
253. }
254. }
256. /**
257. * Returns the current options.
258. * Returns the options currently set for this output handler.
259. *
260. * @return ezcConsoleOutputOptions The current options.
261. */
262. public function getOptions ()
263. {
264. return $this-> properties ['options'];
265. }
267. /**
268. * Property read access.
269. *
270. * @throws ezcBasePropertyNotFoundException
271. * If the the desired property is not found.
272. *
273. * @param string $propertyName Name of the property.
274. * @return mixed Value of the property or null.
275. * @ignore
276. */
277. public function __get( $propertyName )
278. {
279. switch ( $propertyName )
280. {
281. case 'options':
282. case 'formats':
283. return $this-> properties [$propertyName];
284. default:
285. break;
286. }
287. throw new ezcBasePropertyNotFoundException ( $propertyName );
288. }
290. /**
291. * Property write access.
292. *
293. * @param string $propertyName Name of the property.
294. * @param mixed $val The value for the property.
295. *
296. * @throws ezcBaseValueException
297. * If a the value for the property options is not an instance of
298. * ezcConsoleOutputOptions.
299. * @throws ezcBaseValueException
300. * If a the value for the property formats is not an instance of
301. * ezcConsoleOutputFormats.
302. * @ignore
303. */
304. public function __set( $propertyName, $val )
305. {
306. switch ( $propertyName )
307. {
308. case 'options':
309. if ( !( $val instanceof ezcConsoleOutputOptions ) )
310. {
311. throw new ezcBaseValueException ( $propertyName, $val, 'ezcConsoleOutputOptions' );
312. }
313. $this-> properties ['options'] = $val;
314. return;
315. case 'formats':
316. if ( !( $val instanceof ezcConsoleOutputFormats ) )
317. {
318. throw new ezcBaseValueException ( $propertyName, $val, 'ezcConsoleOutputFormats' );
319. }
320. $this-> properties ['formats'] = $val;
321. return;
322. default:
323. break;
324. }
325. throw new ezcBasePropertyNotFoundException ( $propertyName );
326. }
328. /**
329. * Property isset access.
330. *
331. * @param string $propertyName Name of the property.
332. * @return bool True is the property is set, otherwise false.
333. * @ignore
334. */
335. public function __isset( $propertyName )
336. {
337. switch ( $propertyName )
338. {
339. case 'options':
340. case 'formats':
341. return true;
342. }
343. return false;
344. }
346. /**
347. * Print text to the console.
348. *
349. * Output a string to the console. If $format parameter is omitted, the
350. * default style is chosen. Style can either be a special style {@link }
351. * ezcConsoleOutput::$options}, a style name {@link }
352. * ezcConsoleOutput::$formats} or 'default' to print with the default
353. * styling.
354. *
355. * The $format parameter defines the name of a format. Formats are defined
356. * through the $formats proprty, which contains format definitions in form
357. * of {@link ezcConsoleOutputFormat} objects. The format influences the
358. * outer appearance of a message (e.g. color) as well as the target the
359. * message is printed to (e.g. STDERR).
360. *
361. * @throws ezcConsoleInvalidOutputTargetException
362. * If the given target ({@link ezcConsoleOutputFormat}) could not
363. * be opened for writing or writing failed.
364. *
365. * @param string $text The text to print.
366. * @param string $format Format chosen for printing.
367. * @param int $verbosityLevel On which verbose level to output this message.
368. * @return void
369. */
370. public function outputText ( $text, $format = 'default', $verbosityLevel = 1 )
371. {
372. if ( $this-> properties ['options']->verbosityLevel >= $verbosityLevel )
373. {
374. if ( is_int ( $this-> properties ['options']->autobreak ) && $this-> properties ['options']->autobreak > 0 )
375. {
376. $textLines = preg_split ( "(\r\n|\n|\r)", $text );
377. foreach ( $textLines as $id => $textLine )
378. {
379. $textLines[$id] = wordwrap ( $textLine, $this-> properties ['options']->autobreak, PHP_EOL, true );
380. }
381. $text = implode ( PHP_EOL, $textLines );
382. }
383. // Initialize target, if not happened before
384. if ( !isset( $this->targets[$this->formats->$format->target] ) )
385. {
386. // @ to suppress the warning. We handle error cases with an
387. // exception here.
388. if ( ( $this->targets[$this->formats->$format->target] = @ fopen ( $this->formats->$format->target, "w" ) ) === false )
389. {
390. throw new ezcConsoleInvalidOutputTargetException ( $this->formats->$format->target );
391. }
392. }
393. // Print using formats or without. Note: Since the target is a part
394. // of the format, it will also be ignored, if you switch formats off!
395. if ( $this-> properties ['options']->useFormats === true )
396. {
397. if ( fwrite ( $this->targets[$this->formats->$format->target], $this-> formatText ( $text, $format ) ) === false )
398. {
399. throw new ezcConsoleInvalidOutputTargetException ( $this->formats->$format->target );
400. }
401. }
402. else
403. {
404. echo $text;
405. }
406. }
407. }
409. /**
410. * Print text to the console and automatically append a line break.
411. *
412. * This method acts similar to {@link ezcConsoleOutput::outputText()}, in
413. * fact it even uses it. The difference is, that outputLine()
414. * automatically appends a manual line break to the printed text. Besides
415. * that, you can leave out the $text parameter of outputLine() to only
416. * print a line break.
417. *
418. * The $format parameter defines the name of a format. Formats are defined
419. * through the $formats proprty, which contains format definitions in form
420. * of {@link ezcConsoleOutputFormat} objects. The format influences the
421. * outer appearance of a message (e.g. color) as well as the target the
422. * message is printed to (e.g. STDERR).
423. *
424. * @param string $text The text to print.
425. * @param string $format Format chosen for printing.
426. * @param int $verbosityLevel On which verbose level to output this message.
427. * @return void
428. */
429. public function outputLine ( $text = '', $format = 'default', $verbosityLevel = 1 )
430. {
431. $this-> outputText ( $text . PHP_EOL, $format, $verbosityLevel );
432. }
434. /**
435. * Returns a formated version of the text.
436. *
437. * If $format parameter is omitted, the default style is chosen. The format
438. * must be a valid registered format definition. For information on the
439. * formats, see {@link ezcConsoleOutput::$formats}.
440. *
441. * @param string $text Text to apply style to.
442. * @param string $format Format chosen to be applied.
443. * @return string
444. */
445. public function formatText ( $text, $format = 'default' )
446. {
447. switch ( ezcBaseFeatures :: os () )
448. {
449. case "Windows":
450. return $text;
451. default:
452. return $this-> buildSequence ( $format ) . $text . $this-> buildSequence ( 'default' );
453. }
454. }
456. /**
457. * Stores the current cursor position.
458. *
459. * Saves the current cursor position to return to it using
460. * {@link ezcConsoleOutput::restorePos()}. Multiple calls
461. * to this method will override each other. Only the last
462. * position is saved.
463. *
464. * @return void
465. */
466. public function storePos ()
467. {
468. if ( ezcBaseFeatures :: os () !== "Windows" )
469. {
470. echo "\0337";
471. $this-> positionStored = true;
472. }
473. }
475. /**
476. * Restores a cursor position.
477. *
478. * Restores the cursor position last saved using {@link }
479. * ezcConsoleOutput::storePos()}.
480. *
481. * @throws ezcConsoleNoPositionStoredException
482. * If no position is saved.
483. * @return void
484. */
485. public function restorePos ()
486. {
487. if ( ezcBaseFeatures :: os () !== "Windows" )
488. {
489. if ( $this-> positionStored === false )
490. {
491. throw new ezcConsoleNoPositionStoredException ();
492. }
493. echo "\0338";
494. }
495. }
497. /**
498. * Move the cursor to a specific column of the current line.
499. *
500. * Moves the cursor to a specific column index of the current line (default
501. * is 1).
502. *
503. * @param int $column Column to jump to.
504. * @return void
505. */
506. public function toPos ( $column = 1 )
507. {
508. if ( ezcBaseFeatures :: os () !== "Windows" )
509. {
510. echo "\033[{$column}G";
511. }
512. }
514. /**
515. * Returns if a format code is valid for the specific formating option.
516. *
517. * This method determines if a given code is valid for a specific
518. * formatting option ('color', 'bgcolor' or 'style').
519. *
520. * @see ezcConsoleOutput::getFormatCode();
521. *
522. * @param string $type Formating type.
523. * @param string $key Format option name.
524. * @return bool True if the code is valid.
525. */
526. public static function isValidFormatCode ( $type, $key )
527. {
528. return isset( self::${$type}[$key] );
529. }
531. /**
532. * Returns the escape sequence for a specific format.
533. *
534. * Returns the default format escape sequence, if the requested format does
535. * not exist.
536. *
537. * @param string $format Name of the format.
538. * @return string The escape sequence.
539. */
540. protected function buildSequence ( $format = 'default' )
541. {
542. if ( $format === 'default' )
543. {
544. return sprintf( $this->escapeSequence, 0 );
545. }
546. $modifiers = array();
547. $formats = array( 'color', 'style', 'bgcolor' );
548. foreach ( $formats as $formatType )
549. {
550. // Get modifiers
551. if ( is_array ( $this->formats->$format->$formatType ) )
552. {
553. if ( ! in_array ( 'default', $this->formats->$format->$formatType ) )
554. {
555. foreach ( $this->formats->$format->$formatType as $singleVal )
556. {
557. $modifiers[] = $this-> getFormatCode ( $formatType, $singleVal );
558. }
559. }
560. }
561. else
562. {
563. if ( $this->formats->$format->$formatType !== 'default' )
564. {
565. $modifiers[] = $this-> getFormatCode ( $formatType, $this->formats->$format->$formatType );
566. }
567. }
568. }
569. // Merge modifiers
570. return sprintf ( $this->escapeSequence, implode ( ';', $modifiers ) );
571. }
573. /**
574. * Returns the code for a given formating option of a given type.
575. *
576. * $type is the type of formating ('color', 'bgcolor' or 'style'), $key the
577. * name of the format to lookup. Returns the numeric code for the requested
578. * format or 0 if format or type do not exist.
579. *
580. * @see ezcConsoleOutput::isValidFormatCode()
581. *
582. * @param string $type Formatting type.
583. * @param string $key Format option name.
584. * @return int The code representation.
585. */
586. protected function getFormatCode ( $type, $key )
587. {
588. if ( ! ezcConsoleOutput :: isValidFormatCode ( $type, $key ) )
589. {
590. return 0;
591. }
592. return ezcConsoleOutput ::${$type}[$key];
593. }
595. }
596. ?>

Documentation generated by phpDocumentor 1.4.3