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

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