You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Option.php 11KB

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