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.  */
  27.  
  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. {
  95.  
  96.     /**
  97.      * Target to print to standard out, with output buffering possibility.
  98.      */
  99.     const TARGET_OUTPUT "php://output";
  100.  
  101.     /**
  102.      * Target to print to standard out.
  103.      */
  104.     const TARGET_STDOUT "php://stdout";
  105.  
  106.     /**
  107.      * Target to print to standard error.
  108.      */
  109.     const TARGET_STDERR "php://stderr";
  110.  
  111.     /**
  112.      * Container to hold the properties
  113.      *
  114.      * @var array(string=>mixed) 
  115.      */
  116.     protected $properties;
  117.  
  118.     /**
  119.      * Whether a position has been stored before, using the storePos() method.
  120.      *
  121.      * @see ezcConsoleOutput::storePos()
  122.      * @var bool 
  123.      */
  124.     protected $positionStored = false;
  125.  
  126.     /**
  127.      * Stores the mapping of color names to their escape
  128.      * sequence values.
  129.      *
  130.      * @var array(string=>int) 
  131.      */
  132.     protected static $color array(
  133.         'gray'          => 30,
  134.         'black'         => 30,      // Alias black to gray (Bug #8478)
  135.         'red'           => 31,
  136.         'green'         => 32,
  137.         'yellow'        => 33,
  138.         'blue'          => 34,
  139.         'magenta'       => 35,
  140.         'cyan'          => 36,
  141.         'white'         => 37,
  142.         'default'       => 39
  143.     );
  144.  
  145.     /**
  146.      * Stores the mapping of bgcolor names to their escape
  147.      * sequence values.
  148.      * 
  149.      * @var array(string=>int) 
  150.      */
  151.     protected static $bgcolor array(
  152.         'gray'       => 40,      // Alias gray to black (Bug #8478)
  153.         'black'      => 40,
  154.         'red'        => 41,
  155.         'green'      => 42,
  156.         'yellow'     => 43,
  157.         'blue'       => 44,
  158.         'magenta'    => 45,
  159.         'cyan'       => 46,
  160.         'white'      => 47,
  161.         'default'    => 49,
  162.     );
  163.  
  164.     /**
  165.      * Stores the mapping of styles names to their escape
  166.      * sequence values.
  167.      * 
  168.      * @var array(string=>int) 
  169.      */
  170.     protected static $style array
  171.         'default'           => '0',
  172.     
  173.         'bold'              => 1,
  174.         'faint'             => 2,
  175.         'normal'            => 22,
  176.         
  177.         'italic'            => 3,
  178.         'notitalic'         => 23,
  179.         
  180.         'underlined'        => 4,
  181.         'doubleunderlined'  => 21,
  182.         'notunderlined'     => 24,
  183.         
  184.         'blink'             => 5,
  185.         'blinkfast'         => 6,
  186.         'noblink'           => 25,
  187.         
  188.         'negative'          => 7,
  189.         'positive'          => 27,
  190.     );
  191.  
  192.     /**
  193.      * Basic escape sequence string. Use sprintf() to insert escape codes.
  194.      * 
  195.      * @var string 
  196.      */
  197.     private $escapeSequence "\033[%sm";
  198.  
  199.     /**
  200.      * Collection of targets to print to.
  201.      * 
  202.      * @var array 
  203.      */
  204.     private $targets array();
  205.  
  206.     /**
  207.      * Create a new console output handler.
  208.      *
  209.      * @see ezcConsoleOutput::$options
  210.      * @see ezcConsoleOutputOptions
  211.      * @see ezcConsoleOutput::$formats
  212.      * @see ezcConsoleOutputFormats
  213.      *
  214.      * @param ezcConsoleOutputFormats $formats Formats to be used for output.
  215.      * @param array(string=>string) $options   Options to set.
  216.      */
  217.     public function __constructezcConsoleOutputFormats $formats nullarray $options array() )
  218.     {
  219.         $options = isset$options $options new ezcConsoleOutputOptions();
  220.         $formats = isset$formats $formats new ezcConsoleOutputFormats();
  221.         $this->properties['options'new ezcConsoleOutputOptions$options );
  222.         $this->properties['formats'$formats;
  223.     }
  224.     
  225.     /**
  226.      * Set new options.
  227.      * This method allows you to change the options of an output handler.
  228.      *  
  229.      * @param ezcConsoleOutputOptions $options The options to set.
  230.      *
  231.      * @throws ezcBaseSettingNotFoundException
  232.      *          If you tried to set a non-existent option value.
  233.      * @throws ezcBaseSettingValueException
  234.      *          If the value is not valid for the desired option.
  235.      * @throws ezcBaseValueException
  236.      *          If you submit neither an array nor an instance of
  237.      *          ezcConsoleOutputOptions.
  238.      */
  239.     public function setOptions$options 
  240.     {
  241.         if is_array$options ) ) 
  242.         {
  243.             $this->properties['options']->merge$options );
  244.         
  245.         else if $options instanceof ezcConsoleOutputOptions 
  246.         {
  247.             $this->properties['options'$options;
  248.         }
  249.         else
  250.         {
  251.             throw new ezcBaseValueException"options"$options"instance of ezcConsoleOutputOptions" );
  252.         }
  253.     }
  254.  
  255.     /**
  256.      * Returns the current options.
  257.      * Returns the options currently set for this output handler.
  258.      * 
  259.      * @return ezcConsoleOutputOptions The current options.
  260.      */
  261.     public function getOptions()
  262.     {
  263.         return $this->properties['options'];
  264.     }
  265.  
  266.     /**
  267.      * Property read access.
  268.      *
  269.      * @throws ezcBasePropertyNotFoundException
  270.      *          If the the desired property is not found.
  271.      * 
  272.      * @param string $propertyName Name of the property.
  273.      * @return mixed Value of the property or null.
  274.      * @ignore
  275.      */
  276.     public function __get$propertyName )
  277.     {
  278.         switch $propertyName 
  279.         {
  280.             case 'options':
  281.             case 'formats':
  282.                 return $this->properties[$propertyName];
  283.             default:
  284.                 break;
  285.         }
  286.         throw new ezcBasePropertyNotFoundException$propertyName );
  287.     }
  288.  
  289.     /**
  290.      * Property write access.
  291.      * 
  292.      * @param string $propertyName Name of the property.
  293.      * @param mixed $val  The value for the property.
  294.      *
  295.      * @throws ezcBaseValueException
  296.      *          If a the value for the property options is not an instance of
  297.      *          ezcConsoleOutputOptions.
  298.      * @throws ezcBaseValueException
  299.      *          If a the value for the property formats is not an instance of
  300.      *          ezcConsoleOutputFormats.
  301.      * @ignore
  302.      */
  303.     public function __set$propertyName$val )
  304.     {
  305.         switch $propertyName 
  306.         {
  307.             case 'options':
  308.                 if !$val instanceof ezcConsoleOutputOptions ) )
  309.                 {
  310.                     throw new ezcBaseValueException$propertyName$val'ezcConsoleOutputOptions' );
  311.                 }
  312.                 $this->properties['options'$val;
  313.                 return;
  314.             case 'formats':
  315.                 if !$val instanceof ezcConsoleOutputFormats ) )
  316.                 {
  317.                     throw new ezcBaseValueException$propertyName$val'ezcConsoleOutputFormats' );
  318.                 }
  319.                 $this->properties['formats'$val;
  320.                 return;
  321.             default:
  322.                 break;
  323.         }
  324.         throw new ezcBasePropertyNotFoundException$propertyName );
  325.     }
  326.  
  327.     /**
  328.      * Property isset access.
  329.      * 
  330.      * @param string $propertyName Name of the property.
  331.      * @return bool True is the property is set, otherwise false.
  332.      * @ignore
  333.      */
  334.     public function __isset$propertyName )
  335.     {
  336.         switch $propertyName )
  337.         {
  338.             case 'options':
  339.             case 'formats':
  340.                 return true;
  341.         }
  342.         return false;
  343.     }
  344.  
  345.     /**
  346.      * Print text to the console.
  347.      *
  348.      * Output a string to the console. If $format parameter is omitted, the
  349.      * default style is chosen. Style can either be a special style {@link }
  350.      * ezcConsoleOutput::$options}, a style name {@link }
  351.      * ezcConsoleOutput::$formats} or 'default' to print with the default
  352.      * styling.
  353.      *
  354.      * The $format parameter defines the name of a format. Formats are defined
  355.      * through the $formats proprty, which contains format definitions in form
  356.      * of {@link ezcConsoleOutputFormat} objects. The format influences the
  357.      * outer appearance of a message (e.g. color) as well as the target the
  358.      * message is printed to (e.g. STDERR).
  359.      *
  360.      * @throws ezcConsoleInvalidOutputTargetException
  361.      *          If the given target ({@link ezcConsoleOutputFormat}) could not
  362.      *          be opened for writing or writing failed.
  363.      *
  364.      * @param string $text        The text to print.
  365.      * @param string $format      Format chosen for printing.
  366.      * @param int $verbosityLevel On which verbose level to output this message.
  367.      * @return void 
  368.      */
  369.     public function outputText$text$format 'default'$verbosityLevel 
  370.     {
  371.         if $this->properties['options']->verbosityLevel >= $verbosityLevel 
  372.         {
  373.             if is_int$this->properties['options']->autobreak && $this->properties['options']->autobreak )
  374.             {
  375.                 $textLines preg_split"(\r\n|\n|\r)"$text );
  376.                 foreach $textLines as $id => $textLine )
  377.                 {
  378.                     $textLines[$idwordwrap$textLine$this->properties['options']->autobreakPHP_EOLtrue );
  379.                 }
  380.                 $text implodePHP_EOL$textLines );
  381.             }
  382.             // Initialize target, if not happened before
  383.             if !isset$this->targets[$this->formats->$format->target) )
  384.             {
  385.                 // @ to suppress the warning. We handle error cases with an
  386.                 // exception here.
  387.                 if ( ( $this->targets[$this->formats->$format->target@fopen$this->formats->$format->target"w" ) ) === false )
  388.                 {
  389.                     throw new ezcConsoleInvalidOutputTargetException$this->formats->$format->target );
  390.                 }
  391.             }
  392.             // Print using formats or without. Note: Since the target is a part
  393.             // of the format, it will also be ignored, if you switch formats off!
  394.             if $this->properties['options']->useFormats === true )
  395.             {
  396.                 if fwrite$this->targets[$this->formats->$format->target]$this->formatText$text$format ) ) === false )
  397.                 {
  398.                     throw new ezcConsoleInvalidOutputTargetException$this->formats->$format->target );
  399.                 }
  400.             }
  401.             else
  402.             {
  403.                echo $text;
  404.             }
  405.         }
  406.     }
  407.  
  408.     /**
  409.      * Print text to the console and automatically append a line break.
  410.      *
  411.      * This method acts similar to {@link ezcConsoleOutput::outputText()}, in
  412.      * fact it even uses it. The difference is, that outputLine()
  413.      * automatically appends a manual line break to the printed text. Besides
  414.      * that, you can leave out the $text parameter of outputLine() to only
  415.      * print a line break.
  416.      *
  417.      * The $format parameter defines the name of a format. Formats are defined
  418.      * through the $formats proprty, which contains format definitions in form
  419.      * of {@link ezcConsoleOutputFormat} objects. The format influences the
  420.      * outer appearance of a message (e.g. color) as well as the target the
  421.      * message is printed to (e.g. STDERR).
  422.      * 
  423.      * @param string $text        The text to print.
  424.      * @param string $format      Format chosen for printing.
  425.      * @param int $verbosityLevel On which verbose level to output this message.
  426.      * @return void 
  427.      */
  428.     public function outputLine$text ''$format 'default'$verbosityLevel )
  429.     {
  430.         $this->outputText$text PHP_EOL$format$verbosityLevel );
  431.     }
  432.  
  433.     /**
  434.      * Returns a formated version of the text.
  435.      *
  436.      * If $format parameter is omitted, the default style is chosen. The format
  437.      * must be a valid registered format definition.  For information on the
  438.      * formats, see {@link ezcConsoleOutput::$formats}.
  439.      *
  440.      * @param string $text   Text to apply style to.
  441.      * @param string $format Format chosen to be applied.
  442.      * @return string 
  443.      */
  444.     public function formatText$text$format 'default' 
  445.     {
  446.         switch ezcBaseFeatures::os() )
  447.         {
  448.             case "Windows":
  449.                 return $text;
  450.             default:
  451.                 return $this->buildSequence$format $text $this->buildSequence'default' );
  452.         }
  453.     }
  454.  
  455.     /**
  456.      * Stores the current cursor position.
  457.      *
  458.      * Saves the current cursor position to return to it using
  459.      * {@link ezcConsoleOutput::restorePos()}. Multiple calls
  460.      * to this method will override each other. Only the last
  461.      * position is saved.
  462.      *
  463.      * @return void 
  464.      */
  465.     public function storePos(
  466.     {
  467.         if ezcBaseFeatures::os(!== "Windows" )
  468.         {
  469.             echo "\0337";
  470.             $this->positionStored = true;
  471.         }
  472.     }
  473.  
  474.     /**
  475.      * Restores a cursor position.
  476.      *
  477.      * Restores the cursor position last saved using {@link }
  478.      * ezcConsoleOutput::storePos()}.
  479.      *
  480.      * @throws ezcConsoleNoPositionStoredException
  481.      *          If no position is saved.
  482.      * @return void 
  483.      */
  484.     public function restorePos(
  485.     {
  486.         if ezcBaseFeatures::os(!== "Windows" )
  487.         {
  488.             if $this->positionStored === false )
  489.             {
  490.                 throw new ezcConsoleNoPositionStoredException();
  491.             }
  492.             echo "\0338";
  493.         }
  494.     }
  495.  
  496.     /**
  497.      * Move the cursor to a specific column of the current line.
  498.      *
  499.      * Moves the cursor to a specific column index of the current line (default
  500.      * is 1).
  501.      * 
  502.      * @param int $column Column to jump to.
  503.      * @return void 
  504.      */
  505.     public function toPos$column 
  506.     {
  507.         if ezcBaseFeatures::os(!== "Windows" )
  508.         {
  509.             echo "\033[{$column}G";
  510.         }
  511.     }
  512.  
  513.     /**
  514.      * Returns if a format code is valid for the specific formating option.
  515.      *
  516.      * This method determines if a given code is valid for a specific
  517.      * formatting option ('color', 'bgcolor' or 'style').
  518.      * 
  519.      * @see ezcConsoleOutput::getFormatCode();
  520.      *
  521.      * @param string $type Formating type.
  522.      * @param string $key  Format option name.
  523.      * @return bool True if the code is valid.
  524.      */
  525.     public static function isValidFormatCode$type$key )
  526.     {
  527.         return issetself::${$type}[$key);
  528.     }
  529.  
  530.     /**
  531.      * Returns the escape sequence for a specific format.
  532.      *
  533.      * Returns the default format escape sequence, if the requested format does
  534.      * not exist.
  535.      * 
  536.      * @param string $format Name of the format.
  537.      * @return string The escape sequence.
  538.      */
  539.     protected function buildSequence$format 'default' )
  540.     {
  541.         if $format === 'default' )
  542.         {
  543.             return sprintf$this->escapeSequence);
  544.         }
  545.         $modifiers array();
  546.         $formats array'color''style''bgcolor' );
  547.         foreach $formats as $formatType 
  548.         {
  549.             // Get modifiers
  550.             if is_array$this->formats->$format->$formatType ) )
  551.             {
  552.                 if !in_array'default'$this->formats->$format->$formatType ) )
  553.                 {
  554.                     foreach $this->formats->$format->$formatType as $singleVal 
  555.                     {
  556.                         $modifiers[$this->getFormatCode$formatType$singleVal );
  557.                     }
  558.                 }
  559.             }
  560.             else
  561.             {
  562.                 if $this->formats->$format->$formatType !== 'default' )
  563.                 {
  564.                     $modifiers[$this->getFormatCode$formatType$this->formats->$format->$formatType );
  565.                 }
  566.             }
  567.         }
  568.         // Merge modifiers
  569.         return sprintf$this->escapeSequenceimplode';'$modifiers ) );
  570.     }
  571.  
  572.     /**
  573.      * Returns the code for a given formating option of a given type.
  574.      *
  575.      * $type is the type of formating ('color', 'bgcolor' or 'style'), $key the
  576.      * name of the format to lookup. Returns the numeric code for the requested
  577.      * format or 0 if format or type do not exist.
  578.      * 
  579.      * @see ezcConsoleOutput::isValidFormatCode()
  580.      * 
  581.      * @param string $type Formatting type.
  582.      * @param string $key  Format option name.
  583.      * @return int The code representation.
  584.      */
  585.     protected function getFormatCode$type$key )
  586.     {
  587.         if !ezcConsoleOutput::isValidFormatCode$type$key ) ) 
  588.         {
  589.             return 0;
  590.         }
  591.         return ezcConsoleOutput::${$type}[$key];
  592.     }
  593.  
  594. }
  595. ?>
Documentation generated by phpDocumentor 1.4.3