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,v 1.4 2009/06/19 10:22:48 izi Exp $
  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.0
  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.         // check value is in option choices
  243.         if (!empty($this->choices&& !in_array($value$this->choices)) {
  244.             throw Console_CommandLine_Exception::factory(
  245.                 'OPTION_VALUE_NOT_VALID',
  246.                 array(
  247.                     'name'    => $this->name,
  248.                     'choices' => implode('", "'$this->choices),
  249.                     'value'   => $value,
  250.                 ),
  251.                 $parser,
  252.                 $this->messages
  253.             );
  254.         }
  255.         $actionInfo Console_CommandLine::$actions[$this->action];
  256.         if (true === $actionInfo[1]{
  257.             // we have a "builtin" action
  258.             $tokens explode('_'$actionInfo[0]);
  259.             include_once implode('/'$tokens'.php';
  260.         }
  261.         $clsname $actionInfo[0];
  262.         if ($this->_action_instance === null{
  263.             $this->_action_instance  = new $clsname($result$this$parser);
  264.         }
  265.         $this->_action_instance->execute($value$this->action_params);
  266.     }
  267.  
  268.     // }}}
  269.     // validate() {{{
  270.  
  271.     /**
  272.      * Validates the option instance.
  273.      *
  274.      * @return void 
  275.      * @throws Console_CommandLine_Exception
  276.      * @todo use exceptions instead
  277.      */
  278.     public function validate()
  279.     {
  280.         // check if the option name is valid
  281.         if (!preg_match('/^[a-zA-Z_\x7f-\xff]+[a-zA-Z0-9_\x7f-\xff]*$/',
  282.             $this->name)) {
  283.             Console_CommandLine::triggerError('option_bad_name',
  284.                 E_USER_ERRORarray('{$name}' => $this->name));
  285.         }
  286.         // call the parent validate method
  287.         parent::validate();
  288.         // a short_name or a long_name must be provided
  289.         if ($this->short_name == null && $this->long_name == null{
  290.             Console_CommandLine::triggerError('option_long_and_short_name_missing',
  291.                 E_USER_ERRORarray('{$name}' => $this->name));
  292.         }
  293.         // check if the option short_name is valid
  294.         if ($this->short_name != null && 
  295.             !(preg_match('/^\-[a-zA-Z]{1}$/'$this->short_name))) {
  296.             Console_CommandLine::triggerError('option_bad_short_name',
  297.                 E_USER_ERRORarray(
  298.                     '{$name}' => $this->name
  299.                     '{$short_name}' => $this->short_name
  300.                 ));
  301.         }
  302.         // check if the option long_name is valid
  303.         if ($this->long_name != null && 
  304.             !preg_match('/^\-\-[a-zA-Z]+[a-zA-Z0-9_\-]*$/'$this->long_name)) {
  305.             Console_CommandLine::triggerError('option_bad_long_name',
  306.                 E_USER_ERRORarray(
  307.                     '{$name}' => $this->name
  308.                     '{$long_name}' => $this->long_name
  309.                 ));
  310.         }
  311.         // check if we have a valid action
  312.         if (!is_string($this->action)) {
  313.             Console_CommandLine::triggerError('option_bad_action',
  314.                 E_USER_ERRORarray('{$name}' => $this->name));
  315.         }
  316.         if (!isset(Console_CommandLine::$actions[$this->action])) {
  317.             Console_CommandLine::triggerError('option_unregistered_action',
  318.                 E_USER_ERRORarray(
  319.                     '{$action}' => $this->action,
  320.                     '{$name}' => $this->name
  321.                 ));
  322.         }
  323.         // if the action is a callback, check that we have a valid callback
  324.         if ($this->action == 'Callback' && !is_callable($this->callback)) {
  325.             Console_CommandLine::triggerError('option_invalid_callback',
  326.                 E_USER_ERRORarray('{$name}' => $this->name));
  327.         }
  328.     }
  329.  
  330.     // }}}
  331.     // setDefaults() {{{
  332.  
  333.     /**
  334.      * Set the default value according to the configured action.
  335.      *
  336.      * Note that for backward compatibility issues this method is only called
  337.      * when the 'force_options_defaults' is set to true, it will become the
  338.      * default behaviour in the next major release of Console_CommandLine.
  339.      *
  340.      * @return void 
  341.      */
  342.     public function setDefaults()
  343.     {
  344.         if ($this->default !== null{
  345.             // already set
  346.             return;
  347.         }
  348.         switch ($this->action{
  349.         case 'Counter':
  350.         case 'StoreInt':
  351.             $this->default = 0;
  352.             break;
  353.         case 'StoreFloat':
  354.             $this->default = 0.0;
  355.             break;
  356.         case 'StoreArray':
  357.             $this->default = array();
  358.             break;
  359.         case 'StoreTrue':
  360.             $this->default = false;
  361.             break;
  362.         case 'StoreFalse':
  363.             $this->default = true;
  364.             break;
  365.         default:
  366.             return;
  367.         }
  368.     }
  369.  
  370.     // }}}
  371. }

Documentation generated on Fri, 19 Jun 2009 12:00:07 +0000 by phpDocumentor 1.4.2. PEAR Logo Copyright © PHP Group 2004.