Console_Getargs
[ class tree: Console_Getargs ] [ index: Console_Getargs ] [ all elements ]

Source for file Getargs.php

Documentation is available at Getargs.php

  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4: */
  3. // +----------------------------------------------------------------------+
  4. // | PHP Version 4                                                        |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 2004 The PHP Group                                     |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 3.0 of the PHP license,       |
  9. // | that is bundled with this package in the file LICENSE, and is        |
  10. // | available through the world-wide-web at the following url:           |
  11. // | http://www.php.net/license/3_0.txt.                                  |
  12. // | If you did not receive a copy of the PHP license and are unable to   |
  13. // | obtain it through the world-wide-web, please send a note to          |
  14. // | license@php.net so we can mail you a copy immediately.               |
  15. // +----------------------------------------------------------------------+
  16. // | Author: Bertrand Mansion <bmansion@mamasam.com>                      |
  17. // +----------------------------------------------------------------------+
  18. //
  19. // $Id: Getargs.php,v 1.17 2005/04/08 07:11:37 wenz Exp $
  20.  
  21. require_once 'PEAR.php';
  22.  
  23. /**#@+
  24.  * Error Constants
  25.  */
  26. /**
  27.  * Wrong configuration
  28.  *
  29.  * This error will be TRIGGERed when a configuration error is found,
  30.  * it will also issue a WARNING.
  31.  */
  32. define('CONSOLE_GETARGS_ERROR_CONFIG'-1);
  33.  
  34. /**
  35.  * User made an error
  36.  *
  37.  * This error will be RETURNed when a bad parameter
  38.  * is found in the command line, for example an unknown parameter
  39.  * or a parameter with an invalid number of options.
  40.  */
  41. define('CONSOLE_GETARGS_ERROR_USER'-2);
  42.  
  43. /**
  44.  * Help text wanted
  45.  *
  46.  * This error will be RETURNed when the user asked to
  47.  * see the help by using <kbd>-h</kbd> or <kbd>--help</kbd> in the command line, you can then print
  48.  * the help ascii art text by using the {@link Console_Getargs::getHelp()} method
  49.  */
  50. define('CONSOLE_GETARGS_HELP'-3);
  51.  
  52. /**
  53.  * Option name for application "parameters"
  54.  *
  55.  * Parameters are the options an application needs to function.
  56.  * The two files passed to the diff command would be considered
  57.  * the parameters. These are different from other options in that
  58.  * they do not need an option name passed on the command line.
  59.  */
  60. define('CONSOLE_GETARGS_PARAMS''parameters');
  61. /**#@-*/
  62.  
  63. /**
  64.  * Command-line arguments parsing class
  65.  * 
  66.  * This implementation was freely inspired by a python module called
  67.  * getargs by Vinod Vijayarajan and a perl CPAN module called
  68.  * Getopt::Simple by Ron Savage
  69.  *
  70.  * This class implements a Command Line Parser that your cli applications
  71.  * can use to parse command line arguments found in $_SERVER['argv'] or a
  72.  * user defined array.
  73.  * 
  74.  * It gives more flexibility and error checking than Console_Getopt. It also
  75.  * performs some arguments validation and is capable to return a formatted
  76.  * help text to the user, based on the configuration it is given.
  77.  * 
  78.  * The class provides the following capabilities:
  79.  * - Each command line option can take an arbitrary number of arguments.
  80.  * - Makes the distinction between switches (options without arguments)
  81.  *   and options that require arguments.
  82.  * - Recognizes 'single-argument-options' and 'default-if-set' options.
  83.  * - Switches and options with arguments can be interleaved in the command
  84.  *   line.
  85.  * - You can specify the maximum and minimum number of arguments an option
  86.  *   can take. Use -1 if you don't want to specify an upper bound.
  87.  * - Specify the default arguments to an option
  88.  * - Short options can be more than one letter in length.
  89.  * - A given option may be invoked by multiple names (aliases).
  90.  * - Understands by default the --help, -h options
  91.  * - Can return a formatted help text
  92.  * - Arguments may be specified using the '=' syntax also.
  93.  * - Short option names may be concatenated (-dvw 100 == -d -v -w 100)
  94.  * - Can define a default option that will take any arguments added without
  95.  *   an option name
  96.  * - Can pass in a user defined array of arguments instead of using
  97.  *   $_SERVER['argv']
  98.  * 
  99.  * @todo      Implement the parsing of comma delimited arguments
  100.  * @todo      Implement method for turning assocative arrays into command
  101.  *             line arguments (ex. array('d' => true, 'v' => 2) -->
  102.  *                                 array('-d', '-v', 2))
  103.  *
  104.  * @author    Bertrand Mansion <bmansion@mamasam.com>
  105.  * @copyright 2004
  106.  * @license   http://www.php.net/license/3_0.txt PHP License 3.0
  107.  * @version   @VER@
  108.  * @package   Console_Getargs
  109.  */
  110. {
  111.     /**
  112.      * Factory creates a new {@link Console_Getargs_Options} object
  113.      *
  114.      * This method will return a new {@link Console_Getargs_Options}
  115.      * built using the given configuration options. If the configuration
  116.      * or the command line options contain errors, the returned object will
  117.      * in fact be a PEAR_Error explaining the cause of the error.
  118.      *
  119.      * Factory expects an array as parameter.
  120.      * The format for this array is:
  121.      * <pre>
  122.      * array(
  123.      *  longname => array('short'   => Short option name,
  124.      *                    'max'     => Maximum arguments for option,
  125.      *                    'min'     => Minimum arguments for option,
  126.      *                    'default' => Default option argument,
  127.      *                    'desc'    => Option description)
  128.      * )
  129.      * </pre>
  130.      * 
  131.      * If an option can be invoked by more than one name, they have to be defined
  132.      * by using | as a separator. For example: name1|name2
  133.      * This works both in long and short names.
  134.      *
  135.      * max/min are the most/least number of arguments an option accepts.
  136.      *
  137.      * The 'defaults' field is optional and is used to specify default
  138.      * arguments to an option. These will be assigned to the option if
  139.      * it is *not* used in the command line.
  140.      * Default arguments can be:
  141.      * - a single value for options that require a single argument,
  142.      * - an array of values for options with more than one possible arguments.
  143.      * Default argument(s) are mandatory for 'default-if-set' options.
  144.      *
  145.      * If max is 0 (option is just a switch), min is ignored.
  146.      * If max is -1, then the option can have an unlimited number of arguments
  147.      * greater or equal to min.
  148.      * 
  149.      * If max == min == 1, the option is treated as a single argument option.
  150.      * 
  151.      * If max >= 1 and min == 0, the option is treated as a
  152.      * 'default-if-set' option. This implies that it will get the default argument
  153.      * only if the option is used in the command line without any value.
  154.      * (Note: defaults *must* be specified for 'default-if-set' options)
  155.      *
  156.      * If the option is not in the command line, the defaults are
  157.      * *not* applied. If an argument for the option is specified on the command
  158.      * line, then the given argument is assigned to the option.
  159.      * Thus:
  160.      * - a --debug in the command line would cause debug = 'default argument'
  161.      * - a --debug 2 in the command line would result in debug = 2
  162.      *  if not used in the command line, debug will not be defined.
  163.      * 
  164.      * Example 1.
  165.      * <code>
  166.      * require_once 'Console_Getargs.php';
  167.      *
  168.      * $args =& Console_Getargs::factory($config);
  169.      * 
  170.      * if (PEAR::isError($args)) {
  171.      *  if ($args->getCode() === CONSOLE_GETARGS_ERROR_USER) {
  172.      *    echo Console_Getargs::getHelp($config, null, $args->getMessage())."\n";
  173.      *  } else if ($args->getCode() === CONSOLE_GETARGS_HELP) {
  174.      *    echo Console_Getargs::getHelp($config)."\n";
  175.      *  }
  176.      *  exit;
  177.      * }
  178.      * 
  179.      * echo 'Verbose: '.$args->getValue('verbose')."\n";
  180.      * if ($args->isDefined('bs')) {
  181.      *  echo 'Block-size: '.(is_array($args->getValue('bs')) ? implode(', ', $args->getValue('bs'))."\n" : $args->getValue('bs')."\n");
  182.      * } else {
  183.      *  echo "Block-size: undefined\n";
  184.      * }
  185.      * echo 'Files: '.($args->isDefined('file') ? implode(', ', $args->getValue('file'))."\n" : "undefined\n");
  186.      * if ($args->isDefined('n')) {
  187.      *  echo 'Nodes: '.(is_array($args->getValue('n')) ? implode(', ', $args->getValue('n'))."\n" : $args->getValue('n')."\n");
  188.      * } else {
  189.      *  echo "Nodes: undefined\n";
  190.      * }
  191.      * echo 'Log: '.$args->getValue('log')."\n";
  192.      * echo 'Debug: '.($args->isDefined('d') ? "YES\n" : "NO\n");
  193.      * 
  194.      * </code>
  195.      *
  196.      * If you don't want to require any option name for a set of arguments,
  197.      * or if you would like any "leftover" arguments assigned by default,
  198.      * you can create an option named CONSOLE_GETARGS_PARAMS that will
  199.      * grab any arguments that cannot be assigned to another option. The
  200.      * rules for CONSOLE_GETARGS_PARAMS are still the same. If you specify
  201.      * that two values must be passed then two values must be passed. See
  202.      * the example script for a complete example.
  203.      * 
  204.      * @param  array  $config     associative array with keys being the
  205.      *                             options long name
  206.      * @param  array  $arguments  numeric array of command line arguments
  207.      * @access public
  208.      * @return object|PEAR_Error a newly created Console_Getargs_Options
  209.      *                             object or a PEAR_Error object on error
  210.      */
  211.     function &factory($config = array()$arguments = NULL)
  212.     {
  213.         // Create the options object.
  214.         $obj =new Console_Getargs_Options();
  215.         
  216.         // Try to set up the arguments.
  217.         $err $obj->init($config$arguments);
  218.         if ($err !== true{
  219.             return $err;
  220.         }
  221.         
  222.         // Try to set up the options.
  223.         $err $obj->buildMaps();
  224.         if ($err !== true{
  225.             return $err;
  226.         }
  227.         
  228.         // Get the options and arguments from the command line.
  229.         $err $obj->parseArgs();
  230.         if ($err !== true{
  231.             return $err;
  232.         }
  233.         
  234.         // Set arguments for options that have defaults.
  235.         $err $obj->setDefaults();
  236.         if ($err !== true{
  237.             return $err;
  238.         }
  239.         
  240.         // All is good.
  241.         return $obj;
  242.     }
  243.     
  244.     /**
  245.      * Returns an ascii art version of the help
  246.      *
  247.      * This method uses the given configuration and parameters
  248.      * to create and format an help text for the options you defined
  249.      * in your config parameter. You can supply a header and a footer
  250.      * as well as the maximum length of a line. If you supplied
  251.      * descriptions for your options, they will be used as well.
  252.      *
  253.      * By default, it returns something like this:
  254.      * <pre>
  255.      * Usage: myscript.php [-dv --formats] <-fw --filters>
  256.      * 
  257.      * -f --files values(2)          Set the source and destination image files.
  258.      * -w --width=&lt;value&gt;      Set the new width of the image.
  259.      * -d --debug                    Switch to debug mode.
  260.      * --formats values(1-3)         Set the image destination format. (jpegbig,
  261.      *                               jpegsmall)
  262.      * -fi --filters values(1-...)   Set the filters to be applied to the image upon
  263.      *                               conversion. The filters will be used in the order
  264.      *                               they are set.
  265.      * -v --verbose (optional)value  Set the verbose level. (3)
  266.      * </pre>
  267.      *
  268.      * @access public
  269.      * @param  array  your args configuration
  270.      * @param  string the header for the help. If it is left null,
  271.      *                 a default header will be used, starting by Usage:
  272.      * @param  string the footer for the help. This could be used
  273.      *                 to supply a description of the error the user made
  274.      * @param  int    help lines max length
  275.      * @return string the formatted help text
  276.      */
  277.     function getHelp($config$helpHeader = null$helpFooter ''$maxlength = 78)
  278.     {
  279.         // Start with an empty help message and build it piece by piece
  280.         $help '';
  281.         
  282.         // If no user defined header, build the default header.
  283.         if (!isset($helpHeader)) {
  284.             // Get the optional, required and "paramter" names for this config.
  285.             list($optional$required$paramsConsole_Getargs::getOptionalRequired($config);
  286.             // Start with the file name.
  287.             $helpHeader 'Usage: 'basename($_SERVER['SCRIPT_NAME']' ';
  288.             // Add the optional arguments and required arguments.
  289.             $helpHeader.= $optional ' ' $required ' ';
  290.             // Add any parameters that are needed.
  291.             $helpHeader.= $params "\n\n";
  292.         }
  293.         
  294.         // Build the list of options and definitions.
  295.         $i = 0;
  296.         foreach ($config as $long => $def{
  297.             
  298.             // Break the names up if there is more than one for an option.
  299.             $shortArr = array();
  300.             if (isset($def['short'])) {
  301.                 $shortArr explode('|'$def['short']);
  302.             }
  303.             $longArr explode('|'$long);
  304.             
  305.             // Column one is the option name displayed as "-short, --long [additional info]"
  306.             // Add the short option name.
  307.             $col1[$i!empty($shortArr'-'.$shortArr[0].' ' '';
  308.             // Add the long option name.
  309.             $col1[$i.= '--'.$longArr[0];
  310.             
  311.             // Get the min and max to show needed/optional values.
  312.             $max $def['max'];
  313.             $min = isset($def['min']$def['min'$max;
  314.             
  315.             if ($max === 1 && $min === 1{
  316.                 // One value required.
  317.                 $col1[$i.= '=<value>';
  318.             else if ($max > 1{
  319.                 if ($min === $max{
  320.                     // More than one value needed.
  321.                     $col1[$i.= ' values('.$max.')';
  322.                 else if ($min === 0{
  323.                     // Argument takes optional value(s).
  324.                     $col1[$i.= ' values(optional)';
  325.                 else {
  326.                     // Argument takes a range of values.
  327.                     $col1[$i.= ' values('.$min.'-'.$max.')';
  328.                 }
  329.             else if ($max === 1 && $min === 0{
  330.                 // Argument can take at most one value.
  331.                 $col1[$i.= ' (optional)value';
  332.             else if ($max === -1{
  333.                 // Argument can take unlimited values.
  334.                 if ($min > 0{
  335.                     $col1[$i.= ' values('.$min.'-...)';
  336.                 else {
  337.                     $col1[$i.= ' (optional)values';
  338.                 }
  339.             }
  340.             
  341.             // Column two is the description if available.
  342.             if (isset($def['desc'])) {
  343.                 $col2[$i$def['desc'];
  344.             else {
  345.                 $col2[$i'';
  346.             }
  347.             // Add the default value(s) if there are any/
  348.             if (isset($def['default'])) {
  349.                 if (is_array($def['default'])) {
  350.                     $col2[$i.= ' ('.implode(', '$def['default']).')';
  351.                 else {
  352.                     $col2[$i.= ' ('.$def['default'].')';
  353.                 }
  354.             }
  355.             $i++;
  356.         }
  357.         
  358.         // Figure out the maximum length for column one.
  359.         $arglen = 0;
  360.         foreach ($col1 as $txt{
  361.             $length strlen($txt);
  362.             if ($length $arglen{
  363.                 $arglen $length;
  364.             }
  365.         }
  366.         
  367.         // The maximum length for each description line.
  368.         $desclen $maxlength $arglen;
  369.         $padding str_repeat(' '$arglen);
  370.         foreach ($col1 as $k => $txt{
  371.             // Wrap the descriptions.
  372.             if (strlen($col2[$k]$desclen{
  373.                 $desc wordwrap($col2[$k]$desclen"\n  ".$padding);
  374.             else {
  375.                 $desc $col2[$k];
  376.             }
  377.             // Push everything together.
  378.             $help .= str_pad($txt$arglen).'  '.$desc."\n";
  379.         }
  380.         
  381.         // Put it all together.
  382.         return $helpHeader.$help.$helpFooter;
  383.     }
  384.     
  385.     /**
  386.      * Parse the config array to determine which flags are
  387.      * optional and which are required.
  388.      *
  389.      * To make the help header more descriptive, the options
  390.      * are shown seperated into optional and required flags.
  391.      * When possible the short flag is used for readability.
  392.      * Optional items (including "parameters") are surrounded
  393.      * in square braces ([-vd]). Required flags are surrounded
  394.      * in angle brackets (<-wf>).
  395.      *
  396.      * This method may be called statically.
  397.      *
  398.      * @access  public
  399.      * @param   &$config The config array.
  400.      * @return  array 
  401.      * @author  Scott Mattocks
  402.      * @package Console_Getargs
  403.      */
  404.     function getOptionalRequired(&$config)
  405.     {
  406.         // Parse the config array and look for optional/required
  407.         // tags.
  408.         $optional         '';
  409.         $optionalHasShort = false;
  410.         $required         '';
  411.         $requiredHasShort = false;
  412.         
  413.         ksort($config);
  414.         foreach ($config as $long => $def{
  415.             
  416.             // We only really care about the first option name.
  417.             $long reset(explode('|'$long));
  418.             
  419.             // Treat the "parameters" specially.
  420.             if ($long == CONSOLE_GETARGS_PARAMS{
  421.                 continue;
  422.             }
  423.             // We only really care about the first option name.
  424.             $def['short'reset(explode('|'$def['short']));
  425.             
  426.             if (!isset($def['min']|| $def['min'== 0 || isset($def['default'])) {
  427.                 // This argument is optional.
  428.                 if (isset($def['short']&& strlen($def['short']== 1{
  429.                     $optional         $def['short'$optional;
  430.                     $optionalHasShort = true;
  431.                 else {
  432.                     $optional.= ' --' $long;
  433.                 }
  434.             else {
  435.                 // This argument is required.
  436.                 if (isset($def['short']&& strlen($def['short']== 1{
  437.                     $required         $def['short'$required;
  438.                     $requiredHasShort = true;
  439.                 else {
  440.                     $required.= ' --' $long;
  441.                 }
  442.             }
  443.         }
  444.         
  445.         // Check for "parameters" option.
  446.         $params '';
  447.         if (isset($config[CONSOLE_GETARGS_PARAMS])) {
  448.             for ($i = 1; $i <= max($config[CONSOLE_GETARGS_PARAMS]['max']$config[CONSOLE_GETARGS_PARAMS]['min']); ++$i{
  449.                 if ($config[CONSOLE_GETARGS_PARAMS]['max'== -1 ||
  450.                     ($i $config[CONSOLE_GETARGS_PARAMS]['min'&&
  451.                      $i <= $config[CONSOLE_GETARGS_PARAMS]['max']||
  452.                     isset($config[CONSOLE_GETARGS_PARAMS]['default'])) {
  453.                     // Parameter is optional.
  454.                     $params.= '[param' $i .'] ';
  455.                 else {
  456.                     // Parameter is required.
  457.                     $params.= 'param' $i ' ';
  458.                 }
  459.             }
  460.         }
  461.         // Add a leading - if needed.
  462.         if ($optionalHasShort{
  463.             $optional '-' $optional;
  464.         }
  465.         
  466.         if ($requiredHasShort{
  467.             $required '-' $required;
  468.         }
  469.         
  470.         // Add the extra characters if needed.
  471.         if (!empty($optional)) {
  472.             $optional '[' $optional ']';
  473.         }
  474.         if (!empty($required)) {
  475.             $required '<' $required '>';
  476.         }
  477.         
  478.         return array($optional$required$params);
  479.     }
  480. // end class Console_Getargs
  481.  
  482. /**
  483.  * This class implements a wrapper to the command line options and arguments.
  484.  *
  485.  * @author Bertrand Mansion <bmansion@mamasam.com>
  486.  * @package  Console_Getargs
  487.  */
  488. {
  489.     
  490.     /**
  491.      * Lookup to match short options name with long ones
  492.      * @var array 
  493.      * @access private
  494.      */
  495.     var $_shortLong = array();
  496.     
  497.     /**
  498.      * Lookup to match alias options name with long ones
  499.      * @var array 
  500.      * @access private
  501.      */
  502.     var $_aliasLong = array();
  503.     
  504.     /**
  505.      * Arguments set for the options
  506.      * @var array 
  507.      * @access private
  508.      */
  509.     var $_longLong = array();
  510.     
  511.     /**
  512.      * Configuration set at initialization time
  513.      * @var array 
  514.      * @access private
  515.      */
  516.     var $_config = array();
  517.     
  518.     /**
  519.      * A read/write copy of argv
  520.      * @var array 
  521.      * @access private
  522.      */
  523.     var $args = array();
  524.     
  525.     /**
  526.      * Initializes the Console_Getargs_Options object
  527.      * @param array configuration options
  528.      * @access private
  529.      * @throws CONSOLE_GETARGS_ERROR_CONFIG
  530.      * @return true|PEAR_Error
  531.      */
  532.     function init($config$arguments = NULL)
  533.     {
  534.         if (is_array($arguments)) {
  535.             // Use the user defined argument list.
  536.             $this->args $arguments;
  537.         else {
  538.             // Command line arguments must be available.
  539.             if (!isset($_SERVER['argv']|| !is_array($_SERVER['argv'])) {
  540.                 return PEAR::raiseError("Could not read argv"CONSOLE_GETARGS_ERROR_CONFIG,
  541.                                         PEAR_ERROR_TRIGGERE_USER_WARNING'Console_Getargs_Options::init()');
  542.             }
  543.             $this->args $_SERVER['argv'];
  544.         }
  545.         
  546.         // Drop the first argument if it doesn't begin with a '-'.
  547.         if (isset($this->args[0]{0}&& $this->args[0]{0!= '-'{
  548.             array_shift($this->args);
  549.         }
  550.         $this->_config $config;
  551.         return true;
  552.     }
  553.     
  554.     /**
  555.      * Makes the lookup arrays for alias and short name mapping with long names
  556.      * @access private
  557.      * @throws CONSOLE_GETARGS_ERROR_CONFIG
  558.      * @return true|PEAR_Error
  559.      */
  560.     function buildMaps()
  561.     {
  562.         foreach($this->_config as $long => $def{
  563.             
  564.             $longArr explode('|'$long);
  565.             $longname $longArr[0];
  566.             
  567.             if (count($longArr> 1{
  568.                 // The fisrt item in the list is "the option".
  569.                 // The rest are aliases.
  570.                 array_shift($longArr);
  571.                 foreach($longArr as $alias{
  572.                     // Watch out for duplicate aliases.
  573.                     if (isset($this->_aliasLong[$alias])) {
  574.                         return PEAR::raiseError('Duplicate alias for long option '.$aliasCONSOLE_GETARGS_ERROR_CONFIG,
  575.                                                 PEAR_ERROR_TRIGGERE_USER_WARNING'Console_Getargs_Options::buildMaps()');
  576.                         
  577.                     }
  578.                     $this->_aliasLong[$alias$longname;
  579.                 }
  580.                 // Add the real option name and defintion.
  581.                 $this->_config[$longname$def;
  582.                 // Get rid of the old version (name|alias1|...)
  583.                 unset($this->_config[$long]);
  584.             }
  585.             
  586.             // Add the (optional) short option names.
  587.             if (!empty($def['short'])) {
  588.                 // Short names
  589.                 $shortArr explode('|'$def['short']);
  590.                 $short $shortArr[0];
  591.                 if (count($shortArr> 1{
  592.                     // The first item is "the option".
  593.                     // The rest are aliases.
  594.                     array_shift($shortArr);
  595.                     foreach ($shortArr as $alias{
  596.                         // Watch out for duplicate aliases.
  597.                         if (isset($this->_shortLong[$alias])) {
  598.                             return PEAR::raiseError('Duplicate alias for short option '.$aliasCONSOLE_GETARGS_ERROR_CONFIG,
  599.                                                     PEAR_ERROR_TRIGGERE_USER_WARNING'Console_Getargs_Options::buildMaps()');
  600.                         }
  601.                         $this->_shortLong[$alias$longname;
  602.                     }
  603.                 }
  604.                 // Add the real short option name.
  605.                 $this->_shortLong[$short$longname;
  606.             }
  607.         }
  608.         return true;
  609.     }
  610.     
  611.     /**
  612.      * Parses the given options/arguments one by one
  613.      * @access private
  614.      * @throws CONSOLE_GETARGS_HELP
  615.      * @throws CONSOLE_GETARGS_ERROR_USER
  616.      * @return true|PEAR_Error
  617.      */
  618.     function parseArgs()
  619.     {
  620.         // Go through the options and parse the arguments for each.
  621.         for ($i = 0$count count($this->args)$i $count$i++{
  622.             $arg $this->args[$i];
  623.             if ($arg === '--help' || $arg === '-h'{
  624.                 // Asking for help breaks the loop.
  625.                 return PEAR::raiseError(nullCONSOLE_GETARGS_HELPPEAR_ERROR_RETURN);
  626.  
  627.             }
  628.             if ($arg === '--'{
  629.                 // '--' alone signals the start of "parameters"
  630.                 $err $this->parseArg(CONSOLE_GETARGS_PARAMStrue++$i);
  631.             elseif (strlen($arg> 1 && $arg{0== '-' && $arg{1== '-'{
  632.                 // Long name used (--option)
  633.                 $err $this->parseArg(substr($arg2)true$i);
  634.             else if (strlen($arg> 1 && $arg{0== '-'{
  635.                 // Short name used (-o)
  636.                 $err $this->parseArg(substr($arg1)false$i);
  637.                 if ($err === -1{
  638.                     break;
  639.                 }
  640.             elseif (isset($this->_config[CONSOLE_GETARGS_PARAMS])) {
  641.                 // No flags at all. Try the parameters option.
  642.                 $tempI &$i - 1;
  643.                 $err $this->parseArg(CONSOLE_GETARGS_PARAMStrue$tempI);
  644.             else {
  645.                 $err = PEAR::raiseError('Unknown argument '.$arg,
  646.                                         CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  647.                                         null'Console_Getargs_Options::parseArgs()');
  648.             }
  649.             if ($err !== true{
  650.                 return $err;
  651.             }
  652.         }
  653.         // Check to see if we need to reload the arguments
  654.         // due to concatenated short names.
  655.         if (isset($err&& $err === -1{
  656.             return $this->parseArgs();
  657.         }
  658.         
  659.         return true;
  660.     }
  661.     
  662.     /**
  663.      * Parses one option/argument
  664.      * @access private
  665.      * @throws CONSOLE_GETARGS_ERROR_USER
  666.      * @return true|PEAR_Error
  667.      */
  668.     function parseArg($arg$isLong&$pos)
  669.     {
  670.         // If the whole short option isn't in the shortLong array
  671.         // then break it into a bunch of switches.
  672.         if (!$isLong && !isset($this->_shortLong[$arg]&& strlen($arg> 1{
  673.             $newArgs = array();
  674.             for ($i = 0; $i strlen($arg)$i++{
  675.                 if (array_key_exists($arg{$i}$this->_shortLong)) {
  676.                     $newArgs['-' $arg{$i};
  677.                 else {
  678.                     $newArgs[$arg{$i};
  679.                 }
  680.             }
  681.             // Add the new args to the array.
  682.             array_splice($this->args$pos1$newArgs);
  683.             
  684.             // Reset the option values.
  685.             $this->_longLong = array();
  686.             
  687.             // Then reparse the arguments.
  688.             return -1;
  689.         }
  690.         
  691.         $opt '';
  692.         for ($i = 0; $i strlen($arg)$i++{
  693.             // Build the option name one char at a time looking for a match.
  694.             $opt .= $arg{$i};
  695.             if ($isLong === false && isset($this->_shortLong[$opt])) {
  696.                 // Found a match in the short option names.
  697.                 $cmp $opt;
  698.                 $long $this->_shortLong[$opt];
  699.             elseif ($isLong === true && isset($this->_config[$opt])) {
  700.                 // Found a match in the long option names.
  701.                 $long $cmp $opt;
  702.             elseif ($isLong === true && isset($this->_aliasLong[$opt])) {
  703.                 // Found a match in the long option names.
  704.                 $long $this->_aliasLong[$opt];
  705.                 $cmp $opt;
  706.             }
  707.             if ($arg{$i=== '='{
  708.                 // End of the option name when '=' is found.
  709.                 break;
  710.             }
  711.         }
  712.  
  713.         // If no option name is found, assume -- was passed.
  714.         if ($opt == ''{
  715.             $long CONSOLE_GETARGS_PARAMS;
  716.         }
  717.         
  718.         if (isset($long)) {
  719.             // A match was found.
  720.             if (strlen($argstrlen($cmp)) {
  721.                 // Seperate the argument from the option.
  722.                 // Ex: php test.php -f=image.png
  723.                 //     $cmp = 'f'
  724.                 //     $arg = 'f=image.png'
  725.                 $arg substr($argstrlen($cmp));
  726.                 // Now $arg = '=image.png'
  727.                 if ($arg{0=== '='{
  728.                     $arg substr($arg1);
  729.                     // Now $arg = 'image.png'
  730.                 }
  731.             else {
  732.                 // No argument passed for option.
  733.                 $arg '';
  734.             }
  735.             // Set the options value.
  736.             return $this->setValue($long$arg$pos);
  737.         }
  738.         return PEAR::raiseError('Unknown argument '.$opt,
  739.                                 CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  740.                                 null'Console_Getargs_Options::parseArg()');
  741.     }
  742.     
  743.     /**
  744.      * Set the option arguments
  745.      * @access private
  746.      * @throws CONSOLE_GETARGS_ERROR_CONFIG
  747.      * @throws CONSOLE_GETARGS_ERROR_USER
  748.      * @return true|PEAR_Error
  749.      */
  750.     function setValue($optname$value&$pos)
  751.     {
  752.         if (!isset($this->_config[$optname]['max'])) {
  753.             // Max must be set for every option even if it is zero or -1.
  754.             return PEAR::raiseError('No max parameter set for '.$optname,
  755.                                     CONSOLE_GETARGS_ERROR_CONFIGPEAR_ERROR_TRIGGER,
  756.                                     E_USER_WARNING'Console_Getargs_Options::setValue()');
  757.         }
  758.         
  759.         $max $this->_config[$optname]['max'];
  760.         $min = isset($this->_config[$optname]['min']$this->_config[$optname]['min']$max;
  761.         
  762.         // A value was passed after the option.
  763.         if ($value !== ''{
  764.             // Argument is like -v5
  765.             if ($min == 1 && $max > 0{
  766.                 // At least one argument is required for option.
  767.                 $this->updateValue($optname$value);
  768.                 return true;
  769.             }
  770.             if ($max === 0{
  771.                 // Argument passed but not expected.
  772.                 return PEAR::raiseError('Argument '.$optname.' does not take any value',
  773.                                         CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  774.                                         null'Console_Getargs_Options::setValue()');
  775.             }
  776.             // Not enough arguments passed for this option.
  777.             return PEAR::raiseError('Argument '.$optname.' expects more than one value',
  778.                                     CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  779.                                     null'Console_Getargs_Options::setValue()');
  780.         }
  781.         
  782.         if ($min === 1 && $max === 1{
  783.             // Argument requires 1 value
  784.             // If optname is "parameters" take a step back.
  785.             if ($optname == CONSOLE_GETARGS_PARAMS{
  786.                 $pos--;
  787.             }
  788.             if (isset($this->args[$pos+1]&& $this->isValue($this->args[$pos+1])) {
  789.                 // Set the option value and increment the position.
  790.                 $this->updateValue($optname$this->args[$pos+1]);
  791.                 $pos++;
  792.                 return true;
  793.             }
  794.             // What we thought was the argument was really the next option.
  795.             return PEAR::raiseError('Argument '.$optname.' expects one value',
  796.                                     CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  797.                                     null'Console_Getargs_Options::setValue()');
  798.             
  799.         else if ($max === 0{
  800.             // Argument is a switch
  801.             if (isset($this->args[$pos+1]&& $this->isValue($this->args[$pos+1])) {
  802.                 // What we thought was the next option was really an argument for this option.
  803.                 // First update the value
  804.                 $this->updateValue($optnametrue);                
  805.                 // Then try to assign values to parameters.
  806.                 if (isset($this->_config[CONSOLE_GETARGS_PARAMS])) {
  807.                     return $this->setValue(CONSOLE_GETARGS_PARAMS''++$pos);
  808.                 else {
  809.                     return PEAR::raiseError('Argument '.$optname.' does not take any value',
  810.                                             CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  811.                                             null'Console_Getargs_Options::setValue()');
  812.                 }
  813.             }
  814.             // Set the switch to on.
  815.             $this->updateValue($optnametrue);
  816.             return true;
  817.             
  818.         else if ($max >= 1 && $min === 0{
  819.             // Argument has a default-if-set value
  820.             if (!isset($this->_config[$optname]['default'])) {
  821.                 // A default value MUST be assigned when config is loaded.
  822.                 return PEAR::raiseError('No default value defined for '.$optname,
  823.                                         CONSOLE_GETARGS_ERROR_CONFIGPEAR_ERROR_TRIGGER,
  824.                                         E_USER_WARNING'Console_Getargs_Options::setValue()');
  825.             }
  826.             if (is_array($this->_config[$optname]['default'])) {
  827.                 // Default value cannot be an array.
  828.                 return PEAR::raiseError('Default value for '.$optname.' must be scalar',
  829.                                         CONSOLE_GETARGS_ERROR_CONFIGPEAR_ERROR_TRIGGER,
  830.                                         E_USER_WARNING'Console_Getargs_Options::setValue()');
  831.             }
  832.             
  833.             // If optname is "parameters" take a step back.
  834.             if ($optname == CONSOLE_GETARGS_PARAMS{
  835.                 $pos--;
  836.             }
  837.             
  838.             if (isset($this->args[$pos+1]&& $this->isValue($this->args[$pos+1])) {
  839.                 // Assign the option the value from the command line if there is one.
  840.                 $this->updateValue($optname$this->args[$pos+1]);
  841.                 $pos++;
  842.                 return true;
  843.             }
  844.             // Otherwise use the default value.
  845.             $this->updateValue($optname$this->_config[$optname]['default']);
  846.             return true;
  847.         }
  848.         
  849.         // Argument takes one or more values
  850.         $added = 0;
  851.         // If trying to assign values to parameters, must go back one position.
  852.         if ($optname == CONSOLE_GETARGS_PARAMS{
  853.             $pos max($pos - 1-1);
  854.         }
  855.         for ($i $pos + 1; $i <= count($this->args)$i++{
  856.             $paramFull $max <= count($this->getValue($optname)) && $max != -1;
  857.             if (isset($this->args[$i]&& $this->isValue($this->args[$i]&& !$paramFull{
  858.                 // Add the argument value until the next option is hit.
  859.                 $this->updateValue($optname$this->args[$i]);
  860.                 $added++;
  861.                 $pos++;
  862.                 // Only keep trying if we haven't filled up yet.
  863.                 // or there is no limit
  864.                 if (($added $max || $max < 0&& ($max < 0 || !$paramFull)) {
  865.                     continue;
  866.                 }
  867.             }
  868.             if ($min $added && !$paramFull{
  869.                 // There aren't enough arguments for this option.
  870.                 return PEAR::raiseError('Argument '.$optname.' expects at least '.$min.(($min > 1' values' ' value'),
  871.                                         CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  872.                                         null'Console_Getargs_Options::setValue()');
  873.             elseif ($max !== -1 && $paramFull{
  874.                 // Too many arguments for this option.
  875.                 // Try to add the extra options to parameters.
  876.                 if (isset($this->_config[CONSOLE_GETARGS_PARAMS]&& $optname != CONSOLE_GETARGS_PARAMS{
  877.                     return $this->setValue(CONSOLE_GETARGS_PARAMS''++$pos);
  878.                 elseif ($optname == CONSOLE_GETARGS_PARAMS && empty($this->args[$i])) {
  879.                     $pos += $added;
  880.                     break;
  881.                 else {
  882.                     return PEAR::raiseError('Argument '.$optname.' expects maximum '.$max.' values',
  883.                                             CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  884.                                             null'Console_Getargs_Options::setValue()');
  885.                 }
  886.             }
  887.             break;
  888.         }
  889.         // Everything went well.
  890.         return true;
  891.     }
  892.     
  893.     /**
  894.      * Checks whether the given parameter is an argument or an option
  895.      * @access private
  896.      * @return boolean 
  897.      */
  898.     function isValue($arg)
  899.     {
  900.         if ((strlen($arg> 1 && $arg{0== '-' && $arg{1== '-'||
  901.             (strlen($arg> 1 && $arg{0== '-')) {
  902.             // The next argument is really an option.
  903.             return false;
  904.         }
  905.         return true;
  906.     }
  907.     
  908.     /**
  909.      * Adds the argument to the option
  910.      *
  911.      * If the argument for the option is already set,
  912.      * the option arguments will be changed to an array
  913.      * @access private
  914.      * @return void 
  915.      */
  916.     function updateValue($optname$value)
  917.     {
  918.         if (isset($this->_longLong[$optname])) {
  919.             if (is_array($this->_longLong[$optname])) {
  920.                 // Add this value to the list of values for this option.
  921.                 $this->_longLong[$optname][$value;
  922.             else {
  923.                 // There is already one value set. Turn everything into a list of values.
  924.                 $prevValue $this->_longLong[$optname];
  925.                 $this->_longLong[$optname= array($prevValue);
  926.                 $this->_longLong[$optname][$value;
  927.             }
  928.         else {
  929.             // This is the first value for this option.
  930.             $this->_longLong[$optname$value;
  931.         }
  932.     }
  933.     
  934.     /**
  935.      * Sets the option default arguments when necessary
  936.      * @access private
  937.      * @return true 
  938.      */
  939.     function setDefaults()
  940.     {
  941.         foreach ($this->_config as $longname => $def{
  942.             // Add the default value only if the default is defined 
  943.             // and the option requires at least one argument.
  944.             if (isset($def['default']&& 
  945.                 ((isset($def['min']&& $def['min'!== 0||
  946.                 (!isset($def['min']isset($def['max']&& $def['max'!== 0)) &&
  947.                 !isset($this->_longLong[$longname])) {
  948.                 $this->_longLong[$longname$def['default'];
  949.             }
  950.         }
  951.         return true;
  952.     }
  953.     
  954.     /**
  955.      * Checks whether the given option is defined
  956.      *
  957.      * An option will be defined if an argument was assigned to it using
  958.      * the command line options. You can use the short, the long or
  959.      * an alias name as parameter.
  960.      *
  961.      * @access public
  962.      * @param  string the name of the option to be checked
  963.      * @return boolean true if the option is defined
  964.      */
  965.     function isDefined($optname)
  966.     {
  967.         $longname $this->getLongName($optname);
  968.         if (isset($this->_longLong[$longname])) {
  969.             return true;
  970.         }
  971.         return false;
  972.     }
  973.     
  974.     /**
  975.      * Returns the long version of the given parameter
  976.      *
  977.      * If the given name is not found, it will return the name that
  978.      * was given, without further ensuring that the option
  979.      * actually exists
  980.      *
  981.      * @access private
  982.      * @param  string the name of the option
  983.      * @return string long version of the option name
  984.      */
  985.     function getLongName($optname)
  986.     {
  987.         if (isset($this->_shortLong[$optname])) {
  988.             // Short version was passed.
  989.             $longname $this->_shortLong[$optname];
  990.         else if (isset($this->_aliasLong[$optname])) {
  991.             // An alias was passed.
  992.             $longname $this->_aliasLong[$optname];
  993.         else {
  994.             // No further validation is done.
  995.             $longname $optname;
  996.         }
  997.         return $longname;
  998.     }
  999.     
  1000.     /**
  1001.      * Returns the argument of the given option
  1002.      *
  1003.      * You can use the short, alias or long version of the option name.
  1004.      * This method will try to find the argument(s) of the given option name.
  1005.      * If it is not found it will return null. If the arg has more than
  1006.      * one argument, an array of arguments will be returned.
  1007.      *
  1008.      * @access public
  1009.      * @param  string the name of the option
  1010.      * @return array|string|nullargument(s) associated with the option
  1011.      */
  1012.     function getValue($optname)
  1013.     {
  1014.         if ($this->isDefined($optname)) {
  1015.             // Option is defined. Return its value
  1016.             $longname $this->getLongName($optname);
  1017.             return $this->_longLong[$longname];
  1018.         }
  1019.         // Option is not defined.
  1020.         return null;
  1021.     }
  1022.  
  1023.     /**
  1024.      * Returns all arguments that have been parsed and recognized
  1025.      *
  1026.      * The name of the options are stored in the keys of the array.
  1027.      * You may choose whether you want to use the long or the short
  1028.      * option names
  1029.      *
  1030.      * @access public
  1031.      * @param  string   option names to use for the keys (long or short)
  1032.      * @return array    values for all options
  1033.      */
  1034.     function getValues($optionNames 'long')
  1035.     {
  1036.         switch ($optionNames{
  1037.             case 'short':
  1038.                 $values = array();
  1039.                 foreach ($this->_shortLong as $short => $long{
  1040.                     if (isset($this->_longLong[$long])) {
  1041.                         $values[$short$this->_longLong[$long];
  1042.                     }
  1043.                 }
  1044.                 if (isset($this->_longLong['parameters'])) {
  1045.                     $values['parameters'$this->_longLong['parameters'];
  1046.                 }
  1047.                 return $values;
  1048.             case 'long':
  1049.             default:
  1050.                 return $this->_longLong;
  1051.         }
  1052.     }
  1053. // end class Console_Getargs_Options
  1054. /*
  1055.  * Local variables:
  1056.  * tab-width: 4
  1057.  * c-basic-offset: 4
  1058.  * End:
  1059.  */
  1060. ?>

Documentation generated on Mon, 11 Mar 2019 14:20:37 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.