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.5 2004/10/07 23:31:46 scottmattocks 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 = array())
  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 = array())
  533.     {
  534.         if (is_array($arguments&& count($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.             
  624.             if ($arg === '--'{
  625.                 // '--' alone breaks the loop
  626.                 break;
  627.             }
  628.             if ($arg === '--help' || $arg === '-h'{
  629.                 // Asking for help breaks the loop.
  630.                 return PEAR::raiseError(nullCONSOLE_GETARGS_HELPPEAR_ERROR_RETURN);
  631.             }
  632.             if (strlen($arg> 1 && $arg{1== '-'{
  633.                 // Long name used (--option)
  634.                 $err $this->parseArg(substr($arg2)true$i);
  635.             else if (strlen($arg> 1 && $arg{0== '-'{
  636.                 // Short name used (-o)
  637.                 $err $this->parseArg(substr($arg1)false$i);
  638.                 if ($err === -1{
  639.                     break;
  640.                 }
  641.             elseif (isset($this->_config[CONSOLE_GETARGS_PARAMS])) {
  642.                 // No flags at all. Try the parameters option.
  643.                 $tempI &$i - 1;
  644.                 $err $this->parseArg(CONSOLE_GETARGS_PARAMStrue$tempI);
  645.             else {
  646.                 $err = PEAR::raiseError('Unknown argument '.$arg,
  647.                                         CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  648.                                         null'Console_Getargs_Options::parseArgs()');
  649.             }
  650.             if ($err !== true{
  651.                 return $err;
  652.             }
  653.         }
  654.         // Check to see if we need to reload the arguments
  655.         // due to concatenated short names.
  656.         if (isset($err&& $err === -1{
  657.             return $this->parseArgs();
  658.         }
  659.         
  660.         return true;
  661.     }
  662.     
  663.     /**
  664.      * Parses one option/argument
  665.      * @access private
  666.      * @throws CONSOLE_GETARGS_ERROR_USER
  667.      * @return true|PEAR_Error
  668.      */
  669.     function parseArg($arg$isLong&$pos)
  670.     {
  671.         // If the whole short option isn't in the shortLong array
  672.         // then break it into a bunch of switches.
  673.         if (!$isLong && !isset($this->_shortLong[$arg]&& strlen($arg> 1{
  674.             $newArgs = array();
  675.             for ($i = 0; $i strlen($arg)$i++{
  676.                 if (array_key_exists($arg{$i}$this->_shortLong)) {
  677.                     $newArgs['-' $arg{$i};
  678.                 else {
  679.                     $newArgs[$arg{$i};
  680.                 }
  681.             }
  682.             // Add the new args to the array.
  683.             array_splice($this->args$pos1$newArgs);
  684.             
  685.             // Reset the option values.
  686.             $this->_longLong = array();
  687.             
  688.             // Then reparse the arguments.
  689.             return -1;
  690.         }
  691.         
  692.         $opt '';
  693.         for ($i = 0; $i strlen($arg)$i++{
  694.             // Build the option name one char at a time looking for a match.
  695.             $opt .= $arg{$i};
  696.             if ($isLong === false && isset($this->_shortLong[$opt])) {
  697.                 // Found a match in the short option names.
  698.                 $cmp $opt;
  699.                 $long $this->_shortLong[$opt];
  700.             else if ($isLong === true && isset($this->_config[$opt])) {
  701.                 // Found a match in the long option names.
  702.                 $long $cmp $opt;
  703.             }
  704.             if ($arg{$i=== '='{
  705.                 // End of the option name when '=' is found.
  706.                 break;
  707.             }
  708.         }
  709.         
  710.         if (isset($long)) {
  711.             // A match was found.
  712.             if (strlen($argstrlen($cmp)) {
  713.                 // Seperate the argument from the option.
  714.                 // Ex: php test.php -f=image.png
  715.                 //     $cmp = 'f'
  716.                 //     $arg = 'f=image.png'
  717.                 $arg substr($argstrlen($cmp));
  718.                 // Now $arg = '=image.png'
  719.                 if ($arg{0=== '='{
  720.                     $arg substr($arg1);
  721.                     // Now $arg = 'image.png'
  722.                 }
  723.             else {
  724.                 // No argument passed for option.
  725.                 $arg '';
  726.             }
  727.             // Set the options value.
  728.             return $this->setValue($long$arg$pos);
  729.         }
  730.         return PEAR::raiseError('Unknown argument '.$opt,
  731.                                 CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  732.                                 null'Console_Getargs_Options::parseArg()');
  733.     }
  734.     
  735.     /**
  736.      * Set the option arguments
  737.      * @access private
  738.      * @throws CONSOLE_GETARGS_ERROR_CONFIG
  739.      * @throws CONSOLE_GETARGS_ERROR_USER
  740.      * @return true|PEAR_Error
  741.      */
  742.     function setValue($optname$value&$pos)
  743.     {
  744.         if (!isset($this->_config[$optname]['max'])) {
  745.             // Max must be set for every option even if it is zero or -1.
  746.             return PEAR::raiseError('No max parameter set for '.$optname,
  747.                                     CONSOLE_GETARGS_ERROR_CONFIGPEAR_ERROR_TRIGGER,
  748.                                     E_USER_WARNING'Console_Getargs_Options::setValue()');
  749.         }
  750.         
  751.         $max $this->_config[$optname]['max'];
  752.         $min = isset($this->_config[$optname]['min']$this->_config[$optname]['min']$max;
  753.         
  754.         // A value was passed after the option.
  755.         if ($value !== ''{
  756.             // Argument is like -v5
  757.             if ($min == 1 && $max > 0{
  758.                 // At least one argument is required for option.
  759.                 $this->updateValue($optname$value);
  760.                 return true;
  761.             }
  762.             if ($max === 0{
  763.                 // Argument passed but not expected.
  764.                 return PEAR::raiseError('Argument '.$optname.' does not take any value',
  765.                                         CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  766.                                         null'Console_Getargs_Options::setValue()');
  767.             }
  768.             // Not enough arguments passed for this option.
  769.             return PEAR::raiseError('Argument '.$optname.' expects more than one value',
  770.                                     CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  771.                                     null'Console_Getargs_Options::setValue()');
  772.         }
  773.         
  774.         if ($min === 1 && $max === 1{
  775.             // Argument requires 1 value
  776.             // If optname is "parameters" take a step back.
  777.             if ($optname == CONSOLE_GETARGS_PARAMS{
  778.                 $pos--;
  779.             }
  780.             if (isset($this->args[$pos+1]&& $this->isValue($this->args[$pos+1])) {
  781.                 // Set the option value and increment the position.
  782.                 $this->updateValue($optname$this->args[$pos+1]);
  783.                 $pos++;
  784.                 return true;
  785.             }
  786.             // What we thought was the argument was really the next option.
  787.             return PEAR::raiseError('Argument '.$optname.' expects one value',
  788.                                     CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  789.                                     null'Console_Getargs_Options::setValue()');
  790.             
  791.         else if ($max === 0{
  792.             // Argument is a switch
  793.             if (isset($this->args[$pos+1]&& $this->isValue($this->args[$pos+1])) {
  794.                 // What we thought was the next option was really an argument for this option.
  795.                 // First update the value
  796.                 $this->updateValue($optnametrue);                
  797.                 // Then try to assign values to parameters.
  798.                 if (isset($this->_config[CONSOLE_GETARGS_PARAMS])) {
  799.                     return $this->setValue(CONSOLE_GETARGS_PARAMS''++$pos);
  800.                 else {
  801.                     return PEAR::raiseError('Argument '.$optname.' does not take any value',
  802.                                             CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  803.                                             null'Console_Getargs_Options::setValue()');
  804.                 }
  805.             }
  806.             // Set the switch to on.
  807.             $this->updateValue($optnametrue);
  808.             return true;
  809.             
  810.         else if ($max >= 1 && $min === 0{
  811.             // Argument has a default-if-set value
  812.             if (!isset($this->_config[$optname]['default'])) {
  813.                 // A default value MUST be assigned when config is loaded.
  814.                 return PEAR::raiseError('No default value defined for '.$optname,
  815.                                         CONSOLE_GETARGS_ERROR_CONFIGPEAR_ERROR_TRIGGER,
  816.                                         E_USER_WARNING'Console_Getargs_Options::setValue()');
  817.             }
  818.             if (is_array($this->_config[$optname]['default'])) {
  819.                 // Default value cannot be an array.
  820.                 return PEAR::raiseError('Default value for '.$optname.' must be scalar',
  821.                                         CONSOLE_GETARGS_ERROR_CONFIGPEAR_ERROR_TRIGGER,
  822.                                         E_USER_WARNING'Console_Getargs_Options::setValue()');
  823.             }
  824.             
  825.             // If optname is "parameters" take a step back.
  826.             if ($optname == CONSOLE_GETARGS_PARAMS{
  827.                 $pos--;
  828.             }
  829.             
  830.             if (isset($this->args[$pos+1]&& $this->isValue($this->args[$pos+1])) {
  831.                 // Assign the option the value from the command line if there is one.
  832.                 $this->updateValue($optname$this->args[$pos+1]);
  833.                 $pos++;
  834.                 return true;
  835.             }
  836.             // Otherwise use the default value.
  837.             $this->updateValue($optname$this->_config[$optname]['default']);
  838.             return true;
  839.         }
  840.         
  841.         // Argument takes one or more values
  842.         $added = 0;
  843.         // If trying to assign values to parameters, must go back one position.
  844.         if ($optname == CONSOLE_GETARGS_PARAMS{
  845.             $pos max($pos - 1-1);
  846.         }
  847.         for ($i $pos + 1; $i <= count($this->args)$i++{
  848.             if (isset($this->args[$i]&& $this->isValue($this->args[$i])) {
  849.                 // Add the argument value until the next option is hit.
  850.                 $this->updateValue($optname$this->args[$i]);
  851.                 $added++;
  852.                 $pos++;
  853.                 // Only keep trying if we haven't filled up yet.
  854.                 // or there is no limit
  855.                 if ($added $max || $max < 0{
  856.                     continue;
  857.                 }
  858.             }
  859.             if ($min $added{
  860.                 // There aren't enough arguments for this option.
  861.                 return PEAR::raiseError('Argument '.$optname.' expects at least '.$min.(($min > 1' values' ' value'),
  862.                                         CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  863.                                         null'Console_Getargs_Options::setValue()');
  864.             else if ($max !== -1 && $added >= $max{
  865.                 // Too many arguments for this option.
  866.                 // Try to add the extra options to parameters.
  867.                 if (isset($this->_config[CONSOLE_GETARGS_PARAMS]&& $optname != CONSOLE_GETARGS_PARAMS{
  868.                     return $this->setValue(CONSOLE_GETARGS_PARAMS''++$pos);
  869.                 elseif ($optname == CONSOLE_GETARGS_PARAMS && !isset($this->args[$i + 1])) {
  870.                     $pos += $added;
  871.                     break;
  872.                 else {
  873.                     return PEAR::raiseError('Argument '.$optname.' expects maximum '.$max.' values',
  874.                                             CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  875.                                             null'Console_Getargs_Options::setValue()');
  876.                 }
  877.             }
  878.             break;
  879.         }
  880.         // Everything went well.
  881.         return true;
  882.     }
  883.     
  884.     /**
  885.      * Checks whether the given parameter is an argument or an option
  886.      * @access private
  887.      * @return boolean 
  888.      */
  889.     function isValue($arg)
  890.     {
  891.         if (strlen($arg> 1 && $arg{1== '-' ||
  892.             strlen($arg> 1 && $arg{0== '-'{
  893.             // The next argument is really an option.
  894.             return false;
  895.         }
  896.         return true;
  897.     }
  898.     
  899.     /**
  900.      * Adds the argument to the option
  901.      *
  902.      * If the argument for the option is already set,
  903.      * the option arguments will be changed to an array
  904.      * @access private
  905.      * @return void 
  906.      */
  907.     function updateValue($optname$value)
  908.     {
  909.         if (isset($this->_longLong[$optname])) {
  910.             if (is_array($this->_longLong[$optname])) {
  911.                 // Add this value to the list of values for this option.
  912.                 $this->_longLong[$optname][$value;
  913.             else {
  914.                 // There is already one value set. Turn everything into a list of values.
  915.                 $prevValue $this->_longLong[$optname];
  916.                 $this->_longLong[$optname= array($prevValue);
  917.                 $this->_longLong[$optname][$value;
  918.             }
  919.         else {
  920.             // This is the first value for this option.
  921.             $this->_longLong[$optname$value;
  922.         }
  923.     }
  924.     
  925.     /**
  926.      * Sets the option default arguments when necessary
  927.      * @access private
  928.      * @return true 
  929.      */
  930.     function setDefaults()
  931.     {
  932.         foreach ($this->_config as $longname => $def{
  933.             // Add the default value only if the default is defined 
  934.             // and the option requires at least one argument.
  935.             if (isset($def['default']&& $def['min'!== 0 && !isset($this->_longLong[$longname])) {
  936.                 $this->_longLong[$longname$def['default'];
  937.             }
  938.         }
  939.         return true;
  940.     }
  941.     
  942.     /**
  943.      * Checks whether the given option is defined
  944.      *
  945.      * An option will be defined if an argument was assigned to it using
  946.      * the command line options. You can use the short, the long or
  947.      * an alias name as parameter.
  948.      *
  949.      * @access public
  950.      * @param  string the name of the option to be checked
  951.      * @return boolean true if the option is defined
  952.      */
  953.     function isDefined($optname)
  954.     {
  955.         $longname $this->getLongName($optname);
  956.         if (isset($this->_longLong[$longname])) {
  957.             return true;
  958.         }
  959.         return false;
  960.     }
  961.     
  962.     /**
  963.      * Returns the long version of the given parameter
  964.      *
  965.      * If the given name is not found, it will return the name that
  966.      * was given, without further ensuring that the option
  967.      * actually exists
  968.      *
  969.      * @access private
  970.      * @param  string the name of the option
  971.      * @return string long version of the option name
  972.      */
  973.     function getLongName($optname)
  974.     {
  975.         if (isset($this->_shortLong[$optname])) {
  976.             // Short version was passed.
  977.             $longname $this->_shortLong[$optname];
  978.         else if (isset($this->_aliasLong[$optname])) {
  979.             // An alias was passed.
  980.             $longname $this->_aliasLong[$optname];
  981.         else {
  982.             // No further validation is done.
  983.             $longname $optname;
  984.         }
  985.         return $longname;
  986.     }
  987.     
  988.     /**
  989.      * Returns the argument of the given option
  990.      *
  991.      * You can use the short, alias or long version of the option name.
  992.      * This method will try to find the argument(s) of the given option name.
  993.      * If it is not found it will return null. If the arg has more than
  994.      * one argument, an array of arguments will be returned.
  995.      *
  996.      * @access public
  997.      * @param  string the name of the option
  998.      * @return array|string|nullargument(s) associated with the option
  999.      */
  1000.     function getValue($optname)
  1001.     {
  1002.         if ($this->isDefined($optname)) {
  1003.             // Option is defined. Return its value
  1004.             $longname $this->getLongName($optname);
  1005.             return $this->_longLong[$longname];
  1006.         }
  1007.         // Option is not defined.
  1008.         return null;
  1009.     }
  1010. // end class Console_Getargs_Options
  1011. /*
  1012.  * Local variables:
  1013.  * tab-width: 4
  1014.  * c-basic-offset: 4
  1015.  * End:
  1016.  */
  1017. ?>

Documentation generated on Mon, 11 Mar 2019 13:57:32 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.