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.3 2004/09/29 00:36:01 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. /**
  54.  * Command-line arguments parsing class
  55.  * 
  56.  * This implementation was freely inspired by a python module called
  57.  * getargs by Vinod Vijayarajan and a perl CPAN module called
  58.  * Getopt::Simple by Ron Savage
  59.  *
  60.  * This class implements a Command Line Parser that your cli applications
  61.  * can use to parse command line arguments found in $_SERVER['argv'].
  62.  * It gives more flexibility and error checking than Console_Getopt. It also
  63.  * performs some arguments validation and is capable to return a formatted
  64.  * help text to the user, based on the configuration it is given.
  65.  * 
  66.  * The class provides the following capabilities:
  67.  * - Each command line option can take an arbitrary number of arguments.
  68.  * - Makes the distinction between switches (options without arguments)
  69.  *   and options that require arguments.
  70.  * - Recognizes 'single-argument-options' and 'default-if-set' options.
  71.  * - Switches and options with arguments can be interleaved in the command
  72.  *   line.
  73.  * - You can specify the maximum and minimum number of arguments an option
  74.  *   can take. Use -1 if you don't want to specify an upper bound.
  75.  * - Specify the default arguments to an option
  76.  * - Short options can be more than one letter in length.
  77.  * - A given option may be invoked by multiple names (aliases).
  78.  * - Understands by default the --help, -h options
  79.  * - Can return a formatted help text
  80.  * - Arguments may be specified using the '=' syntax also.
  81.  * 
  82.  * @todo Implement the parsing of comma delimited arguments
  83.  * @author Bertrand Mansion <bmansion@mamasam.com>
  84.  * @copyright 2004
  85.  * @license http://www.php.net/license/3_0.txt PHP License 3.0
  86.  * @version @VER@
  87.  * @package  Console_Getargs
  88.  */
  89. {
  90.     /**
  91.      * Factory creates a new {@link Console_Getargs_Options} object
  92.      *
  93.      * This method will return a new {@link Console_Getargs_Options}
  94.      * built using the given configuration options. If the configuration
  95.      * or the command line options contain errors, the returned object will
  96.      * in fact be a PEAR_Error explaining the cause of the error.
  97.      *
  98.      * Factory expects an array as parameter.
  99.      * The format for this array is:
  100.      * <pre>
  101.      * array(
  102.      *  longname => array('short'   => Short option name,
  103.      *                    'max'     => Maximum arguments for option,
  104.      *                    'min'     => Minimum arguments for option,
  105.      *                    'default' => Default option argument,
  106.      *                    'desc'    => Option description)
  107.      * )
  108.      * </pre>
  109.      * 
  110.      * If an option can be invoked by more than one name, they have to be defined
  111.      * by using | as a separator. For example: name1|name2
  112.      * This works both in long and short names.
  113.      *
  114.      * max/min are the most/least number of arguments an option accepts.
  115.      *
  116.      * The 'defaults' field is optional and is used to specify default
  117.      * arguments to an option. These will be assigned to the option if
  118.      * it is *not* used in the command line.
  119.      * Default arguments can be:
  120.      * - a single value for options that require a single argument,
  121.      * - an array of values for options with more than one possible arguments.
  122.      * Default argument(s) are mandatory for 'default-if-set' options.
  123.      *
  124.      * If max is 0 (option is just a switch), min is ignored.
  125.      * If max is -1, then the option can have an unlimited number of arguments
  126.      * greater or equal to min.
  127.      * 
  128.      * If max == min == 1, the option is treated as a single argument option.
  129.      * 
  130.      * If max >= 1 and min == 0, the option is treated as a
  131.      * 'default-if-set' option. This implies that it will get the default argument
  132.      * only if the option is used in the command line without any value.
  133.      * (Note: defaults *must* be specified for 'default-if-set' options)
  134.      *
  135.      * If the option is not in the command line, the defaults are
  136.      * *not* applied. If an argument for the option is specified on the command
  137.      * line, then the given argument is assigned to the option.
  138.      * Thus:
  139.      * - a --debug in the command line would cause debug = 'default argument'
  140.      * - a --debug 2 in the command line would result in debug = 2
  141.      *  if not used in the command line, debug will not be defined.
  142.      * 
  143.      * Example 1.
  144.      * <code>
  145.      * require_once 'Console_Getargs.php';
  146.      *
  147.      * $args =& Console_Getargs::factory($config);
  148.      * 
  149.      * if (PEAR::isError($args)) {
  150.      *  if ($args->getCode() === CONSOLE_GETARGS_ERROR_USER) {
  151.      *    echo Console_Getargs::getHelp($config, null, $args->getMessage())."\n";
  152.      *  } else if ($args->getCode() === CONSOLE_GETARGS_HELP) {
  153.      *    echo Console_Getargs::getHelp($config)."\n";
  154.      *  }
  155.      *  exit;
  156.      * }
  157.      * 
  158.      * echo 'Verbose: '.$args->getValue('verbose')."\n";
  159.      * if ($args->isDefined('bs')) {
  160.      *  echo 'Block-size: '.(is_array($args->getValue('bs')) ? implode(', ', $args->getValue('bs'))."\n" : $args->getValue('bs')."\n");
  161.      * } else {
  162.      *  echo "Block-size: undefined\n";
  163.      * }
  164.      * echo 'Files: '.($args->isDefined('file') ? implode(', ', $args->getValue('file'))."\n" : "undefined\n");
  165.      * if ($args->isDefined('n')) {
  166.      *  echo 'Nodes: '.(is_array($args->getValue('n')) ? implode(', ', $args->getValue('n'))."\n" : $args->getValue('n')."\n");
  167.      * } else {
  168.      *  echo "Nodes: undefined\n";
  169.      * }
  170.      * echo 'Log: '.$args->getValue('log')."\n";
  171.      * echo 'Debug: '.($args->isDefined('d') ? "YES\n" : "NO\n");
  172.      * 
  173.      * </code>
  174.      * 
  175.      * @param array associative array with keys being the options long name
  176.      * @access public
  177.      * @return object|PEAR_Error a newly created Console_Getargs_Options object
  178.      *                             or a PEAR_Error object on error
  179.      */
  180.     function &factory($config = array())
  181.     {
  182.         // Create the options object.
  183.         $obj =new Console_Getargs_Options();
  184.  
  185.         // Try to set up the arguments.
  186.         $err $obj->init($config);
  187.         if ($err !== true{
  188.             return $err;
  189.         }
  190.  
  191.         // Try to set up the options.
  192.         $err $obj->buildMaps();
  193.         if ($err !== true{
  194.             return $err;
  195.         }
  196.  
  197.         // Get the options and arguments from the command line.
  198.         $err $obj->parseArgs();
  199.         if ($err !== true{
  200.             return $err;
  201.         }
  202.  
  203.         // Set arguments for options that have defaults.
  204.         $err $obj->setDefaults();
  205.         if ($err !== true{
  206.             return $err;
  207.         }
  208.  
  209.         // All is good.
  210.         return $obj;
  211.     }
  212.  
  213.     /**
  214.      * Returns an ascii art version of the help
  215.      *
  216.      * This method uses the given configuration and parameters
  217.      * to create and format an help text for the options you defined
  218.      * in your config parameter. You can supply a header and a footer
  219.      * as well as the maximum length of a line. If you supplied
  220.      * descriptions for your options, they will be used as well.
  221.      *
  222.      * By default, it returns something like this:
  223.      * <pre>
  224.      * Usage: myscript.php [options]
  225.      * 
  226.      * -f --files values(2)          Set the source and destination image files.
  227.      * -w --width=&lt;value&gt;            Set the new width of the image.
  228.      * -d --debug                    Switch to debug mode.
  229.      * --formats values(1-3)         Set the image destination format. (jpegbig,
  230.      *                               jpegsmall)
  231.      * -fi --filters values(1-...)   Set the filters to be applied to the image upon
  232.      *                               conversion. The filters will be used in the order
  233.      *                               they are set.
  234.      * -v --verbose (optional)value  Set the verbose level. (3)
  235.      * </pre>
  236.      *
  237.      * @access public
  238.      * @param  array  your args configuration
  239.      * @param  string the header for the help. If it is left null,
  240.      *                 a default header will be used, starting by Usage:
  241.      * @param  string the footer for the help. This could be used
  242.      *                 to supply a description of the error the user made
  243.      * @param  int    help lines max length
  244.      * @return string the formatted help text
  245.      */
  246.     function getHelp($config$helpHeader = null$helpFooter ''$maxlength = 78)
  247.     {
  248.         $help '';
  249.         if (!isset($helpHeader)) {
  250.             $helpHeader 'Usage: '.basename($_SERVER['SCRIPT_NAME'])." [options]\n\n";
  251.         }
  252.         $i = 0;
  253.         foreach ($config as $long => $def{
  254.             
  255.             $shortArr = array();
  256.             if (isset($def['short'])) {
  257.                 $shortArr explode('|'$def['short']);
  258.             }
  259.             $longArr explode('|'$long);
  260.  
  261.             // Column one is the option name displayed as "-short, --long [additional info]"
  262.             $col1[$i!empty($shortArr'-'.$shortArr[0].' ' '';
  263.             $col1[$i.= '--'.$longArr[0];
  264.             $max $def['max'];
  265.             $min = isset($def['min']$def['min'$max;
  266.  
  267.             if ($max === 1 && $min === 1{
  268.                 $col1[$i.= '=<value>';
  269.             else if ($max > 1{
  270.                 if ($min === $max{
  271.                     $col1[$i.= ' values('.$max.')';
  272.                 else if ($min === 0{
  273.                     $col1[$i.= ' values(optional)';
  274.                 else {
  275.                     $col1[$i.= ' values('.$min.'-'.$max.')';
  276.                 }
  277.             else if ($max === 1 && $min === 0{
  278.                 $col1[$i.= ' (optional)value';
  279.             else if ($max === -1{
  280.                 if ($min > 0{
  281.                     $col1[$i.= ' values('.$min.'-...)';
  282.                 else {
  283.                     $col1[$i.= ' (optional)values';
  284.                 }
  285.             }
  286.  
  287.             // Column two is the description if available.
  288.             if (isset($def['desc'])) {
  289.                 $col2[$i$def['desc'];
  290.             else {
  291.                 $col2[$i'';
  292.             }
  293.             // Add the default value(s) if there are any/
  294.             if (isset($def['default'])) {
  295.                 if (is_array($def['default'])) {
  296.                     $col2[$i.= ' ('.implode(', '$def['default']).')';
  297.                 else {
  298.                     $col2[$i.= ' ('.$def['default'].')';
  299.                 }
  300.             }
  301.             $i++;
  302.         }
  303.         
  304.         // Figure out the maximum length for column one.
  305.         $arglen = 0;
  306.         foreach ($col1 as $txt{
  307.             $length strlen($txt);
  308.             if ($length $arglen{
  309.                 $arglen $length;
  310.             }
  311.         }
  312.  
  313.         // The maximum length for each description line.
  314.         $desclen $maxlength $arglen;
  315.         $padding str_repeat(' '$arglen);
  316.         foreach ($col1 as $k => $txt{
  317.             // Wrap the descriptions.
  318.             if (strlen($col2[$k]$desclen{
  319.                 $desc wordwrap($col2[$k]$desclen"\n  ".$padding);
  320.             else {
  321.                 $desc $col2[$k];
  322.             }
  323.             // Push everything together.
  324.             $help .= str_pad($txt$arglen).'  '.$desc."\n";
  325.         }
  326.         return $helpHeader.$help.$helpFooter;
  327.     }
  328. // end class Console_Getargs
  329.  
  330. /**
  331.  * This class implements a wrapper to the command line options and arguments.
  332.  *
  333.  * @author Bertrand Mansion <bmansion@mamasam.com>
  334.  * @package  Console_Getargs
  335.  */
  336. {
  337.  
  338.     /**
  339.      * Lookup to match short options name with long ones
  340.      * @var array 
  341.      * @access private
  342.      */
  343.     var $_shortLong = array();
  344.  
  345.     /**
  346.      * Lookup to match alias options name with long ones
  347.      * @var array 
  348.      * @access private
  349.      */
  350.     var $_aliasLong = array();
  351.  
  352.     /**
  353.      * Arguments set for the options
  354.      * @var array 
  355.      * @access private
  356.      */
  357.     var $_longLong = array();
  358.  
  359.     /**
  360.      * Configuration set at initialization time
  361.      * @var array 
  362.      * @access private
  363.      */
  364.     var $_config = array();
  365.  
  366.     /**
  367.      * A read/write copy of argv
  368.      * @var array 
  369.      * @access private
  370.      */
  371.     var $args = array();
  372.  
  373.     /**
  374.      * Initializes the Console_Getargs_Options object
  375.      * @param array configuration options
  376.      * @access private
  377.      * @throws CONSOLE_GETARGS_ERROR_CONFIG
  378.      * @return true|PEAR_Error
  379.      */
  380.     function init($config)
  381.     {
  382.         // Command line arguments must be available.
  383.         if (!isset($_SERVER['argv']|| !is_array($_SERVER['argv'])) {
  384.             return PEAR::raiseError("Could not read argv"CONSOLE_GETARGS_ERROR_CONFIG,
  385.                                     PEAR_ERROR_TRIGGERE_USER_WARNING'Console_Getargs_Options::init()');
  386.         }
  387.         $this->args $_SERVER['argv'];
  388.  
  389.         // Drop the first argument if it doesn't begin with a '-'.
  390.         if (isset($this->args[0]{0}&& $this->args[0]{0!= '-'{
  391.             array_shift($this->args);
  392.         }
  393.         $this->_config $config;
  394.         return true;
  395.     }
  396.  
  397.     /**
  398.      * Makes the lookup arrays for alias and short name mapping with long names
  399.      * @access private
  400.      * @throws CONSOLE_GETARGS_ERROR_CONFIG
  401.      * @return true|PEAR_Error
  402.      */
  403.     function buildMaps()
  404.     {
  405.         foreach($this->_config as $long => $def{
  406.  
  407.             $longArr explode('|'$long);
  408.             $longname $longArr[0];
  409.  
  410.             if (count($longArr> 1{
  411.                 // The fisrt item in the list is "the option".
  412.                 // The rest are aliases.
  413.                 array_shift($longArr);
  414.                 foreach($longArr as $alias{
  415.                     // Watch out for duplicate aliases.
  416.                     if (isset($this->_aliasLong[$alias])) {
  417.                         return PEAR::raiseError('Duplicate alias for long option '.$aliasCONSOLE_GETARGS_ERROR_CONFIG,
  418.                                     PEAR_ERROR_TRIGGERE_USER_WARNING'Console_Getargs_Options::buildMaps()');
  419.  
  420.                     }
  421.                     $this->_aliasLong[$alias$longname;
  422.                 }
  423.                 // Add the real option name and defintion.
  424.                 $this->_config[$longname$def;
  425.                 // Get rid of the old version (name|alias1|...)
  426.                 unset($this->_config[$long]);
  427.             }
  428.  
  429.             // Add the (optional) short option names.
  430.             if (!empty($def['short'])) {
  431.                 // Short names
  432.                 $shortArr explode('|'$def['short']);
  433.                 $short $shortArr[0];
  434.                 if (count($shortArr> 1{
  435.                     // The first item is "the option".
  436.                     // The rest are aliases.
  437.                     array_shift($shortArr);
  438.                     foreach ($shortArr as $alias{
  439.                         // Watch out for duplicate aliases.
  440.                         if (isset($this->_shortLong[$alias])) {
  441.                             return PEAR::raiseError('Duplicate alias for short option '.$aliasCONSOLE_GETARGS_ERROR_CONFIG,
  442.                                     PEAR_ERROR_TRIGGERE_USER_WARNING'Console_Getargs_Options::buildMaps()');
  443.                         }
  444.                         $this->_shortLong[$alias$longname;
  445.                     }
  446.                 }
  447.                 // Add the real short option name.
  448.                 $this->_shortLong[$short$longname;
  449.             }
  450.         }
  451.         return true;
  452.     }
  453.  
  454.     /**
  455.      * Parses the given options/arguments one by one
  456.      * @access private
  457.      * @throws CONSOLE_GETARGS_HELP
  458.      * @throws CONSOLE_GETARGS_ERROR_USER
  459.      * @return true|PEAR_Error
  460.      */
  461.     function parseArgs()
  462.     {
  463.         // Go through the options and parse the arguments for each.
  464.         for ($i = 0$count count($this->args)$i $count$i++{
  465.  
  466.             $arg $this->args[$i];
  467.  
  468.             if ($arg === '--'{
  469.                 // '--' alone breaks the loop
  470.                 break;
  471.             }
  472.             if ($arg === '--help' || $arg === '-h'{
  473.                 // Asking for help breaks the loop.
  474.                 return PEAR::raiseError(nullCONSOLE_GETARGS_HELPPEAR_ERROR_RETURN);
  475.             }
  476.             if (strlen($arg> 1 && $arg{1== '-'{
  477.                 // Long name used (--option)
  478.                 $err $this->parseArg(substr($arg2)true$i);
  479.             else if (strlen($arg> 1 && $arg{0== '-'{
  480.                 // Short name used (-o)
  481.                 $err $this->parseArg(substr($arg1)false$i);
  482.                 if ($err === -1{
  483.                     break;
  484.                 }
  485.             else {
  486.                 $err = PEAR::raiseError('Unknown argument '.$arg,
  487.                                      CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  488.                                      null'Console_Getargs_Options::parseArgs()');
  489.             }
  490.             if ($err !== true{
  491.                 return $err;
  492.             }
  493.         }
  494.         // Check to see if we need to reload the arguments
  495.         // due to concatenated short names.
  496.         if ($err === -1{
  497.             return $this->parseArgs();
  498.         }
  499.  
  500.         return true;
  501.     }
  502.  
  503.     /**
  504.      * Parses one option/argument
  505.      * @access private
  506.      * @throws CONSOLE_GETARGS_ERROR_USER
  507.      * @return true|PEAR_Error
  508.      */
  509.     function parseArg($arg$isLong&$pos)
  510.     {
  511.         // If the whole short option isn't in the shortLong array
  512.         // then break it into a bunch of switches.
  513.         if (!$isLong && !isset($this->_shortLong[$arg]&& strlen($arg> 1{
  514.             $newArgs = array();
  515.             for ($i = 0; $i strlen($arg)$i++{
  516.                 $newArgs['-' $arg{$i};
  517.             }
  518.             // Add the new args to the array.
  519.             array_splice($this->args$pos1$newArgs);
  520.  
  521.             // Reset the option values.
  522.             $this->_longLong = array();
  523.  
  524.             // Then reparse the arguments.
  525.             return -1;
  526.         }
  527.  
  528.         $opt '';
  529.         for ($i = 0; $i strlen($arg)$i++{
  530.             // Build the option name one char at a time looking for a match.
  531.             $opt .= $arg{$i};
  532.             if ($isLong === false && isset($this->_shortLong[$opt])) {
  533.                 // Found a match in the short option names.
  534.                 $cmp $opt;
  535.                 $long $this->_shortLong[$opt];
  536.             else if ($isLong === true && isset($this->_config[$opt])) {
  537.                 // Found a match in the long option names.
  538.                 $long $cmp $opt;
  539.             }
  540.             if ($arg{$i=== '='{
  541.                 // End of the option name when '=' is found.
  542.                 break;
  543.             }
  544.         }
  545.  
  546.         if (isset($long)) {
  547.             // A match was found.
  548.             if (strlen($argstrlen($cmp)) {
  549.                 // Seperate the argument from the option.
  550.                 // Ex: php test.php -f=image.png
  551.                 //     $cmp = 'f'
  552.                 //     $arg = 'f=image.png'
  553.                 $arg substr($argstrlen($cmp));
  554.                 // Now $arg = '=image.png'
  555.                 if ($arg{0=== '='{
  556.                     $arg substr($arg1);
  557.                     // Now $arg = 'image.png'
  558.                 }
  559.             else {
  560.                 // No argument passed for option.
  561.                 $arg '';
  562.             }
  563.             // Set the options value.
  564.             return $this->setValue($long$arg$pos);
  565.         }
  566.         return PEAR::raiseError('Unknown argument '.$opt,
  567.                                 CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  568.                                 null'Console_Getargs_Options::parseArg()');
  569.     }
  570.  
  571.     /**
  572.      * Set the option arguments
  573.      * @access private
  574.      * @throws CONSOLE_GETARGS_ERROR_CONFIG
  575.      * @throws CONSOLE_GETARGS_ERROR_USER
  576.      * @return true|PEAR_Error
  577.      */
  578.     function setValue($optname$value&$pos)
  579.     {
  580.         if (!isset($this->_config[$optname]['max'])) {
  581.             // Max must be set for every option even if it is zero or -1.
  582.             return PEAR::raiseError('No max parameter set for '.$optname,
  583.                                      CONSOLE_GETARGS_ERROR_CONFIGPEAR_ERROR_TRIGGER,
  584.                                      E_USER_WARNING'Console_Getargs_Options::setValue()');
  585.         }
  586.  
  587.         $max $this->_config[$optname]['max'];
  588.         $min = isset($this->_config[$optname]['min']$this->_config[$optname]['min']$max;
  589.  
  590.         // A value was passed after the option.
  591.         if ($value !== ''{
  592.             // Argument is like -v 5
  593.             if ($min == 1 && $max > 0{
  594.                 // At least one argument is required for option.
  595.                 $this->updateValue($optname$value);
  596.                 return true;
  597.             }
  598.             if ($max === 0{
  599.                 // Argument passed but not expected.
  600.                 return PEAR::raiseError('Argument '.$optname.' does not take any value',
  601.                                      CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  602.                                      null'Console_Getargs_Options::setValue()');
  603.             }
  604.             // Not enough arguments passed for this option.
  605.             return PEAR::raiseError('Argument '.$optname.' expects more than one value',
  606.                                      CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  607.                                      null'Console_Getargs_Options::setValue()');
  608.         }
  609.  
  610.         if ($min === 1 && $max === 1{
  611.             // Argument requires 1 value
  612.             if (isset($this->args[$pos+1]&& $this->isValue($this->args[$pos+1])) {
  613.                 // Set the option value and increment the position.
  614.                 $this->updateValue($optname$this->args[$pos+1]);
  615.                 $pos++;
  616.                 return true;
  617.             }
  618.             // What we thought was the argument was really the next option.
  619.             return PEAR::raiseError('Argument '.$optname.' expects one value',
  620.                              CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  621.                              null'Console_Getargs_Options::setValue()');
  622.  
  623.         else if ($max === 0{
  624.             // Argument is a switch
  625.             if (isset($this->args[$pos+1]&& $this->isValue($this->args[$pos+1])) {
  626.                 // What we thought was the next option was really an argument for this option.
  627.                 return PEAR::raiseError('Argument '.$optname.' does not take any value',
  628.                                  CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  629.                                  null'Console_Getargs_Options::setValue()');
  630.             }
  631.             // Set the switch to on.
  632.             $this->updateValue($optnametrue);
  633.             return true;
  634.  
  635.         else if ($max >= 1 && $min === 0{
  636.             // Argument has a default-if-set value
  637.             if (!isset($this->_config[$optname]['default'])) {
  638.                 // A default value MUST be assigned when config is loaded.
  639.                 return PEAR::raiseError('No default value defined for '.$optname,
  640.                                  CONSOLE_GETARGS_ERROR_CONFIGPEAR_ERROR_TRIGGER,
  641.                                  E_USER_WARNING'Console_Getargs_Options::setValue()');
  642.             }
  643.             if (is_array($this->_config[$optname]['default'])) {
  644.                 // Default value cannot be an array.
  645.                 return PEAR::raiseError('Default value for '.$optname.' must be scalar',
  646.                                  CONSOLE_GETARGS_ERROR_CONFIGPEAR_ERROR_TRIGGER,
  647.                                  E_USER_WARNING'Console_Getargs_Options::setValue()');
  648.             }
  649.             if (isset($this->args[$pos+1]&& $this->isValue($this->args[$pos+1])) {
  650.                 // Assign the option the value from the command line if there is one.
  651.                 $this->updateValue($optname$this->args[$pos+1]);
  652.                 $pos++;
  653.                 return true;
  654.             }
  655.             // Otherwise use the default value.
  656.             $this->updateValue($optname$this->_config[$optname]['default']);
  657.             return true;
  658.         }
  659.  
  660.         // Argument takes one or more values
  661.         $added = 0;
  662.         for ($i $pos + 1; $i <= count($this->args)$i++{
  663.             if (isset($this->args[$i]&& $this->isValue($this->args[$i])) {
  664.                 // Add the argument value until the next option is hit.
  665.                 $this->updateValue($optname$this->args[$i]);
  666.                 $added++;
  667.                 $pos++;
  668.                 continue;
  669.             }
  670.             if ($min $added{
  671.                 // There aren't enough arguments for this option.
  672.                 return PEAR::raiseError('Argument '.$optname.' expects at least '.$min.(($min > 1' values' ' value'),
  673.                          CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  674.                          null'Console_Getargs_Options::setValue()');
  675.             else if ($max !== -1 && $added $max{
  676.                 // Too many arguments for this option.
  677.                 return PEAR::raiseError('Argument '.$optname.' expects maximum '.$max.' values',
  678.                          CONSOLE_GETARGS_ERROR_USERPEAR_ERROR_RETURN,
  679.                          null'Console_Getargs_Options::setValue()');
  680.             }
  681.             break;
  682.         }
  683.         // Everything went well.
  684.         return true;
  685.     }
  686.  
  687.     /**
  688.      * Checks whether the given parameter is an argument or an option
  689.      * @access private
  690.      * @return boolean 
  691.      */
  692.     function isValue($arg)
  693.     {
  694.         if (strlen($arg> 1 && $arg{1== '-' ||
  695.             strlen($arg> 1 && $arg{0== '-'{
  696.             // The next argument is really an option.
  697.             return false;
  698.         }
  699.         return true;
  700.     }
  701.  
  702.     /**
  703.      * Adds the argument to the option
  704.      *
  705.      * If the argument for the option is already set,
  706.      * the option arguments will be changed to an array
  707.      * @access private
  708.      * @return void 
  709.      */
  710.     function updateValue($optname$value)
  711.     {
  712.         if (isset($this->_longLong[$optname])) {
  713.             if (is_array($this->_longLong[$optname])) {
  714.                 // Add this value to the list of values for this option.
  715.                 $this->_longLong[$optname][$value;
  716.             else {
  717.                 // There is already one value set. Turn everything into a list of values.
  718.                 $prevValue $this->_longLong[$optname];
  719.                 $this->_longLong[$optname= array($prevValue);
  720.                 $this->_longLong[$optname][$value;
  721.             }
  722.         else {
  723.             // This is the first value for this option.
  724.             $this->_longLong[$optname$value;
  725.         }
  726.     }
  727.  
  728.     /**
  729.      * Sets the option default arguments when necessary
  730.      * @access private
  731.      * @return true 
  732.      */
  733.     function setDefaults()
  734.     {
  735.         foreach ($this->_config as $longname => $def{
  736.             // Add the default value only if the default is defined 
  737.             // and the option requires at least one argument.
  738.             if (isset($def['default']&& $def['min'!== 0 && !isset($this->_longLong[$longname])) {
  739.                 $this->_longLong[$longname$def['default'];
  740.             }
  741.         }
  742.         return true;
  743.     }
  744.  
  745.     /**
  746.      * Checks whether the given option is defined
  747.      *
  748.      * An option will be defined if an argument was assigned to it using
  749.      * the command line options. You can use the short, the long or
  750.      * an alias name as parameter.
  751.      *
  752.      * @access public
  753.      * @param  string the name of the option to be checked
  754.      * @return boolean true if the option is defined
  755.      */
  756.     function isDefined($optname)
  757.     {
  758.         $longname $this->getLongName($optname);
  759.         if (isset($this->_longLong[$longname])) {
  760.             return true;
  761.         }
  762.         return false;
  763.     }
  764.  
  765.     /**
  766.      * Returns the long version of the given parameter
  767.      *
  768.      * If the given name is not found, it will return the name that
  769.      * was given, without further ensuring that the option
  770.      * actually exists
  771.      *
  772.      * @access private
  773.      * @param  string the name of the option
  774.      * @return string long version of the option name
  775.      */
  776.     function getLongName($optname)
  777.     {
  778.         if (isset($this->_shortLong[$optname])) {
  779.             // Short version was passed.
  780.             $longname $this->_shortLong[$optname];
  781.         else if (isset($this->_aliasLong[$optname])) {
  782.             // An alias was passed.
  783.             $longname $this->_aliasLong[$optname];
  784.         else {
  785.             // No further validation is done.
  786.             $longname $optname;
  787.         }
  788.         return $longname;
  789.     }
  790.  
  791.     /**
  792.      * Returns the argument of the given option
  793.      *
  794.      * You can use the short, alias or long version of the option name.
  795.      * This method will try to find the argument(s) of the given option name.
  796.      * If it is not found it will return null. If the arg has more than
  797.      * one argument, an array of arguments will be returned.
  798.      *
  799.      * @access public
  800.      * @param  string the name of the option
  801.      * @return array|string|nullargument(s) associated with the option
  802.      */
  803.     function getValue($optname)
  804.     {
  805.         if ($this->isDefined($optname)) {
  806.             // Option is defined. Return its value
  807.             $longname $this->getLongName($optname);
  808.             return $this->_longLong[$longname];
  809.         }
  810.         // Option is not defined.
  811.         return null;
  812.     }
  813. // end class Console_Getargs_Options
  814. ?>

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