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$
  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.2.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.      * An array of possible values for the option. If this array is not empty
  69.      * and the value passed is not in the array an exception is raised.
  70.      * This only make sense for actions that accept values of course.
  71.      *
  72.      * @var array $choices Valid choices for the option
  73.      */
  74.     public $choices = array();
  75.  
  76.     /**
  77.      * The callback function (or method) to call for an action of type
  78.      * Callback, this can be any callable supported by the php function
  79.      * call_user_func.
  80.      * 
  81.      * Example:
  82.      *
  83.      * <code>
  84.      * $parser->addOption('myoption', array(
  85.      *     'short_name' => '-m',
  86.      *     'long_name'  => '--myoption',
  87.      *     'action'     => 'Callback',
  88.      *     'callback'   => 'myCallbackFunction'
  89.      * ));
  90.      * </code>
  91.      *
  92.      * @var callable $callback The option callback
  93.      */
  94.     public $callback;
  95.  
  96.     /**
  97.      * An associative array of additional params to pass to the class
  98.      * corresponding to the action, this array will also be passed to the
  99.      * callback defined for an action of type Callback, Example:
  100.      *
  101.      * <code>
  102.      * // for a custom action
  103.      * $parser->addOption('myoption', array(
  104.      *     'short_name'    => '-m',
  105.      *     'long_name'     => '--myoption',
  106.      *     'action'        => 'MyCustomAction',
  107.      *     'action_params' => array('foo'=>true, 'bar'=>false)
  108.      * ));
  109.      *
  110.      * // if the user type:
  111.      * // $ <yourprogram> -m spam
  112.      * // in your MyCustomAction class the execute() method will be called
  113.      * // with the value 'spam' as first parameter and
  114.      * // array('foo'=>true, 'bar'=>false) as second parameter
  115.      * </code>
  116.      *
  117.      * @var array $action_params Additional parameters to pass to the action
  118.      */
  119.     public $action_params = array();
  120.  
  121.     /**
  122.      * For options that expect an argument, this property tells the parser if
  123.      * the option argument is optional and can be ommited.
  124.      *
  125.      * @var bool $argumentOptional Whether the option arg is optional or not
  126.      */
  127.     public $argument_optional = false;
  128.  
  129.     /**
  130.      * For options that uses the "choice" property only.
  131.      * Adds a --list-<choice> option to the parser that displays the list of
  132.      * choices for the option.
  133.      *
  134.      * @var bool $add_list_option Whether to add a list option or not
  135.      */
  136.     public $add_list_option = false;
  137.  
  138.     // }}}
  139.     // Private properties {{{
  140.  
  141.     /**
  142.      * When an action is called remember it to allow for multiple calls.
  143.      *
  144.      * @var object $action_instance Placeholder for action
  145.      */
  146.     private $_action_instance = null;
  147.  
  148.     // }}}
  149.     // __construct() {{{
  150.  
  151.     /**
  152.      * Constructor.
  153.      *
  154.      * @param string $name   The name of the option
  155.      * @param array  $params An optional array of parameters
  156.      *
  157.      * @return void 
  158.      */
  159.     public function __construct($name = null$params = array()) 
  160.     {
  161.         parent::__construct($name$params);
  162.         if ($this->action == 'Password'{
  163.             // special case for Password action, password can be passed to the 
  164.             // commandline or prompted by the parser
  165.             $this->argument_optional = true;
  166.         }
  167.     }
  168.  
  169.     // }}}
  170.     // toString() {{{
  171.  
  172.     /**
  173.      * Returns the string representation of the option.
  174.      *
  175.      * @param string $delim Delimiter to use between short and long option
  176.      *
  177.      * @return string The string representation of the option
  178.      * @todo use __toString() instead
  179.      */
  180.     public function toString($delim ", ")
  181.     {
  182.         $ret     '';
  183.         $padding '';
  184.         if ($this->short_name != null{
  185.             $ret .= $this->short_name;
  186.             if ($this->expectsArgument()) {
  187.                 $ret .= ' ' $this->help_name;
  188.             }
  189.             $padding $delim;
  190.         }
  191.         if ($this->long_name != null{
  192.             $ret .= $padding $this->long_name;
  193.             if ($this->expectsArgument()) {
  194.                 $ret .= '=' $this->help_name;
  195.             }
  196.         }
  197.         return $ret;
  198.     }
  199.  
  200.     // }}}
  201.     // expectsArgument() {{{
  202.  
  203.     /**
  204.      * Returns true if the option requires one or more argument and false
  205.      * otherwise.
  206.      *
  207.      * @return bool Whether the option expects an argument or not
  208.      */
  209.     public function expectsArgument()
  210.     {
  211.         if ($this->action == 'StoreTrue' || $this->action == 'StoreFalse' ||
  212.             $this->action == 'Help' || $this->action == 'Version' ||
  213.             $this->action == 'Counter' || $this->action == 'List'{
  214.             return false;
  215.         }
  216.         return true;
  217.     }
  218.  
  219.     // }}}
  220.     // dispatchAction() {{{
  221.  
  222.     /**
  223.      * Formats the value $value according to the action of the option and
  224.      * updates the passed Console_CommandLine_Result object.
  225.      *
  226.      * @param mixed                      $value  The value to format
  227.      * @param Console_CommandLine_Result $result The result instance
  228.      * @param Console_CommandLine        $parser The parser instance
  229.      *
  230.      * @return void 
  231.      * @throws Console_CommandLine_Exception
  232.      */
  233.     public function dispatchAction($value$result$parser)
  234.     {
  235.         $actionInfo Console_CommandLine::$actions[$this->action];
  236.         if (true === $actionInfo[1]{
  237.             // we have a "builtin" action
  238.             $tokens explode('_'$actionInfo[0]);
  239.             include_once implode('/'$tokens'.php';
  240.         }
  241.         $clsname $actionInfo[0];
  242.         if ($this->_action_instance === null{
  243.             $this->_action_instance  = new $clsname($result$this$parser);
  244.         }
  245.  
  246.         // check value is in option choices
  247.         if (!empty($this->choices&& !in_array($this->_action_instance->format($value)$this->choices)) {
  248.             throw Console_CommandLine_Exception::factory(
  249.                 'OPTION_VALUE_NOT_VALID',
  250.                 array(
  251.                     'name'    => $this->name,
  252.                     'choices' => implode('", "'$this->choices),
  253.                     'value'   => $value,
  254.                 ),
  255.                 $parser,
  256.                 $this->messages
  257.             );
  258.         }
  259.         $this->_action_instance->execute($value$this->action_params);
  260.     }
  261.  
  262.     // }}}
  263.     // validate() {{{
  264.  
  265.     /**
  266.      * Validates the option instance.
  267.      *
  268.      * @return void 
  269.      * @throws Console_CommandLine_Exception
  270.      * @todo use exceptions instead
  271.      */
  272.     public function validate()
  273.     {
  274.         // check if the option name is valid
  275.         if (!preg_match('/^[a-zA-Z_\x7f-\xff]+[a-zA-Z0-9_\x7f-\xff]*$/',
  276.             $this->name)) {
  277.             Console_CommandLine::triggerError('option_bad_name',
  278.                 E_USER_ERRORarray('{$name}' => $this->name));
  279.         }
  280.         // call the parent validate method
  281.         parent::validate();
  282.         // a short_name or a long_name must be provided
  283.         if ($this->short_name == null && $this->long_name == null{
  284.             Console_CommandLine::triggerError('option_long_and_short_name_missing',
  285.                 E_USER_ERRORarray('{$name}' => $this->name));
  286.         }
  287.         // check if the option short_name is valid
  288.         if ($this->short_name != null && 
  289.             !(preg_match('/^\-[a-zA-Z]{1}$/'$this->short_name))) {
  290.             Console_CommandLine::triggerError('option_bad_short_name',
  291.                 E_USER_ERRORarray(
  292.                     '{$name}' => $this->name
  293.                     '{$short_name}' => $this->short_name
  294.                 ));
  295.         }
  296.         // check if the option long_name is valid
  297.         if ($this->long_name != null && 
  298.             !preg_match('/^\-\-[a-zA-Z]+[a-zA-Z0-9_\-]*$/'$this->long_name)) {
  299.             Console_CommandLine::triggerError('option_bad_long_name',
  300.                 E_USER_ERRORarray(
  301.                     '{$name}' => $this->name
  302.                     '{$long_name}' => $this->long_name
  303.                 ));
  304.         }
  305.         // check if we have a valid action
  306.         if (!is_string($this->action)) {
  307.             Console_CommandLine::triggerError('option_bad_action',
  308.                 E_USER_ERRORarray('{$name}' => $this->name));
  309.         }
  310.         if (!isset(Console_CommandLine::$actions[$this->action])) {
  311.             Console_CommandLine::triggerError('option_unregistered_action',
  312.                 E_USER_ERRORarray(
  313.                     '{$action}' => $this->action,
  314.                     '{$name}' => $this->name
  315.                 ));
  316.         }
  317.         // if the action is a callback, check that we have a valid callback
  318.         if ($this->action == 'Callback' && !is_callable($this->callback)) {
  319.             Console_CommandLine::triggerError('option_invalid_callback',
  320.                 E_USER_ERRORarray('{$name}' => $this->name));
  321.         }
  322.     }
  323.  
  324.     // }}}
  325.     // setDefaults() {{{
  326.  
  327.     /**
  328.      * Set the default value according to the configured action.
  329.      *
  330.      * Note that for backward compatibility issues this method is only called
  331.      * when the 'force_options_defaults' is set to true, it will become the
  332.      * default behaviour in the next major release of Console_CommandLine.
  333.      *
  334.      * @return void 
  335.      */
  336.     public function setDefaults()
  337.     {
  338.         if ($this->default !== null{
  339.             // already set
  340.             return;
  341.         }
  342.         switch ($this->action{
  343.         case 'Counter':
  344.         case 'StoreInt':
  345.             $this->default = 0;
  346.             break;
  347.         case 'StoreFloat':
  348.             $this->default = 0.0;
  349.             break;
  350.         case 'StoreArray':
  351.             $this->default = array();
  352.             break;
  353.         case 'StoreTrue':
  354.             $this->default = false;
  355.             break;
  356.         case 'StoreFalse':
  357.             $this->default = true;
  358.             break;
  359.         default:
  360.             return;
  361.         }
  362.     }
  363.  
  364.     // }}}
  365. }

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