Apache Zeta Components Manual :: File Source for input.php

Source for file input.php

Documentation is available at input.php

  1. <?php
  2. /**
  3.  * File containing the ezcConsoleInput 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.  * The ezcConsoleInput class handles the given options and arguments on the console.
  30.  * 
  31.  * This class allows the complete handling of options and arguments submitted
  32.  * to a console based application.
  33.  *
  34.  * The next example demonstrate how to capture the console options:
  35.  * 
  36.  * <code>
  37.  * $optionHandler = new ezcConsoleInput();
  38.  * 
  39.  * // Register simple parameter -h/--help
  40.  * $optionHandler->registerOption( new ezcConsoleOption( 'h', 'help' ) );
  41.  * 
  42.  * // Register complex parameter -f/--file
  43.  * $file = new ezcConsoleOption(
  44.  *  'f',
  45.  *  'file',
  46.  *  ezcConsoleInput::TYPE_STRING,
  47.  *  null,
  48.  *  false,
  49.  *  'Process a file.',
  50.  *  'Processes a single file.'
  51.  * );
  52.  * $optionHandler->registerOption( $file );
  53.  * 
  54.  * // Manipulate parameter -f/--file after registration
  55.  * $file->multiple = true;
  56.  * 
  57.  * // Register another complex parameter that depends on -f and excludes -h
  58.  * $dir = new ezcConsoleOption(
  59.  *  'd',
  60.  *  'dir',
  61.  *  ezcConsoleInput::TYPE_STRING,
  62.  *  null,
  63.  *  true,
  64.  *  'Process a directory.',
  65.  *  'Processes a complete directory.',
  66.  *  array( new ezcConsoleOptionRule( $optionHandler->getOption( 'f' ) ) ),
  67.  *  array( new ezcConsoleOptionRule( $optionHandler->getOption( 'h' ) ) )
  68.  * );
  69.  * $optionHandler->registerOption( $dir );
  70.  * 
  71.  * // Register an alias for this parameter
  72.  * $optionHandler->registerAlias( 'e', 'extended-dir', $dir );
  73.  * 
  74.  * // Process registered parameters and handle errors
  75.  * try
  76.  * {
  77.  *      $optionHandler->process( array( 'example_input.php', '-h' ) );
  78.  * }
  79.  * catch ( ezcConsoleOptionException $e )
  80.  * {
  81.  *      echo $e->getMessage();
  82.  *      exit( 1 );
  83.  * }
  84.  * 
  85.  * // Process a single parameter
  86.  * $file = $optionHandler->getOption( 'f' );
  87.  * if ( $file->value === false )
  88.  * {
  89.  *      echo "Parameter -{$file->short}/--{$file->long} was not submitted.\n";
  90.  * }
  91.  * elseif ( $file->value === true )
  92.  * {
  93.  *      echo "Parameter -{$file->short}/--{$file->long} was submitted without value.\n";
  94.  * }
  95.  * else
  96.  * {
  97.  *      echo "Parameter -{$file->short}/--{$file->long} was submitted with value '".var_export($file->value, true)."'.\n";
  98.  * }
  99.  * 
  100.  * // Process all parameters at once:
  101.  * foreach ( $optionHandler->getOptionValues() as $paramShort => $val )
  102.  * {
  103.  *      switch ( true )
  104.  *      {
  105.  *          case $val === false:
  106.  *              echo "Parameter $paramShort was not submitted.\n";
  107.  *              break;
  108.  *          case $val === true:
  109.  *              echo "Parameter $paramShort was submitted without a value.\n";
  110.  *              break;
  111.  *          case is_array( $val ):
  112.  *              echo "Parameter $paramShort was submitted multiple times with value: '".implode(', ', $val)."'.\n";
  113.  *              break;
  114.  *          default:
  115.  *              echo "Parameter $paramShort was submitted with value: '$val'.\n";
  116.  *              break;
  117.  *      }
  118.  * }
  119.  * </code>
  120.  * 
  121.  * @package ConsoleTools
  122.  * @version //autogen//
  123.  * @mainclass
  124.  *
  125.  * @property ezcConsoleArguments $argumentDefinition Optional argument definition.
  126.  */
  127. {
  128.     /**
  129.      * Option does not carry a value.
  130.      */
  131.     const TYPE_NONE     1;
  132.  
  133.     /**
  134.      * Option takes an integer value.
  135.      */
  136.     const TYPE_INT      2;
  137.  
  138.     /**
  139.      * Option takes a string value.
  140.      */
  141.     const TYPE_STRING   3;
  142.  
  143.     /**
  144.      * Array of option definitions, indexed by number.
  145.      *
  146.      * This array stores the ezcConsoleOption objects representing
  147.      * the options.
  148.      *
  149.      * For lookup of an option after its short or long values the attributes
  150.      * {@link ezcConsoleInput::$optionShort}
  151.      * {@link ezcConsoleInput::$optionLong}
  152.      * are used.
  153.      * 
  154.      * @var array(array) 
  155.      */
  156.     private $options array();
  157.  
  158.     /**
  159.      * Short option names.
  160.      *
  161.      * Each references a key in {@link ezcConsoleInput::$options}.
  162.      * 
  163.      * @var array(string=>int) 
  164.      */
  165.     private $optionShort array();
  166.  
  167.     /**
  168.      * Long option names.
  169.      * 
  170.      * Each references a key in {@link ezcConsoleInput::$options}.
  171.      * 
  172.      * @var array(string=>int) 
  173.      */
  174.     private $optionLong array();
  175.  
  176.     /**
  177.      * Arguments, if submitted, are stored here.
  178.      * 
  179.      * @var array(string) 
  180.      */
  181.     private $arguments array();
  182.  
  183.     /**
  184.      * Wether the process() method has already been called.
  185.      * 
  186.      * @var bool 
  187.      */
  188.     private $processed false;
  189.  
  190.     /**
  191.      * Indicates if an option was submitted, that has the isHelpOption flag set.
  192.      * 
  193.      * @var bool 
  194.      */
  195.     private $helpOptionSet false;
  196.  
  197.     /**
  198.      * Tool object for multi-byte encoding safe string operations.
  199.      * 
  200.      * @var ezcConsoleStringTool 
  201.      */
  202.     private $stringTool;
  203.  
  204.     /**
  205.      * Input validator.
  206.      *
  207.      * @var ezcConsoleInputValidator 
  208.      */
  209.     private $validator;
  210.  
  211.     /**
  212.      * Help generator.
  213.      * 
  214.      * @var ezcConsoleInputHelpGenerator 
  215.      */
  216.     private $helpGenerator;
  217.  
  218.     /**
  219.      * Collection of properties.
  220.      * 
  221.      * @var array(string=>mixed) 
  222.      */
  223.     protected $properties = array();
  224.  
  225.     /**
  226.      * Creates an input handler.
  227.      */
  228.     public function __construct()
  229.     {
  230.         $this->argumentDefinition null;
  231.         $this->stringTool         new ezcConsoleStringTool();
  232.  
  233.         // @TODO Verify interface and make plugable
  234.         $this->validator     new ezcConsoleStandardInputValidator();
  235.         $this->helpGenerator new ezcConsoleInputStandardHelpGenerator$this );
  236.     }
  237.  
  238.     /**
  239.      * Registers the new option $option.
  240.      *
  241.      * This method adds the new option $option to your option collection. If
  242.      * already an option with the assigned short or long value exists, an
  243.      * exception will be thrown.
  244.      *
  245.      * @see ezcConsoleInput::unregisterOption()
  246.      *
  247.      * @param ezcConsoleOption $option 
  248.      *
  249.      * @return ezcConsoleOption The recently registered option.
  250.      */
  251.     public function registerOptionezcConsoleOption $option )
  252.     {
  253.         foreach $this->optionShort as $short => $ref )
  254.         {
  255.             if $short === $option->short 
  256.             {
  257.                 throw new ezcConsoleOptionAlreadyRegisteredException$short );
  258.             }
  259.         }
  260.         foreach $this->optionLong as $long => $ref )
  261.         {
  262.             if $long === $option->long 
  263.             {
  264.                 throw new ezcConsoleOptionAlreadyRegisteredException$long );
  265.             }
  266.         }
  267.         $this->options[$option;
  268.         $this->optionLong[$option->long$option;
  269.         if $option->short !== "" )
  270.         {
  271.             $this->optionShort[$option->short$option;
  272.         }
  273.         return $option;
  274.     }
  275.  
  276.     /**
  277.      * Registers an alias for an option.
  278.      *
  279.      * Registers a new alias for an existing option. Aliases can
  280.      * be used as if they were a normal option.
  281.      *
  282.      * The alias is registered with the short option name $short and the
  283.      * long option name $long. The alias references to the existing
  284.      * option $option.
  285.      *
  286.      * @see ezcConsoleInput::unregisterAlias()
  287.      *
  288.      * @param string $short 
  289.      * @param string $long 
  290.      * @param ezcConsoleOption $option 
  291.      *
  292.      *
  293.      * @throws ezcConsoleOptionNotExistsException
  294.      *          If the referenced option is not registered.
  295.      * @throws ezcConsoleOptionAlreadyRegisteredException
  296.      *          If another option/alias has taken the provided short or long name.
  297.      * @return void 
  298.      */
  299.     public function registerAlias$short$longezcConsoleOption $option )
  300.     {
  301.         if !isset$this->optionShort[$option->short|| !isset$this->optionLong[$option->long) )
  302.         {
  303.             throw new ezcConsoleOptionNotExistsException$option->long );
  304.         }
  305.         if isset$this->optionShort[$short|| isset$this->optionLong[$long) )
  306.         {
  307.             throw new ezcConsoleOptionAlreadyRegisteredExceptionisset$this->optionShort[$short"-$short"--$long);
  308.         }
  309.         $this->optionShort[$short$option;
  310.         $this->optionLong[$long]   $option;
  311.     }
  312.  
  313.     /**
  314.      * Registers options according to a string specification.
  315.      *
  316.      * Accepts a string to define parameters and registers all parameters as
  317.      * options accordingly. String definition, specified in $optionDef, looks
  318.      * like this:
  319.      *
  320.      * <code>
  321.      * [s:|size:][u:|user:][a:|all:]
  322.      * </code>
  323.      *
  324.      * This string registers 3 parameters:
  325.      * -s / --size
  326.      * -u / --user
  327.      * -a / --all
  328.      *
  329.      * @param string $optionDef 
  330.      * @return void 
  331.      * 
  332.      * @throws ezcConsoleOptionStringNotWellformedException
  333.      *          If provided string does not have the correct format.
  334.      */
  335.     public function registerOptionString$optionDef 
  336.     {
  337.         $regex '\[([a-z0-9-]+)([:?*+])?([^|]*)\|([a-z0-9-]+)([:?*+])?\]';
  338.         // Check string for wellformedness
  339.         if preg_match"/^($regex)+$/"$optionDef == )
  340.         {
  341.             throw new ezcConsoleOptionStringNotWellformedException"Option definition not wellformed: \"$optionDef\");
  342.         }
  343.         if preg_match_all"/$regex/"$optionDef$matches ) )
  344.         {
  345.             foreach $matches[1as $id => $short )
  346.             {
  347.                 $option null;
  348.                 $option new ezcConsoleOption$short$matches[4][$id);
  349.                 if !empty$matches[2][$id|| !empty$matches[5][$id) )
  350.                 {
  351.                     switch !empty$matches[2][$id$matches[2][$id$matches[5][$id)
  352.                     {
  353.                         case '*':
  354.                             // Allows 0 or more occurances
  355.                             $option->multiple true;
  356.                             break;
  357.                         case '+':
  358.                             // Allows 1 or more occurances
  359.                             $option->multiple true;
  360.                             $option->type self::TYPE_STRING;
  361.                             break;
  362.                         case '?':
  363.                             $option->type self::TYPE_STRING;
  364.                             $option->default '';
  365.                             break;
  366.                         default:
  367.                             break;
  368.                     }
  369.                 }
  370.                 if !empty$matches[3][$id) )
  371.                 {
  372.                     $option->default $matches[3][$id];
  373.                 }
  374.                 $this->registerOption$option );
  375.             }
  376.         }
  377.     }
  378.  
  379.     /**
  380.      * Removes an option.
  381.      *
  382.      * This function removes an option. All dependencies to that
  383.      * specific option are removed completely from every other registered
  384.      * option.
  385.      *
  386.      * @see ezcConsoleInput::registerOption()
  387.      *
  388.      * @param ezcConsoleOption $option The option object to unregister.
  389.      *
  390.      * @throws ezcConsoleOptionNotExistsException
  391.      *          If requesting a not registered option.
  392.      * @return void 
  393.      */
  394.     public function unregisterOptionezcConsoleOption $option )
  395.     {
  396.         $found false;
  397.         foreach $this->options as $id => $existParam )
  398.         {
  399.             if $existParam === $option )
  400.             {
  401.                 $found true;
  402.                 unset$this->options[$id);
  403.                 continue;
  404.             }
  405.             $existParam->removeAllExclusions$option );
  406.             $existParam->removeAllDependencies$option );
  407.         }
  408.         if $found === false )
  409.         {
  410.             throw new ezcConsoleOptionNotExistsException$option->long );
  411.         }
  412.         foreach $this->optionLong as $name => $existParam )
  413.         {
  414.             if $existParam === $option )
  415.             {
  416.                 unset$this->optionLong[$name);
  417.             }
  418.         }
  419.         foreach $this->optionShort as $name => $existParam )
  420.         {
  421.             if $existParam === $option )
  422.             {
  423.                 unset$this->optionShort[$name);
  424.             }
  425.         }
  426.     }
  427.     
  428.     /**
  429.      * Removes an alias to an option.
  430.      *
  431.      * This function removes an alias with the short name $short and long
  432.      * name $long.
  433.      *
  434.      * @see ezcConsoleInput::registerAlias()
  435.      * 
  436.      * @throws ezcConsoleOptionNoAliasException
  437.      *       If the requested short/long name belongs to a real parameter instead.
  438.      *
  439.      * @param string $short 
  440.      * @param string $long 
  441.      * @return void 
  442.      *
  443.      * @todo Check if $short and $long refer to the same option!
  444.      */
  445.     public function unregisterAlias$short$long )
  446.     {
  447.         foreach $this->options as $id => $option )
  448.         {
  449.             if $option->short === $short )
  450.             {
  451.                 throw new ezcConsoleOptionNoAliasException$short );
  452.             }
  453.             if $option->long === $long )
  454.             {
  455.                 throw new ezcConsoleOptionNoAliasException$long );
  456.             }
  457.         }
  458.         if isset$this->optionShort[$short) )
  459.         {
  460.             unset$this->optionShort[$short);
  461.         }
  462.         if isset$this->optionLong[$long) )
  463.         {
  464.             unset$this->optionLong[$long);
  465.         }
  466.     }
  467.  
  468.     /**
  469.      * Returns the definition object for the option with the name $name.
  470.      *
  471.      * This method receives the long or short name of an option and
  472.      * returns the ezcConsoleOption object.
  473.      * 
  474.      * @param string $name  Short or long name of the option (without - or --).
  475.      * @return ezcConsoleOption 
  476.      *
  477.      * @throws ezcConsoleOptionNotExistsException
  478.      *          If requesting a not registered parameter.
  479.      */
  480.     public function getOption$name )
  481.     {
  482.         $name $name;
  483.         if isset$this->optionShort[$name) )
  484.         {
  485.             return $this->optionShort[$name];
  486.         }
  487.         if isset$this->optionLong[$name) )
  488.         {
  489.             return $this->optionLong[$name];
  490.         }
  491.         throw new ezcConsoleOptionNotExistsException$name );
  492.     }
  493.  
  494.     /**
  495.      * Process the input parameters.
  496.      *
  497.      * Actually process the input options and arguments according to the actual
  498.      * settings.
  499.      * 
  500.      * Per default this method uses $argc and $argv for processing. You can
  501.      * override this setting with your own input, if necessary, using the
  502.      * parameters of this method. (Attention, first argument is always the pro
  503.      * gram name itself!)
  504.      *
  505.      * All exceptions thrown by this method contain an additional attribute "option"
  506.      * which specifies the parameter on which the error occurred.
  507.      * 
  508.      * @param array(string) $args The arguments
  509.      * @return void 
  510.      *
  511.      * @throws ezcConsoleOptionNotExistsException
  512.      *          If an option that was submitted does not exist.
  513.      * @throws ezcConsoleOptionDependencyViolationException
  514.      *          If a dependency rule was violated.
  515.      * @throws ezcConsoleOptionExclusionViolationException
  516.      *          If an exclusion rule was violated.
  517.      * @throws ezcConsoleOptionTypeViolationException
  518.      *          If the type of a submitted value violates the options type rule.
  519.      * @throws ezcConsoleOptionArgumentsViolationException
  520.      *          If arguments are passed although a parameter disallowed them.
  521.      *
  522.      * @see ezcConsoleOptionException
  523.      */ 
  524.     public function processarray $args null )
  525.     {
  526.         if $this->processed )
  527.         {
  528.             $this->reset();
  529.         }
  530.         $this->processed true;
  531.  
  532.         if !isset$args ) )
  533.         {
  534.             $args = isset$argv $argv : isset$_SERVER['argv'$_SERVER['argv'array();
  535.         }
  536.  
  537.         $nextIndex $this->processOptions$args );
  538.  
  539.         if $this->helpOptionSet() )
  540.         {
  541.             // No need to parse arguments
  542.             return;
  543.         }
  544.  
  545.         $this->processArguments$args$nextIndex );
  546.  
  547.         $this->checkRules();
  548.  
  549.         $this->setOptionDefaults();
  550.     }
  551.  
  552.     /**
  553.      * Sets defaults for options that have not been submitted.
  554.      *
  555.      * Checks all options if they have been submited. If not and a default
  556.      * values is present, this is set as the options value.
  557.      */
  558.     private function setOptionDefaults()
  559.     {
  560.         foreach $this->options as $option )
  561.         {
  562.             if $option->value === false || $option->value === array() )
  563.             {
  564.                 // Default value to set?
  565.                 if $option->default !== null )
  566.                 {
  567.                     $option->value $option->default;
  568.                 }
  569.             }
  570.         }
  571.     }
  572.  
  573.     /**
  574.      * Reads the submitted options from $args array.
  575.      *
  576.      * Returns the next index to check for arguments.
  577.      * 
  578.      * @param array(string) $args 
  579.      * @returns int
  580.      *
  581.      * @throws ezcConsoleOptionNotExistsException
  582.      *          if a submitted option does not exist.
  583.      * @throws ezcConsoleOptionTooManyValuesException
  584.      *          if an option that expects only a single value was submitted
  585.      *          with multiple values.
  586.      * @throws ezcConsoleOptionTypeViolationException
  587.      *          if an option was submitted with a value of the wrong type.
  588.      * @throws ezcConsoleOptionMissingValueException
  589.      *          if an option thats expects a value was submitted without.
  590.      */
  591.     private function processOptionsarray $args )
  592.     {
  593.         $numArgs count$args );
  594.         $i 1;
  595.  
  596.         while $i $numArgs )
  597.         {
  598.             if $args[$i=== '--' )
  599.             {
  600.                 break;
  601.             }
  602.  
  603.             // Equalize parameter handling (long params with =)
  604.             if iconv_substr$args[$i]02'UTF-8' == '--' )
  605.             {
  606.                 $this->preprocessLongOption$args$i );
  607.                 // Update number of args, changed by preprocessLongOption()
  608.                 $numArgs count$args );
  609.             }
  610.  
  611.             // Check for parameter
  612.             if iconv_substr$args[$i]01'UTF-8' === '-' )
  613.             {
  614.                 if !$this->hasOptionpreg_replace'/^-*/'''$args[$i) ) )
  615.                 {
  616.                     throw new ezcConsoleOptionNotExistsException$args[$i);
  617.                 }
  618.                 $this->processOption$args$i );
  619.             }
  620.             // Must be the arguments
  621.             else
  622.             {
  623.                 break;
  624.             }
  625.         }
  626.  
  627.         // Move pointer over argument sign
  628.         isset$args[$i&& $args[$i== '--' ? ++$i $i;
  629.  
  630.         return $i;
  631.     }
  632.  
  633.     /**
  634.      * Resets all option and argument values.
  635.      *
  636.      * This method is called automatically by {@link process()}, if this method
  637.      * is called twice or more, and may also be used to manually reset the
  638.      * values of all registered {@ezcConsoleOption} and {@link }
  639.      * ezcConsoleArgument} objects.
  640.      */
  641.     public function reset()
  642.     {
  643.         foreach $this->options as $option )
  644.         {
  645.             $option->value false;
  646.         }
  647.         if $this->argumentDefinition !== null )
  648.         {
  649.             foreach $this->argumentDefinition as $argument )
  650.             {
  651.                 $argument->value null;
  652.             }
  653.         }
  654.         $this->arguments array();
  655.     }
  656.  
  657.     /**
  658.      * Returns true if an option with the given name exists, otherwise false.
  659.      *
  660.      * Checks if an option with the given name is registered.
  661.      * 
  662.      * @param string $name Short or long name of the option.
  663.      * @return bool True if option exists, otherwise false.
  664.      */
  665.     public function hasOption$name )
  666.     {
  667.         try
  668.         {
  669.             $param $this->getOption$name );
  670.         }
  671.         catch ezcConsoleOptionNotExistsException $e )
  672.         {
  673.             return false;
  674.         }
  675.         return true;
  676.     }
  677.  
  678.     /**
  679.      * Returns an array of all registered options.
  680.      *
  681.      * Returns an array of all registered options in the following format:
  682.      * <code>
  683.      * array(
  684.      *      0 => ezcConsoleOption,
  685.      *      1 => ezcConsoleOption,
  686.      *      2 => ezcConsoleOption,
  687.      *      ...
  688.      * );
  689.      * </code>
  690.      *
  691.      * @return array(string=>ezcConsoleOption) Registered options.
  692.      */
  693.     public function getOptions()
  694.     {
  695.         return $this->options;
  696.     }
  697.  
  698.     /**
  699.      * Returns the values of all submitted options.
  700.      *
  701.      * Returns an array of all values submitted to the options. The array is
  702.      * indexed by the parameters short name (excluding the '-' prefix). The array
  703.      * does not contain any parameter, which value is 'false' (meaning: the
  704.      * parameter was not submitted).
  705.      * 
  706.      * @param bool $longnames Wheather to use longnames for indexing.
  707.      * @return array(string=>mixed) 
  708.      */
  709.     public function getOptionValues$longnames false )
  710.     {
  711.         $res array();
  712.         foreach $this->options as $param )
  713.         {
  714.             if $param->value !== false 
  715.             {
  716.                 $res[$longnames === true $param->long $param->short$param->value;
  717.             }
  718.         }
  719.         return $res;
  720.     }
  721.  
  722.     /**
  723.      * Returns arguments provided to the program.
  724.      *
  725.      * This method returns all arguments provided to a program in an
  726.      * int indexed array. Arguments are sorted in the way
  727.      * they are submitted to the program. You can disable arguments
  728.      * through the 'arguments' flag of a parameter, if you want
  729.      * to disallow arguments.
  730.      *
  731.      * Arguments are either the last part of the program call (if the
  732.      * last parameter is not a 'multiple' one) or divided via the '--'
  733.      * method which is commonly used on Unix (if the last parameter
  734.      * accepts multiple values this is required).
  735.      *
  736.      * @return array(string) Arguments.
  737.      */
  738.     public function getArguments()
  739.     {
  740.         return $this->arguments;
  741.     }
  742.  
  743.     /**
  744.      * Get help information for your options.
  745.      *
  746.      * This method returns an array of help information for your options,
  747.      * indexed by int. Each help info has 2 fields:
  748.      *
  749.      * 0 => The options names ("<short> / <long>")
  750.      * 1 => The help text (depending on the $long parameter)
  751.      *
  752.      * The $long options determines if you want to get the short or long help
  753.      * texts. The array returned can be used by {@link ezcConsoleTable}.
  754.      *
  755.      * If using the second options, you can filter the options shown in the
  756.      * help output (e.g. to show short help for related options). Provide
  757.      * as simple number indexed array of short and/or long values to set a filter.
  758.      *
  759.      * The $paramGrouping option can be used to group options in the help
  760.      * output. The structure of this array parameter is as follows:
  761.      *
  762.      * <code>
  763.      *  array(
  764.      *      'First section' => array(
  765.      *          'input',
  766.      *          'output'
  767.      *          'overwrite',
  768.      *      ),
  769.      *      'Second section' => array(
  770.      *          'v',
  771.      *          'h',
  772.      *      ),
  773.      *  )
  774.      * </code>
  775.      *
  776.      * As can be seen, short option names are possible as well as long ones.
  777.      * The key of the first array level is the name of the section, which is
  778.      * assigned to an array of options to group under this section. The $params
  779.      * parameter still influences if an option is displayed at all.
  780.      * 
  781.      * @param bool $long 
  782.      * @param array(string) $params 
  783.      * @param array(string=>array(string)) $paramGrouping 
  784.      * @return array(array(string)) Table structure as explained.
  785.      * 
  786.      * @apichange In future versions, the default values of $params will change
  787.      *             to null instead of an empty array. Giving an empty array for
  788.      *             these will then be taken literally.
  789.      */
  790.     public function getHelp$long falsearray $params array()array $paramGrouping null )
  791.     {
  792.         // New handling
  793.         $params $params === array(|| $params === null null $params );
  794.  
  795.         $help array();
  796.         if $paramGrouping === null )
  797.         {
  798.             // Original handling
  799.             $help $this->getOptionHelpWithoutGrouping$long$params );
  800.         }
  801.         else
  802.         {
  803.             $help $this->getOptionHelpWithGrouping$long$params$paramGrouping );
  804.         }
  805.  
  806.         if $this->argumentDefinition !== null )
  807.         {
  808.             $help[array"Arguments:"'' );
  809.  
  810.             $argumentsHelp $this->helpGenerator->generateArgumentHelp$long );
  811.             if $argumentsHelp === array() )
  812.             {
  813.                 $help[array''"No arguments available." );
  814.             }
  815.             else
  816.             {
  817.                 $help array_merge$help$argumentsHelp );
  818.             }
  819.         }
  820.  
  821.         return $help;
  822.     }
  823.  
  824.     /**
  825.      * Creates the option help array in the original, ungrouped way.
  826.      *
  827.      * Creates the original help array generated by {@link getHelp()}. The
  828.      * $long and $params options are the same as they are for this method.
  829.      * 
  830.      * @param bool $long 
  831.      * @param array $params 
  832.      * @return array 
  833.      */
  834.     private function getOptionHelpWithoutGrouping$long$params )
  835.     {
  836.         return $this->helpGenerator->generateUngroupedOptionHelp(
  837.             $long,
  838.             $params
  839.         );
  840.     }
  841.  
  842.     /**
  843.      * Generates options helo array with ordering and grouping.
  844.      * 
  845.      * @param mixed $long 
  846.      * @param mixed $params 
  847.      * @param mixed $paramGrouping 
  848.      * @return array() 
  849.      */
  850.     private function getOptionHelpWithGrouping$long$params$paramGrouping )
  851.     {
  852.         $rawHelp $this->helpGenerator->generateGroupedOptionHelp(
  853.             $paramGrouping,
  854.             $long,
  855.             $params
  856.         );
  857.  
  858.         $help  array();
  859.         $first true;
  860.         foreach $rawHelp as $category => $optionsHelp )
  861.         {
  862.             if !$first )
  863.             {
  864.                 $help[array'''' );
  865.             }
  866.             else
  867.             {
  868.                 $first false;
  869.             }
  870.  
  871.             $help[array$category'' );
  872.             $help array_merge$help$optionsHelp );
  873.         }
  874.         return $help;
  875.     }
  876.  
  877.     
  878.     /**
  879.      * Get help information for your options as a table.
  880.      *
  881.      * This method provides the information returned by
  882.      * {@link ezcConsoleInput::getHelp()} in a table.
  883.      *
  884.      * The $paramGrouping option can be used to group options in the help
  885.      * output. The structure of this array parameter is as follows:
  886.      *
  887.      * <code>
  888.      *  array(
  889.      *      'First section' => array(
  890.      *          'input',
  891.      *          'output'
  892.      *          'overwrite',
  893.      *      ),
  894.      *      'Second section' => array(
  895.      *          'v',
  896.      *          'h',
  897.      *      ),
  898.      *  )
  899.      * </code>
  900.      *
  901.      * As can be seen, short option names are possible as well as long ones.
  902.      * The key of the first array level is the name of the section, which is
  903.      * assigned to an array of options to group under this section. The $params
  904.      * parameter still influences if an option as displayed at all.
  905.      * 
  906.      * @param ezcConsoleTable $table     The table object to fill.
  907.      * @param bool $long                 Set this to true for getting the
  908.      *                                    long help version.
  909.      * @param array(string) $params Set of option names to generate help
  910.      *                                    for, default is all.
  911.      * @param array(string=>array(string)) $paramGrouping 
  912.      * @return ezcConsoleTable           The filled table.
  913.      */
  914.     public function getHelpTableezcConsoleTable $table$long falsearray $params array()$paramGrouping null )
  915.     {
  916.         $help $this->getHelp$long$params$paramGrouping );
  917.         $i 0;
  918.         foreach $help as $row )
  919.         {
  920.             $table[$i][0]->content $row[0];
  921.             $table[$i++][1]->content $row[1];
  922.         }
  923.         return $table;
  924.     }
  925.  
  926.     /**
  927.      * Returns a standard help output for your program.
  928.      *
  929.      * This method generates a help text as it's commonly known from Unix
  930.      * command line programs. The output will contain the synopsis, your
  931.      * provided program description and the selected parameter help
  932.      * as also provided by {@link ezcConsoleInput::getHelp()}. The returned
  933.      * string can directly be printed to the console.
  934.      *
  935.      * The $paramGrouping option can be used to group options in the help
  936.      * output. The structure of this array parameter is as follows:
  937.      *
  938.      * <code>
  939.      *  array(
  940.      *      'First section' => array(
  941.      *          'input',
  942.      *          'output'
  943.      *          'overwrite',
  944.      *      ),
  945.      *      'Second section' => array(
  946.      *          'v',
  947.      *          'h',
  948.      *      ),
  949.      *  )
  950.      * </code>
  951.      *
  952.      * As can be seen, short option names are possible as well as long ones.
  953.      * The key of the first array level is the name of the section, which is
  954.      * assigned to an array of options to group under this section. The $params
  955.      * parameter still influences if an option as displayed at all.
  956.      * 
  957.      * @param string $programDesc        The description of your program.
  958.      * @param int $width                 The width to adjust the output text to.
  959.      * @param bool $long                 Set this to true for getting the long
  960.      *                                    help version.
  961.      * @param array(string) $params Set of option names to generate help
  962.      *                                    for, default is all.
  963.      * @param array(string=>array(string)) $paramGrouping 
  964.      * @return string The generated help text.
  965.      */
  966.     public function getHelpText$programDesc$width 80$long falsearray $params null$paramGrouping null )
  967.     {
  968.         $help $this->getHelp$long$params == null array($params )$paramGrouping );
  969.  
  970.         // Determine max length of first column text.
  971.         $maxLength 0;
  972.         foreach $help as $row )
  973.         {
  974.             $maxLength max$maxLengthiconv_strlen$row[0]'UTF-8' ) );
  975.         }
  976.  
  977.         // Width of left column
  978.         $leftColWidth $maxLength 2;
  979.         // Width of righ column
  980.         $rightColWidth $width $leftColWidth;
  981.  
  982.         $res 'Usage: ' $this->getSynopsis$params PHP_EOL;
  983.         $res .= $this->stringTool->wordwrap$programDesc$widthPHP_EOL );
  984.         $res .= PHP_EOL PHP_EOL;
  985.         foreach $help as $row )
  986.         {
  987.             $rowParts explode(
  988.                 "\n",
  989.                 $this->stringTool->wordwrap$row[1]$rightColWidth )
  990.             );
  991.  
  992.             $res .= $this->stringTool->strPad$row[0]$leftColWidth' ' );
  993.             $res .= $rowParts[0PHP_EOL;
  994.             // @TODO: Fix function call in loop header
  995.             for $i 1$i sizeof$rowParts )$i++ )
  996.             {
  997.                 $res .= str_repeat' '$leftColWidth $rowParts[$iPHP_EOL;
  998.             }
  999.         }
  1000.         return $res;
  1001.     }
  1002.  
  1003.     /**
  1004.      * Returns the synopsis string for the program.
  1005.      *
  1006.      * This gives you a synopsis definition for the options and arguments
  1007.      * defined with this instance of ezcConsoleInput. You can filter the
  1008.      * options named in the synopsis by submitting their short names in an
  1009.      * array as the parameter of this method. If the parameter $optionNames
  1010.      * is set, only those options are listed in the synopsis.
  1011.      * 
  1012.      * @param array(string) $optionNames 
  1013.      * @return string 
  1014.      */
  1015.     public function getSynopsisarray $optionNames null )
  1016.     {
  1017.         return $this->helpGenerator->generateSynopsis$optionNames );
  1018.     
  1019.  
  1020.     /**
  1021.      * Returns if a help option was set.
  1022.      * This method returns if an option was submitted, which was defined to be
  1023.      * a help option, using the isHelpOption flag.
  1024.      * 
  1025.      * @return bool If a help option was set.
  1026.      */
  1027.     public function helpOptionSet()
  1028.     {
  1029.         return $this->helpOptionSet;
  1030.     }
  1031.  
  1032.     /**
  1033.      * Property read access.
  1034.      *
  1035.      * @throws ezcBasePropertyNotFoundException
  1036.      *          If the the desired property is not found.
  1037.      * 
  1038.      * @param string $propertyName Name of the property.
  1039.      * @return mixed Value of the property or null.
  1040.      * @ignore
  1041.      */
  1042.     public function __get$propertyName )
  1043.     {
  1044.         if !isset$this->$propertyName ) )
  1045.         {
  1046.                 throw new ezcBasePropertyNotFoundException$propertyName );
  1047.         }
  1048.         return $this->properties[$propertyName];
  1049.     }
  1050.  
  1051.     /**
  1052.      * Property set access.
  1053.      * 
  1054.      * @param string $propertyName 
  1055.      * @param string $propertyValue 
  1056.      * @ignore
  1057.      * @return void 
  1058.      */
  1059.     public function __set$propertyName$propertyValue )
  1060.     {
  1061.         switch $propertyName )
  1062.         {
  1063.             case "argumentDefinition":
  1064.                 if ( ( $propertyValue instanceof ezcConsoleArguments === false && $propertyValue !== null )
  1065.                 {
  1066.                     throw new ezcBaseValueException$propertyName$propertyValue"ezcConsoleArguments" );
  1067.                 }
  1068.                 break;
  1069.             default:
  1070.                 throw new ezcBasePropertyNotFoundException$propertyName );
  1071.         }
  1072.         $this->properties[$propertyName$propertyValue;
  1073.     }
  1074.     
  1075.     /**
  1076.      * Property isset access.
  1077.      * 
  1078.      * @param string $propertyName Name of the property.
  1079.      * @return bool True if the property is set, otherwise false.
  1080.      * @ignore
  1081.      */
  1082.     public function __isset$propertyName )
  1083.     {
  1084.         return array_key_exists$propertyName$this->properties );
  1085.     }
  1086.  
  1087.     /**
  1088.      * Returns the synopsis string for a single option and its dependencies.
  1089.      *
  1090.      * This method returns a part of the program synopsis, specifically for a
  1091.      * certain parameter. The method recursively adds depending parameters up
  1092.      * to the 2nd depth level to the synopsis. The second parameter is used
  1093.      * to store the short names of all options that have already been used in
  1094.      * the synopsis (to avoid adding an option twice). The 3rd parameter
  1095.      * determines the actual deps in the option dependency recursion to
  1096.      * terminate that after 2 recursions.
  1097.      * 
  1098.      * @param ezcConsoleOption $option        The option to include.
  1099.      * @param array(string) $usedOptions Array of used option short names.
  1100.      * @param int $depth                      Current recursion depth.
  1101.      * @return string The synopsis for this parameter.
  1102.      *
  1103.      * @apichange This method is deprecates. Implement your own {@link }
  1104.      *             ezcConsoleInputHelpGenerator} instead, as soon as the
  1105.      *             interface is made public.
  1106.      */
  1107.     protected function createOptionSynopsisezcConsoleOption $option&$usedOptions$depth )
  1108.     {
  1109.         $synopsis '';
  1110.  
  1111.         // Break after a nesting level of 2
  1112.         if $depth++ > || in_array$option->short$usedOptions['short'&& in_array$option->long$usedOptions['long') ) ) return $synopsis;
  1113.         
  1114.         $usedOptions['short'][$option->short;
  1115.         $usedOptions['long'][]  $option->long;
  1116.         
  1117.         $synopsis .= $option->short !== "" "-{$option->short}"--{$option->long}";
  1118.  
  1119.         if isset$option->default ) )
  1120.         {
  1121.             $synopsis .= " " $option->type === ezcConsoleInput::TYPE_STRING '"' '' $option->default $option->type === ezcConsoleInput::TYPE_STRING '"' '' );
  1122.         }
  1123.         else if $option->type !== ezcConsoleInput::TYPE_NONE )
  1124.         {
  1125.             $synopsis .= " ";
  1126.             switch $option->type )
  1127.             {
  1128.                 case ezcConsoleInput::TYPE_STRING:
  1129.                     $synopsis .= "<string>";
  1130.                     break;
  1131.                 case ezcConsoleInput::TYPE_INT:
  1132.                     $synopsis .= "<int>";
  1133.                     break;
  1134.             }
  1135.         }
  1136.  
  1137.         foreach $option->getDependencies(as $rule )
  1138.         {
  1139.             $deeperSynopsis $this->createOptionSynopsis$rule->option$usedOptions$depth );
  1140.             $synopsis .= iconv_strlentrim$deeperSynopsis )'UTF-8' 
  1141.                 ? ' ' $deeperSynopsis
  1142.                 : ''
  1143.             );
  1144.         }
  1145.         
  1146.         if $option->arguments === false )
  1147.         {
  1148.             $allowsArgs false;
  1149.         }
  1150.         
  1151.         // Make the whole thing optional?
  1152.         if $option->mandatory === false )
  1153.         {
  1154.             $synopsis "[$synopsis]";
  1155.         }
  1156.  
  1157.         return $synopsis ' ';
  1158.     }
  1159.  
  1160.     /**
  1161.      * Process an option.
  1162.      *
  1163.      * This method does the processing of a single option.
  1164.      * 
  1165.      * @param array(string) $args The arguments array.
  1166.      * @param int $i                   The current position in the arguments array.
  1167.      * @return void 
  1168.      *
  1169.      * @throws ezcConsoleOptionTooManyValuesException
  1170.      *          If an option that expects only a single value was submitted
  1171.      *          with multiple values.
  1172.      * @throws ezcConsoleOptionTypeViolationException
  1173.      *          If an option was submitted with a value of the wrong type.
  1174.      * @throws ezcConsoleOptionMissingValueException
  1175.      *          If an option thats expects a value was submitted without.
  1176.      */
  1177.     private function processOptionarray $args&$i )
  1178.     {
  1179.         $option $this->getOptionpreg_replace'/^-+/'''$args[$i++) );
  1180.  
  1181.         // Is the actual option a help option?
  1182.         if $option->isHelpOption === true )
  1183.         {
  1184.             $this->helpOptionSet = true;
  1185.         }
  1186.         // No value expected
  1187.         if $option->type === ezcConsoleInput::TYPE_NONE )
  1188.         {
  1189.             // No value expected
  1190.             if isset$args[$i&& iconv_substr$args[$i]01'UTF-8' !== '-' && sizeof$args $i ) )
  1191.             {
  1192.                 // But one found
  1193.                 throw new ezcConsoleOptionTypeViolationException$option$args[$i);
  1194.             }
  1195.             // Multiple occurance possible
  1196.             if $option->multiple === true )
  1197.             {
  1198.                 $option->value[true;
  1199.             }
  1200.             else
  1201.             {
  1202.                 $option->value true;
  1203.             }
  1204.             // Everything fine, nothing to do
  1205.             return $i;
  1206.         }
  1207.         // Value expected, check for it
  1208.         if isset$args[$i&& iconv_substr$args[$i]01'UTF-8' !== '-' )
  1209.         {
  1210.             // Type check
  1211.             if $this->isCorrectType$option->type$args[$i=== false )
  1212.             {
  1213.                 throw new ezcConsoleOptionTypeViolationException$option$args[$i);
  1214.             }
  1215.             // Multiple values possible
  1216.             if $option->multiple === true )
  1217.             {
  1218.                 $option->value[$args[$i];
  1219.             }
  1220.             // Only single value expected, check for multiple
  1221.             elseif isset$option->value && $option->value !== false )
  1222.             {
  1223.                 throw new ezcConsoleOptionTooManyValuesException$option );
  1224.             }
  1225.             else
  1226.             {
  1227.                 $option->value $args[$i];
  1228.             }
  1229.             $i++;
  1230.         }
  1231.         // Value found? If not, use default, if available
  1232.         if !isset$option->value || $option->value === false || is_array$option->value && count$option->value === 0) ) 
  1233.         {
  1234.             throw new ezcConsoleOptionMissingValueException$option );
  1235.         }
  1236.     }
  1237.  
  1238.     /**
  1239.      * Process arguments given to the program.
  1240.      * 
  1241.      * @param array(string) $args The arguments array.
  1242.      * @param int $i                   Current index in arguments array.
  1243.      * @return void 
  1244.      */
  1245.     private function processArgumentsarray $args&$i )
  1246.     {
  1247.         $numArgs count$args );
  1248.         if $this->argumentDefinition === null || $this->argumentsAllowed(=== false )
  1249.         {
  1250.             // Old argument handling, also used of a set option sets disallowing arguments
  1251.             while $i $numArgs )
  1252.             {
  1253.                 $this->arguments[$args[$i++];
  1254.             }
  1255.         }
  1256.         else
  1257.         {
  1258.             $mandatory true;
  1259.             foreach $this->argumentDefinition as $arg )
  1260.             {
  1261.                 // Check if all followinga arguments are optional
  1262.                 if $arg->mandatory === false )
  1263.                 {
  1264.                     $mandatory false;
  1265.                 }
  1266.  
  1267.                 // Check if the current argument is present and mandatory
  1268.                 if $mandatory === true )
  1269.                 {
  1270.                     if !isset$args[$i) )
  1271.                     {
  1272.                         throw new ezcConsoleArgumentMandatoryViolationException$arg );
  1273.                     }
  1274.                 }
  1275.                 else
  1276.                 {
  1277.                     // Arguments are optional, if no more left: return.
  1278.                     if !isset$args[$i) )
  1279.                     {
  1280.                         // Optional and no more arguments left, assign default
  1281.                         $arg->value $arg->default;
  1282.                         continue;
  1283.                     }
  1284.                 }
  1285.  
  1286.                 if $arg->multiple === true )
  1287.                 {
  1288.                     $arg->value array();
  1289.                     for $i $i$i $numArgs++$i )
  1290.                     {
  1291.                         if $this->isCorrectType$arg->type$args[$i=== false )
  1292.                         {
  1293.                             throw new ezcConsoleArgumentTypeViolationException$arg$args[$i);
  1294.                         }
  1295.                         $arg->value array_merge$arg->valuearray$args[$i) );
  1296.                         // Keep old handling, too
  1297.                         $this->arguments[$args[$i];
  1298.                     }
  1299.                     return;
  1300.                 }
  1301.                 else
  1302.                 {
  1303.                     if $this->isCorrectType$arg->type$args[$i=== false )
  1304.                     {
  1305.                         throw new ezcConsoleArgumentTypeViolationException$arg$args[$i);
  1306.                     }
  1307.                     $arg->value $args[$i];
  1308.                     // Keep old handling, too
  1309.                     $this->arguments[$args[$i];
  1310.                 }
  1311.                 ++$i;
  1312.             }
  1313.  
  1314.             if $i $numArgs )
  1315.             {
  1316.                 throw new ezcConsoleTooManyArgumentsException$args$i );
  1317.             }
  1318.         }
  1319.     }
  1320.  
  1321.     /**
  1322.      * Returns if arguments are allowed with the current option submition.
  1323.      * 
  1324.      * @return bool If arguments allowed.
  1325.      */
  1326.     protected function argumentsAllowed()
  1327.     {
  1328.         foreach $this->options as $id => $option )
  1329.         {
  1330.             if $option->value !== false && $option->arguments === false )
  1331.             {
  1332.                 return false;
  1333.             }
  1334.         }
  1335.         return true;
  1336.     }
  1337.  
  1338.     /**
  1339.      * Check the rules that may be associated with an option.
  1340.      *
  1341.      * Options are allowed to have rules associated for dependencies to other
  1342.      * options and exclusion of other options or arguments. This method
  1343.      * processes the checks.
  1344.      *
  1345.      * @throws ezcConsoleException
  1346.      *          in case validation fails.
  1347.      */
  1348.     private function checkRules()
  1349.     {
  1350.         // If a help option is set, skip rule checking
  1351.         if $this->helpOptionSet === true )
  1352.         {
  1353.             return;
  1354.         }
  1355.         $this->validator->validateOptions(
  1356.             $this->options,
  1357.             $this->arguments !== array() )
  1358.         );
  1359.     }
  1360.  
  1361.     /**
  1362.      * Checks if a value is of a given type. Converts the value to the
  1363.      * correct PHP type on success.
  1364.      *  
  1365.      * @param int $type   The type to check for. One of self::TYPE_*.
  1366.      * @param string $val The value to check. Will possibly altered!
  1367.      * @return bool True on succesful check, otherwise false.
  1368.      */
  1369.     private function isCorrectType$type&$val )
  1370.     {
  1371.         $res false;
  1372.         switch $type )
  1373.         {
  1374.             case ezcConsoleInput::TYPE_STRING:
  1375.                 $res true;
  1376.                 $val preg_replace'/^(["\'])(.*)\1$/''\2'$val );
  1377.                 break;
  1378.             case ezcConsoleInput::TYPE_INT:
  1379.                 $res preg_match'/^[0-9]+$/'$val true false;
  1380.                 if $res )
  1381.                 {
  1382.                     $val = ( int ) $val;
  1383.                 }
  1384.                 break;
  1385.         }
  1386.         return $res;
  1387.     }
  1388.  
  1389.     /**
  1390.      * Split parameter and value for long option names.
  1391.      * 
  1392.      * This method checks for long options, if the value is passed using =. If
  1393.      * this is the case parameter and value get split and replaced in the
  1394.      * arguments array.
  1395.      * 
  1396.      * @param array(string) $args The arguments array
  1397.      * @param int $i                   Current arguments array position
  1398.      * @return void 
  1399.      */
  1400.     private function preprocessLongOptionarray &$args$i )
  1401.     {
  1402.         // Value given?
  1403.         if preg_match'/^--\w+\=[^ ]/i'$args[$i) )
  1404.         {
  1405.             // Split param and value and replace current param
  1406.             $parts explode'='$args[$i]);
  1407.             array_splice$args$i1$parts );
  1408.         }
  1409.     }
  1410. }
  1411. ?>
Documentation generated by phpDocumentor 1.4.3