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.18 2005/12/04 16:43:14 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.             if (isset($_SERVER['SCRIPT_NAME'])) {
  288.                 $filename basename($_SERVER['SCRIPT_NAME']);
  289.             else {
  290.                 $filename $argv[0];
  291.             }
  292.             $helpHeader 'Usage: '$filename ' ';
  293.             // Add the optional arguments and required arguments.
  294.             $helpHeader.= $optional ' ' $required ' ';
  295.             // Add any parameters that are needed.
  296.             $helpHeader.= $params "\n\n";
  297.         }
  298.         
  299.         // Build the list of options and definitions.
  300.         $i = 0;
  301.         foreach ($config as $long => $def{
  302.             
  303.             // Break the names up if there is more than one for an option.
  304.             $shortArr = array();
  305.             if (isset($def['short'])) {
  306.                 $shortArr explode('|'$def['short']);
  307.             }
  308.             $longArr explode('|'$long);
  309.             
  310.             // Column one is the option name displayed as "-short, --long [additional info]"
  311.             // Add the short option name.
  312.             $col1[$i!empty($shortArr'-'.$shortArr[0].' ' '';
  313.             // Add the long option name.
  314.             $col1[$i.= '--'.$longArr[0];
  315.             
  316.             // Get the min and max to show needed/optional values.
  317.             $max $def['max'];
  318.             $min = isset($def['min']$def['min'$max;
  319.             
  320.             if ($max === 1 && $min === 1{
  321.                 // One value required.
  322.                 $col1[$i.= '=<value>';
  323.             else if ($max > 1{
  324.                 if ($min === $max{
  325.                     // More than one value needed.
  326.                     $col1[$i.= ' values('.$max.')';
  327.                 else if ($min === 0{
  328.                     // Argument takes optional value(s).
  329.                     $col1[$i.= ' values(optional)';
  330.                 else {
  331.                     // Argument takes a range of values.
  332.                     $col1[$i.= ' values('.$min.'-'.$max.')';
  333.                 }
  334.             else if ($max === 1 && $min === 0{
  335.                 // Argument can take at most one value.
  336.                 $col1[$i.= ' (optional)value';
  337.             else if ($max === -1{
  338.                 // Argument can take unlimited values.
  339.                 if ($min > 0{
  340.                     $col1[$i.= ' values('.$min.'-...)';
  341.                 else {
  342.                     $col1[$i.= ' (optional)values';
  343.                 }
  344.             }
  345.             
  346.             // Column two is the description if available.
  347.             if (isset($def['desc'])) {
  348.                 $col2[$i$def['desc'];
  349.             else {
  350.                 $col2[$i'';
  351.             }
  352.             // Add the default value(s) if there are any/
  353.             if (isset($def['default'])) {
  354.                 if (is_array($def['default'])) {
  355.                     $col2[$i.= ' ('.implode(', '$def['default']).')';
  356.                 else {
  357.                     $col2[$i.= ' ('.$def['default'].')';
  358.                 }
  359.             }
  360.             $i++;
  361.         }
  362.         
  363.         // Figure out the maximum length for column one.
  364.         $arglen = 0;
  365.         foreach ($col1 as $txt{
  366.             $length strlen($txt);
  367.             if ($length $arglen{
  368.                 $arglen $length;
  369.             }
  370.         }
  371.         
  372.         // The maximum length for each description line.
  373.         $desclen $maxlength $arglen;
  374.         $padding str_repeat(' '$arglen);
  375.         foreach ($col1 as $k => $txt{
  376.             // Wrap the descriptions.
  377.             if (strlen($col2[$k]$desclen{
  378.                 $desc wordwrap($col2[$k]$desclen"\n  ".$padding);
  379.             else {
  380.                 $desc $col2[$k];
  381.             }
  382.             // Push everything together.
  383.             $help .= str_pad($txt$arglen).'  '.$desc."\n";
  384.         }
  385.         
  386.         // Put it all together.
  387.         return $helpHeader.$help.$helpFooter;
  388.     }
  389.     
  390.     /**
  391.      * Parse the config array to determine which flags are
  392.      * optional and which are required.
  393.      *
  394.      * To make the help header more descriptive, the options
  395.      * are shown seperated into optional and required flags.
  396.      * When possible the short flag is used for readability.
  397.      * Optional items (including "parameters") are surrounded
  398.      * in square braces ([-vd]). Required flags are surrounded
  399.      * in angle brackets (<-wf>).
  400.      *
  401.      * This method may be called statically.
  402.      *
  403.      * @access  public
  404.      * @param   &$config The config array.
  405.      * @return  array 
  406.      * @author  Scott Mattocks
  407.      * @package Console_Getargs
  408.      */
  409.     function getOptionalRequired(&$config)
  410.     {
  411.         // Parse the config array and look for optional/required
  412.         // tags.
  413.         $optional         '';
  414.         $optionalHasShort = false;
  415.         $required         '';
  416.         $requiredHasShort = false;
  417.         
  418.         ksort($config);
  419.         foreach ($config as $long => $def{
  420.             
  421.             // We only really care about the first option name.
  422.             $long explode('|'$long);
  423.             $long reset($long);
  424.             
  425.             // Treat the "parameters" specially.
  426.             if ($long == CONSOLE_GETARGS_PARAMS{
  427.                 continue;
  428.             }
  429.             // We only really care about the first option name.
  430.             $def['short'explode('|'$def['short']);
  431.             $def['short'reset($def['short']);
  432.             
  433.             if (!isset($def['min']|| $def['min'== 0 || isset($def['default'])) {
  434.                 // This argument is optional.
  435.                 if (isset($def['short']&& strlen($def['short']== 1{
  436.                     $optional         $def['short'$optional;
  437.                     $optionalHasShort = true;
  438.                 else {
  439.                     $optional.= ' --' $long;
  440.                 }
  441.             else {
  442.                 // This argument is required.
  443.                 if (isset($def['short']&& strlen($def['short']== 1{
  444.                     $required         $def['short'$required;
  445.                     $requiredHasShort = true;
  446.                 else {
  447.                     $required.= ' --' $long;
  448.                 }
  449.             }
  450.         }
  451.         
  452.         // Check for "parameters" option.
  453.         $params '';
  454.         if (isset($config[CONSOLE_GETARGS_PARAMS])) {
  455.             for ($i = 1; $i <= max($config[CONSOLE_GETARGS_PARAMS]['max']$config[CONSOLE_GETARGS_PARAMS]['min']); ++$i{
  456.                 if ($config[CONSOLE_GETARGS_PARAMS]['max'== -1 ||
  457.                     ($i $config[CONSOLE_GETARGS_PARAMS]['min'&&
  458.                      $i <= $config[CONSOLE_GETARGS_PARAMS]['max']||
  459.                     isset($config[CONSOLE_GETARGS_PARAMS]['default'])) {
  460.                     // Parameter is optional.
  461.                     $params.= '[param' $i .'] ';
  462.                 else {
  463.                     // Parameter is required.
  464.                     $params.= 'param' $i ' ';
  465.                 }
  466.             }
  467.         }
  468.         // Add a leading - if needed.
  469.         if ($optionalHasShort{
  470.             $optional '-' $optional;
  471.         }
  472.         
  473.         if ($requiredHasShort{
  474.             $required '-' $required;
  475.         }
  476.         
  477.         // Add the extra characters if needed.
  478.         if (!empty($optional)) {
  479.             $optional '[' $optional ']';
  480.         }
  481.         if (!empty($required)) {
  482.             $required '<' $required '>';
  483.         }
  484.         
  485.         return array($optional$required$params);
  486.     }
  487. // end class Console_Getargs
  488.  
  489. /**
  490.  * This class implements a wrapper to the command line options and arguments.
  491.  *
  492.  * @author Bertrand Mansion <bmansion@mamasam.com>
  493.  * @package  Console_Getargs
  494.  */
  495. {
  496.     
  497.     /**
  498.      * Lookup to match short options name with long ones
  499.      * @var array 
  500.      * @access private
  501.      */
  502.     var $_shortLong = array();
  503.     
  504.     /**
  505.      * Lookup to match alias options name with long ones
  506.      * @var array 
  507.      * @access private
  508.      */
  509.     var $_aliasLong = array();
  510.     
  511.     /**
  512.      * Arguments set for the options
  513.      * @var array 
  514.      * @access private
  515.      */
  516.     var $_longLong = array();
  517.     
  518.     /**
  519.      * Configuration set at initialization time
  520.      * @var array 
  521.      * @access private
  522.      */
  523.     var $_config = array();
  524.     
  525.     /**
  526.      * A read/write copy of argv
  527.      * @var array 
  528.      * @access private
  529.      */
  530.     var $args = array();
  531.     
  532.     /**
  533.      * Initializes the Console_Getargs_Options object
  534.      * @param array configuration options
  535.      * @access private
  536.      * @throws CONSOLE_GETARGS_ERROR_CONFIG
  537.      * @return true|PEAR_Error
  538.      */
  539.     function init($config$arguments = NULL)
  540.     {
  541.         if (is_array($arguments)) {
  542.             // Use the user defined argument list.
  543.             $this->args $arguments;
  544.         else {
  545.             // Command line arguments must be available.
  546.             if (!isset($_SERVER['argv']|| !is_array($_SERVER['argv'])) {
  547.                 return PEAR::raiseError("Could not read argv"CONSOLE_GETARGS_ERROR_CONFIG,
  548.                                         PEAR_ERROR_TRIGGERE_USER_WARNING'Console_Getargs_Options::init()');
  549.             }
  550.             $this->args $_SERVER['argv'];
  551.         }
  552.         
  553.         // Drop the first argument if it doesn't begin with a '-'.
  554.         if (isset($this->args[0]{0}&& $this->args[0]{0!= '-'{
  555.             array_shift($this->args);
  556.         }
  557.         $this->_config $config;
  558.         return true;
  559.     }
  560.     
  561.     /**
  562.      * Makes the lookup arrays for alias and short name mapping with long names
  563.      * @access private
  564.      * @throws CONSOLE_GETARGS_ERROR_CONFIG
  565.      * @return true|PEAR_Error
  566.      */
  567.     function buildMaps()
  568.     {
  569.         foreach($this->_config as $long => $def{
  570.             
  571.             $longArr explode('|'$long);
  572.             $longname $longArr[0];
  573.             
  574.             if (count($longArr> 1{
  575.                 // The fisrt item in the list is "the option".
  576.                 // The rest are aliases.
  577.                 array_shift($longArr);
  578.                 foreach($longArr as $alias{
  579.                     // Watch out for duplicate aliases.
  580.                     if (isset($this->_aliasLong[$alias])) {
  581.                         return PEAR::raiseError('Duplicate alias for long option '.$aliasCONSOLE_GETARGS_ERROR_CONFIG,
  582.                                                 PEAR_ERROR_TRIGGERE_USER_WARNING'Console_Getargs_Options::buildMaps()');
  583.                         
  584.                     }
  585.                     $this->_aliasLong[$alias$longname;
  586.                 }
  587.                 // Add the real option name and defintion.
  588.                 $this->_config[$longname$def;
  589.                 // Get rid of the old version (name|alias1|...)
  590.                 unset($this->_config[$long]);
  591.             }
  592.             
  593.             // Add the (optional) short option names.
  594.             if (!empty($def['short'])) {
  595.                 // Short names
  596.                 $shortArr explode('|'$def['short']);
  597.                 $short $shortArr[0];
  598.                 if (count($shortArr> 1{
  599.                     // The first item is "the option".
  600.                     // The rest are aliases.
  601.                     array_shift($shortArr);
  602.                     foreach ($shortArr as $alias{
  603.                         // Watch out for duplicate aliases.
  604.                         if (isset($this->_shortLong[$alias])) {
  605.                             return PEAR::raiseError('Duplicate alias for short option '.$aliasCONSOLE_GETARGS_ERROR_CONFIG,
  606.                                                     PEAR_ERROR_TRIGGERE_USER_WARNING'Console_Getargs_Options::buildMaps()');
  607.                         }
  608.                         $this->_shortLong[$alias$longname;
  609.                     }
  610.                 }
  611.                 // Add the real short option name.
  612.                 $this->_shortLong[$short$longname;
  613.             }
  614.         }
  615.         return true;
  616.     }
  617.     
  618.     /**
  619.      * Parses the given options/arguments one by one
  620.      * @access private
  621.      * @throws CONSOLE_GETARGS_HELP
  622.      * @throws CONSOLE_GETARGS_ERROR_USER
  623.      * @return true|PEAR_Error
  624.      */
  625.     function parseArgs()
  626.     {
  627.         // Go through the options and parse the arguments for each.
  628.         for ($i = 0$count count($this->args)$i $count$i++{
  629.             $arg $this->args[$i];
  630.             if ($arg === '--help' || $arg === '-h'{
  631.                 // Asking for help breaks the loop.
  632.                 return PEAR::raiseError(nullCONSOLE_GETARGS_HELPPEAR_ERROR_RETURN);
  633.  
  634.             }
  635.             if ($arg === '--'{
  636.                 // '--' alone signals the start of "parameters"
  637.                 $err $this->parseArg(CONSOLE_GETARGS_PARAMStrue++$i);
  638.             elseif (strlen($arg> 1 && $arg{0== '-' && $arg{1== '-'{
  639.                 // Long name used (--option)
  640.                 $err $this->parseArg(substr($arg2)true$i);
  641.             else if (strlen($arg> 1 && $arg{0== '-'{
  642.                 // Short name used (-o)
  643.                 $err $this->parseArg(substr($arg1)false$i);
  644.                 if ($err === -1{
  645.                     break;
  646.                 }
  647.             elseif (isset($this->_config[CONSOLE_GETARGS_PARAMS])) {
  648.                 // No flags at all. Try the parameters option.
  649.                 $tempI &$i - 1;
  650.                 $err $this->parseArg(CONSOLE_GETARGS_PARAMStrue$tempI);
  651.             else {
  652.                 $err = PEAR::raiseError('Unknown argument '.$arg,
  653.                                         CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  654.                                         null'Console_Getargs_Options::parseArgs()');
  655.             }
  656.             if ($err !== true{
  657.                 return $err;
  658.             }
  659.         }
  660.         // Check to see if we need to reload the arguments
  661.         // due to concatenated short names.
  662.         if (isset($err&& $err === -1{
  663.             return $this->parseArgs();
  664.         }
  665.         
  666.         return true;
  667.     }
  668.     
  669.     /**
  670.      * Parses one option/argument
  671.      * @access private
  672.      * @throws CONSOLE_GETARGS_ERROR_USER
  673.      * @return true|PEAR_Error
  674.      */
  675.     function parseArg($arg$isLong&$pos)
  676.     {
  677.         // If the whole short option isn't in the shortLong array
  678.         // then break it into a bunch of switches.
  679.         if (!$isLong && !isset($this->_shortLong[$arg]&& strlen($arg> 1{
  680.             $newArgs = array();
  681.             for ($i = 0; $i strlen($arg)$i++{
  682.                 if (array_key_exists($arg{$i}$this->_shortLong)) {
  683.                     $newArgs['-' $arg{$i};
  684.                 else {
  685.                     $newArgs[$arg{$i};
  686.                 }
  687.             }
  688.             // Add the new args to the array.
  689.             array_splice($this->args$pos1$newArgs);
  690.             
  691.             // Reset the option values.
  692.             $this->_longLong = array();
  693.             
  694.             // Then reparse the arguments.
  695.             return -1;
  696.         }
  697.         
  698.         $opt '';
  699.         for ($i = 0; $i strlen($arg)$i++{
  700.             // Build the option name one char at a time looking for a match.
  701.             $opt .= $arg{$i};
  702.             if ($isLong === false && isset($this->_shortLong[$opt])) {
  703.                 // Found a match in the short option names.
  704.                 $cmp $opt;
  705.                 $long $this->_shortLong[$opt];
  706.             elseif ($isLong === true && isset($this->_config[$opt])) {
  707.                 // Found a match in the long option names.
  708.                 $long $cmp $opt;
  709.             elseif ($isLong === true && isset($this->_aliasLong[$opt])) {
  710.                 // Found a match in the long option names.
  711.                 $long $this->_aliasLong[$opt];
  712.                 $cmp $opt;
  713.             }
  714.             if ($arg{$i=== '='{
  715.                 // End of the option name when '=' is found.
  716.                 break;
  717.             }
  718.         }
  719.  
  720.         // If no option name is found, assume -- was passed.
  721.         if ($opt == ''{
  722.             $long CONSOLE_GETARGS_PARAMS;
  723.         }
  724.         
  725.         if (isset($long)) {
  726.             // A match was found.
  727.             if (strlen($argstrlen($cmp)) {
  728.                 // Seperate the argument from the option.
  729.                 // Ex: php test.php -f=image.png
  730.                 //     $cmp = 'f'
  731.                 //     $arg = 'f=image.png'
  732.                 $arg substr($argstrlen($cmp));
  733.                 // Now $arg = '=image.png'
  734.                 if ($arg{0=== '='{
  735.                     $arg substr($arg1);
  736.                     // Now $arg = 'image.png'
  737.                 }
  738.             else {
  739.                 // No argument passed for option.
  740.                 $arg '';
  741.             }
  742.             // Set the options value.
  743.             return $this->setValue($long$arg$pos);
  744.         }
  745.         return PEAR::raiseError('Unknown argument '.$opt,
  746.                                 CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  747.                                 null'Console_Getargs_Options::parseArg()');
  748.     }
  749.     
  750.     /**
  751.      * Set the option arguments
  752.      * @access private
  753.      * @throws CONSOLE_GETARGS_ERROR_CONFIG
  754.      * @throws CONSOLE_GETARGS_ERROR_USER
  755.      * @return true|PEAR_Error
  756.      */
  757.     function setValue($optname$value&$pos)
  758.     {
  759.         if (!isset($this->_config[$optname]['max'])) {
  760.             // Max must be set for every option even if it is zero or -1.
  761.             return PEAR::raiseError('No max parameter set for '.$optname,
  762.                                     CONSOLE_GETARGS_ERROR_CONFIGPEAR_ERROR_TRIGGER,
  763.                                     E_USER_WARNING'Console_Getargs_Options::setValue()');
  764.         }
  765.         
  766.         $max $this->_config[$optname]['max'];
  767.         $min = isset($this->_config[$optname]['min']$this->_config[$optname]['min']$max;
  768.         
  769.         // A value was passed after the option.
  770.         if ($value !== ''{
  771.             // Argument is like -v5
  772.             if ($min == 1 && $max > 0{
  773.                 // At least one argument is required for option.
  774.                 $this->updateValue($optname$value);
  775.                 return true;
  776.             }
  777.             if ($max === 0{
  778.                 // Argument passed but not expected.
  779.                 return PEAR::raiseError('Argument '.$optname.' does not take any value',
  780.                                         CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  781.                                         null'Console_Getargs_Options::setValue()');
  782.             }
  783.             // Not enough arguments passed for this option.
  784.             return PEAR::raiseError('Argument '.$optname.' expects more than one value',
  785.                                     CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  786.                                     null'Console_Getargs_Options::setValue()');
  787.         }
  788.         
  789.         if ($min === 1 && $max === 1{
  790.             // Argument requires 1 value
  791.             // If optname is "parameters" take a step back.
  792.             if ($optname == CONSOLE_GETARGS_PARAMS{
  793.                 $pos--;
  794.             }
  795.             if (isset($this->args[$pos+1]&& $this->isValue($this->args[$pos+1])) {
  796.                 // Set the option value and increment the position.
  797.                 $this->updateValue($optname$this->args[$pos+1]);
  798.                 $pos++;
  799.                 return true;
  800.             }
  801.             // What we thought was the argument was really the next option.
  802.             return PEAR::raiseError('Argument '.$optname.' expects one value',
  803.                                     CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  804.                                     null'Console_Getargs_Options::setValue()');
  805.             
  806.         else if ($max === 0{
  807.             // Argument is a switch
  808.             if (isset($this->args[$pos+1]&& $this->isValue($this->args[$pos+1])) {
  809.                 // What we thought was the next option was really an argument for this option.
  810.                 // First update the value
  811.                 $this->updateValue($optnametrue);                
  812.                 // Then try to assign values to parameters.
  813.                 if (isset($this->_config[CONSOLE_GETARGS_PARAMS])) {
  814.                     return $this->setValue(CONSOLE_GETARGS_PARAMS''++$pos);
  815.                 else {
  816.                     return PEAR::raiseError('Argument '.$optname.' does not take any value',
  817.                                             CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  818.                                             null'Console_Getargs_Options::setValue()');
  819.                 }
  820.             }
  821.             // Set the switch to on.
  822.             $this->updateValue($optnametrue);
  823.             return true;
  824.             
  825.         else if ($max >= 1 && $min === 0{
  826.             // Argument has a default-if-set value
  827.             if (!isset($this->_config[$optname]['default'])) {
  828.                 // A default value MUST be assigned when config is loaded.
  829.                 return PEAR::raiseError('No default value defined for '.$optname,
  830.                                         CONSOLE_GETARGS_ERROR_CONFIGPEAR_ERROR_TRIGGER,
  831.                                         E_USER_WARNING'Console_Getargs_Options::setValue()');
  832.             }
  833.             if (is_array($this->_config[$optname]['default'])) {
  834.                 // Default value cannot be an array.
  835.                 return PEAR::raiseError('Default value for '.$optname.' must be scalar',
  836.                                         CONSOLE_GETARGS_ERROR_CONFIGPEAR_ERROR_TRIGGER,
  837.                                         E_USER_WARNING'Console_Getargs_Options::setValue()');
  838.             }
  839.             
  840.             // If optname is "parameters" take a step back.
  841.             if ($optname == CONSOLE_GETARGS_PARAMS{
  842.                 $pos--;
  843.             }
  844.             
  845.             if (isset($this->args[$pos+1]&& $this->isValue($this->args[$pos+1])) {
  846.                 // Assign the option the value from the command line if there is one.
  847.                 $this->updateValue($optname$this->args[$pos+1]);
  848.                 $pos++;
  849.                 return true;
  850.             }
  851.             // Otherwise use the default value.
  852.             $this->updateValue($optname$this->_config[$optname]['default']);
  853.             return true;
  854.         }
  855.         
  856.         // Argument takes one or more values
  857.         $added = 0;
  858.         // If trying to assign values to parameters, must go back one position.
  859.         if ($optname == CONSOLE_GETARGS_PARAMS{
  860.             $pos max($pos - 1-1);
  861.         }
  862.         for ($i $pos + 1; $i <= count($this->args)$i++{
  863.             $paramFull $max <= count($this->getValue($optname)) && $max != -1;
  864.             if (isset($this->args[$i]&& $this->isValue($this->args[$i]&& !$paramFull{
  865.                 // Add the argument value until the next option is hit.
  866.                 $this->updateValue($optname$this->args[$i]);
  867.                 $added++;
  868.                 $pos++;
  869.                 // Only keep trying if we haven't filled up yet.
  870.                 // or there is no limit
  871.                 if (($added $max || $max < 0&& ($max < 0 || !$paramFull)) {
  872.                     continue;
  873.                 }
  874.             }
  875.             if ($min $added && !$paramFull{
  876.                 // There aren't enough arguments for this option.
  877.                 return PEAR::raiseError('Argument '.$optname.' expects at least '.$min.(($min > 1' values' ' value'),
  878.                                         CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  879.                                         null'Console_Getargs_Options::setValue()');
  880.             elseif ($max !== -1 && $paramFull{
  881.                 // Too many arguments for this option.
  882.                 // Try to add the extra options to parameters.
  883.                 if (isset($this->_config[CONSOLE_GETARGS_PARAMS]&& $optname != CONSOLE_GETARGS_PARAMS{
  884.                     return $this->setValue(CONSOLE_GETARGS_PARAMS''++$pos);
  885.                 elseif ($optname == CONSOLE_GETARGS_PARAMS && empty($this->args[$i])) {
  886.                     $pos += $added;
  887.                     break;
  888.                 else {
  889.                     return PEAR::raiseError('Argument '.$optname.' expects maximum '.$max.' values',
  890.                                             CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  891.                                             null'Console_Getargs_Options::setValue()');
  892.                 }
  893.             }
  894.             break;
  895.         }
  896.         // Everything went well.
  897.         return true;
  898.     }
  899.     
  900.     /**
  901.      * Checks whether the given parameter is an argument or an option
  902.      * @access private
  903.      * @return boolean 
  904.      */
  905.     function isValue($arg)
  906.     {
  907.         if ((strlen($arg> 1 && $arg{0== '-' && $arg{1== '-'||
  908.             (strlen($arg> 1 && $arg{0== '-')) {
  909.             // The next argument is really an option.
  910.             return false;
  911.         }
  912.         return true;
  913.     }
  914.     
  915.     /**
  916.      * Adds the argument to the option
  917.      *
  918.      * If the argument for the option is already set,
  919.      * the option arguments will be changed to an array
  920.      * @access private
  921.      * @return void 
  922.      */
  923.     function updateValue($optname$value)
  924.     {
  925.         if (isset($this->_longLong[$optname])) {
  926.             if (is_array($this->_longLong[$optname])) {
  927.                 // Add this value to the list of values for this option.
  928.                 $this->_longLong[$optname][$value;
  929.             else {
  930.                 // There is already one value set. Turn everything into a list of values.
  931.                 $prevValue $this->_longLong[$optname];
  932.                 $this->_longLong[$optname= array($prevValue);
  933.                 $this->_longLong[$optname][$value;
  934.             }
  935.         else {
  936.             // This is the first value for this option.
  937.             $this->_longLong[$optname$value;
  938.         }
  939.     }
  940.     
  941.     /**
  942.      * Sets the option default arguments when necessary
  943.      * @access private
  944.      * @return true 
  945.      */
  946.     function setDefaults()
  947.     {
  948.         foreach ($this->_config as $longname => $def{
  949.             // Add the default value only if the default is defined 
  950.             // and the option requires at least one argument.
  951.             if (isset($def['default']&& 
  952.                 ((isset($def['min']&& $def['min'!== 0||
  953.                 (!isset($def['min']isset($def['max']&& $def['max'!== 0)) &&
  954.                 !isset($this->_longLong[$longname])) {
  955.                 $this->_longLong[$longname$def['default'];
  956.             }
  957.         }
  958.         return true;
  959.     }
  960.     
  961.     /**
  962.      * Checks whether the given option is defined
  963.      *
  964.      * An option will be defined if an argument was assigned to it using
  965.      * the command line options. You can use the short, the long or
  966.      * an alias name as parameter.
  967.      *
  968.      * @access public
  969.      * @param  string the name of the option to be checked
  970.      * @return boolean true if the option is defined
  971.      */
  972.     function isDefined($optname)
  973.     {
  974.         $longname $this->getLongName($optname);
  975.         if (isset($this->_longLong[$longname])) {
  976.             return true;
  977.         }
  978.         return false;
  979.     }
  980.     
  981.     /**
  982.      * Returns the long version of the given parameter
  983.      *
  984.      * If the given name is not found, it will return the name that
  985.      * was given, without further ensuring that the option
  986.      * actually exists
  987.      *
  988.      * @access private
  989.      * @param  string the name of the option
  990.      * @return string long version of the option name
  991.      */
  992.     function getLongName($optname)
  993.     {
  994.         if (isset($this->_shortLong[$optname])) {
  995.             // Short version was passed.
  996.             $longname $this->_shortLong[$optname];
  997.         else if (isset($this->_aliasLong[$optname])) {
  998.             // An alias was passed.
  999.             $longname $this->_aliasLong[$optname];
  1000.         else {
  1001.             // No further validation is done.
  1002.             $longname $optname;
  1003.         }
  1004.         return $longname;
  1005.     }
  1006.     
  1007.     /**
  1008.      * Returns the argument of the given option
  1009.      *
  1010.      * You can use the short, alias or long version of the option name.
  1011.      * This method will try to find the argument(s) of the given option name.
  1012.      * If it is not found it will return null. If the arg has more than
  1013.      * one argument, an array of arguments will be returned.
  1014.      *
  1015.      * @access public
  1016.      * @param  string the name of the option
  1017.      * @return array|string|nullargument(s) associated with the option
  1018.      */
  1019.     function getValue($optname)
  1020.     {
  1021.         if ($this->isDefined($optname)) {
  1022.             // Option is defined. Return its value
  1023.             $longname $this->getLongName($optname);
  1024.             return $this->_longLong[$longname];
  1025.         }
  1026.         // Option is not defined.
  1027.         return null;
  1028.     }
  1029.  
  1030.     /**
  1031.      * Returns all arguments that have been parsed and recognized
  1032.      *
  1033.      * The name of the options are stored in the keys of the array.
  1034.      * You may choose whether you want to use the long or the short
  1035.      * option names
  1036.      *
  1037.      * @access public
  1038.      * @param  string   option names to use for the keys (long or short)
  1039.      * @return array    values for all options
  1040.      */
  1041.     function getValues($optionNames 'long')
  1042.     {
  1043.         switch ($optionNames{
  1044.             case 'short':
  1045.                 $values = array();
  1046.                 foreach ($this->_shortLong as $short => $long{
  1047.                     if (isset($this->_longLong[$long])) {
  1048.                         $values[$short$this->_longLong[$long];
  1049.                     }
  1050.                 }
  1051.                 if (isset($this->_longLong['parameters'])) {
  1052.                     $values['parameters'$this->_longLong['parameters'];
  1053.                 }
  1054.                 return $values;
  1055.             case 'long':
  1056.             default:
  1057.                 return $this->_longLong;
  1058.         }
  1059.     }
  1060. // end class Console_Getargs_Options
  1061. /*
  1062.  * Local variables:
  1063.  * tab-width: 4
  1064.  * c-basic-offset: 4
  1065.  * End:
  1066.  */
  1067. ?>

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