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

Source for file Option.php

Documentation is available at Option.php

  1. <?php
  2.  
  3. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  4.  
  5. /**
  6.  * This file is part of the PEAR Console_CommandLine package.
  7.  *
  8.  * PHP version 5
  9.  *
  10.  * LICENSE: This source file is subject to the MIT license that is available
  11.  * through the world-wide-web at the following URI:
  12.  * http://opensource.org/licenses/mit-license.php
  13.  *
  14.  * @category  Console
  15.  * @package   Console_CommandLine
  16.  * @author    David JEAN LOUIS <izimobil@gmail.com>
  17.  * @copyright 2007 David JEAN LOUIS
  18.  * @license   http://opensource.org/licenses/mit-license.php MIT License
  19.  * @version   CVS: $Id: Option.php 292158 2009-12-15 12:14:28Z rquadling $
  20.  * @link      http://pear.php.net/package/Console_CommandLine
  21.  * @since     File available since release 0.1.0
  22.  * @filesource
  23.  */
  24.  
  25. /**
  26.  * Required by this class.
  27.  */
  28. require_once 'Console/CommandLine.php';
  29. require_once 'Console/CommandLine/Element.php';
  30.  
  31. /**
  32.  * Class that represent a commandline option.
  33.  *
  34.  * @category  Console
  35.  * @package   Console_CommandLine
  36.  * @author    David JEAN LOUIS <izimobil@gmail.com>
  37.  * @copyright 2007 David JEAN LOUIS
  38.  * @license   http://opensource.org/licenses/mit-license.php MIT License
  39.  * @version   Release: 1.1.3
  40.  * @link      http://pear.php.net/package/Console_CommandLine
  41.  * @since     Class available since release 0.1.0
  42.  */
  43. {
  44.     // Public properties {{{
  45.  
  46.     /**
  47.      * The option short name (ex: -v).
  48.      *
  49.      * @var string $short_name Short name of the option
  50.      */
  51.     public $short_name;
  52.  
  53.     /**
  54.      * The option long name (ex: --verbose).
  55.      *
  56.      * @var string $long_name Long name of the option
  57.      */
  58.     public $long_name;
  59.  
  60.     /**
  61.      * The option action, defaults to "StoreString".
  62.      *
  63.      * @var string $action Option action
  64.      */
  65.     public $action = 'StoreString';
  66.  
  67.     /**
  68.      * The default value of the option if not provided on the command line.
  69.      *
  70.      * @var mixed $default Default value of the option.
  71.      */
  72.     public $default;
  73.  
  74.     /**
  75.      * An array of possible values for the option. If this array is not empty
  76.      * and the value passed is not in the array an exception is raised.
  77.      * This only make sense for actions that accept values of course.
  78.      *
  79.      * @var array $choices Valid choices for the option
  80.      */
  81.     public $choices = array();
  82.  
  83.     /**
  84.      * The callback function (or method) to call for an action of type
  85.      * Callback, this can be any callable supported by the php function
  86.      * call_user_func.
  87.      * 
  88.      * Example:
  89.      *
  90.      * <code>
  91.      * $parser->addOption('myoption', array(
  92.      *     'short_name' => '-m',
  93.      *     'long_name'  => '--myoption',
  94.      *     'action'     => 'Callback',
  95.      *     'callback'   => 'myCallbackFunction'
  96.      * ));
  97.      * </code>
  98.      *
  99.      * @var callable $callback The option callback
  100.      */
  101.     public $callback;
  102.  
  103.     /**
  104.      * An associative array of additional params to pass to the class
  105.      * corresponding to the action, this array will also be passed to the
  106.      * callback defined for an action of type Callback, Example:
  107.      *
  108.      * <code>
  109.      * // for a custom action
  110.      * $parser->addOption('myoption', array(
  111.      *     'short_name'    => '-m',
  112.      *     'long_name'     => '--myoption',
  113.      *     'action'        => 'MyCustomAction',
  114.      *     'action_params' => array('foo'=>true, 'bar'=>false)
  115.      * ));
  116.      *
  117.      * // if the user type:
  118.      * // $ <yourprogram> -m spam
  119.      * // in your MyCustomAction class the execute() method will be called
  120.      * // with the value 'spam' as first parameter and
  121.      * // array('foo'=>true, 'bar'=>false) as second parameter
  122.      * </code>
  123.      *
  124.      * @var array $action_params Additional parameters to pass to the action
  125.      */
  126.     public $action_params = array();
  127.  
  128.     /**
  129.      * For options that expect an argument, this property tells the parser if
  130.      * the option argument is optional and can be ommited.
  131.      *
  132.      * @var bool $argumentOptional Whether the option arg is optional or not
  133.      */
  134.     public $argument_optional = false;
  135.  
  136.     /**
  137.      * For options that uses the "choice" property only.
  138.      * Adds a --list-<choice> option to the parser that displays the list of
  139.      * choices for the option.
  140.      *
  141.      * @var bool $add_list_option Whether to add a list option or not
  142.      */
  143.     public $add_list_option = false;
  144.  
  145.     // }}}
  146.     // Private properties {{{
  147.  
  148.     /**
  149.      * When an action is called remember it to allow for multiple calls.
  150.      *
  151.      * @var object $action_instance Placeholder for action
  152.      */
  153.     private $_action_instance = null;
  154.  
  155.     // }}}
  156.     // __construct() {{{
  157.  
  158.     /**
  159.      * Constructor.
  160.      *
  161.      * @param string $name   The name of the option
  162.      * @param array  $params An optional array of parameters
  163.      *
  164.      * @return void 
  165.      */
  166.     public function __construct($name = null$params = array()) 
  167.     {
  168.         parent::__construct($name$params);
  169.         if ($this->action == 'Password'{
  170.             // special case for Password action, password can be passed to the 
  171.             // commandline or prompted by the parser
  172.             $this->argument_optional = true;
  173.         }
  174.     }
  175.  
  176.     // }}}
  177.     // toString() {{{
  178.  
  179.     /**
  180.      * Returns the string representation of the option.
  181.      *
  182.      * @param string $delim Delimiter to use between short and long option
  183.      *
  184.      * @return string The string representation of the option
  185.      * @todo use __toString() instead
  186.      */
  187.     public function toString($delim ", ")
  188.     {
  189.         $ret     '';
  190.         $padding '';
  191.         if ($this->short_name != null{
  192.             $ret .= $this->short_name;
  193.             if ($this->expectsArgument()) {
  194.                 $ret .= ' ' $this->help_name;
  195.             }
  196.             $padding $delim;
  197.         }
  198.         if ($this->long_name != null{
  199.             $ret .= $padding $this->long_name;
  200.             if ($this->expectsArgument()) {
  201.                 $ret .= '=' $this->help_name;
  202.             }
  203.         }
  204.         return $ret;
  205.     }
  206.  
  207.     // }}}
  208.     // expectsArgument() {{{
  209.  
  210.     /**
  211.      * Returns true if the option requires one or more argument and false
  212.      * otherwise.
  213.      *
  214.      * @return bool Whether the option expects an argument or not
  215.      */
  216.     public function expectsArgument()
  217.     {
  218.         if ($this->action == 'StoreTrue' || $this->action == 'StoreFalse' ||
  219.             $this->action == 'Help' || $this->action == 'Version' ||
  220.             $this->action == 'Counter' || $this->action == 'List'{
  221.             return false;
  222.         }
  223.         return true;
  224.     }
  225.  
  226.     // }}}
  227.     // dispatchAction() {{{
  228.  
  229.     /**
  230.      * Formats the value $value according to the action of the option and
  231.      * updates the passed Console_CommandLine_Result object.
  232.      *
  233.      * @param mixed                      $value  The value to format
  234.      * @param Console_CommandLine_Result $result The result instance
  235.      * @param Console_CommandLine        $parser The parser instance
  236.      *
  237.      * @return void 
  238.      * @throws Console_CommandLine_Exception
  239.      */
  240.     public function dispatchAction($value$result$parser)
  241.     {
  242.         $actionInfo Console_CommandLine::$actions[$this->action];
  243.         if (true === $actionInfo[1]{
  244.             // we have a "builtin" action
  245.             $tokens explode('_'$actionInfo[0]);
  246.             include_once implode('/'$tokens'.php';
  247.         }
  248.         $clsname $actionInfo[0];
  249.         if ($this->_action_instance === null{
  250.             $this->_action_instance  = new $clsname($result$this$parser);
  251.         }
  252.  
  253.         // check value is in option choices
  254.         if (!empty($this->choices&& !in_array($this->_action_instance->format($value)$this->choices)) {
  255.             throw Console_CommandLine_Exception::factory(
  256.                 'OPTION_VALUE_NOT_VALID',
  257.                 array(
  258.                     'name'    => $this->name,
  259.                     'choices' => implode('", "'$this->choices),
  260.                     'value'   => $value,
  261.                 ),
  262.                 $parser,
  263.                 $this->messages
  264.             );
  265.         }
  266.         $this->_action_instance->execute($value$this->action_params);
  267.     }
  268.  
  269.     // }}}
  270.     // validate() {{{
  271.  
  272.     /**
  273.      * Validates the option instance.
  274.      *
  275.      * @return void 
  276.      * @throws Console_CommandLine_Exception
  277.      * @todo use exceptions instead
  278.      */
  279.     public function validate()
  280.     {
  281.         // check if the option name is valid
  282.         if (!preg_match('/^[a-zA-Z_\x7f-\xff]+[a-zA-Z0-9_\x7f-\xff]*$/',
  283.             $this->name)) {
  284.             Console_CommandLine::triggerError('option_bad_name',
  285.                 E_USER_ERRORarray('{$name}' => $this->name));
  286.         }
  287.         // call the parent validate method
  288.         parent::validate();
  289.         // a short_name or a long_name must be provided
  290.         if ($this->short_name == null && $this->long_name == null{
  291.             Console_CommandLine::triggerError('option_long_and_short_name_missing',
  292.                 E_USER_ERRORarray('{$name}' => $this->name));
  293.         }
  294.         // check if the option short_name is valid
  295.         if ($this->short_name != null && 
  296.             !(preg_match('/^\-[a-zA-Z]{1}$/'$this->short_name))) {
  297.             Console_CommandLine::triggerError('option_bad_short_name',
  298.                 E_USER_ERRORarray(
  299.                     '{$name}' => $this->name
  300.                     '{$short_name}' => $this->short_name
  301.                 ));
  302.         }
  303.         // check if the option long_name is valid
  304.         if ($this->long_name != null && 
  305.             !preg_match('/^\-\-[a-zA-Z]+[a-zA-Z0-9_\-]*$/'$this->long_name)) {
  306.             Console_CommandLine::triggerError('option_bad_long_name',
  307.                 E_USER_ERRORarray(
  308.                     '{$name}' => $this->name
  309.                     '{$long_name}' => $this->long_name
  310.                 ));
  311.         }
  312.         // check if we have a valid action
  313.         if (!is_string($this->action)) {
  314.             Console_CommandLine::triggerError('option_bad_action',
  315.                 E_USER_ERRORarray('{$name}' => $this->name));
  316.         }
  317.         if (!isset(Console_CommandLine::$actions[$this->action])) {
  318.             Console_CommandLine::triggerError('option_unregistered_action',
  319.                 E_USER_ERRORarray(
  320.                     '{$action}' => $this->action,
  321.                     '{$name}' => $this->name
  322.                 ));
  323.         }
  324.         // if the action is a callback, check that we have a valid callback
  325.         if ($this->action == 'Callback' && !is_callable($this->callback)) {
  326.             Console_CommandLine::triggerError('option_invalid_callback',
  327.                 E_USER_ERRORarray('{$name}' => $this->name));
  328.         }
  329.     }
  330.  
  331.     // }}}
  332.     // setDefaults() {{{
  333.  
  334.     /**
  335.      * Set the default value according to the configured action.
  336.      *
  337.      * Note that for backward compatibility issues this method is only called
  338.      * when the 'force_options_defaults' is set to true, it will become the
  339.      * default behaviour in the next major release of Console_CommandLine.
  340.      *
  341.      * @return void 
  342.      */
  343.     public function setDefaults()
  344.     {
  345.         if ($this->default !== null{
  346.             // already set
  347.             return;
  348.         }
  349.         switch ($this->action{
  350.         case 'Counter':
  351.         case 'StoreInt':
  352.             $this->default = 0;
  353.             break;
  354.         case 'StoreFloat':
  355.             $this->default = 0.0;
  356.             break;
  357.         case 'StoreArray':
  358.             $this->default = array();
  359.             break;
  360.         case 'StoreTrue':
  361.             $this->default = false;
  362.             break;
  363.         case 'StoreFalse':
  364.             $this->default = true;
  365.             break;
  366.         default:
  367.             return;
  368.         }
  369.     }
  370.  
  371.     // }}}
  372. }

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