PageRenderTime 41ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/library/Zend/Tool/Framework/Client/Console/ArgumentParser.php

https://bitbucket.org/cclearning/seaeagle3
PHP | 503 lines | 301 code | 79 blank | 123 comment | 64 complexity | 3e97f09769ac83b5b121e304757c9191 MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Tool
  17. * @subpackage Framework
  18. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: ArgumentParser.php 18951 2009-11-12 16:26:19Z alexander $
  21. */
  22. /**
  23. * @see Zend_Console_GetOpt
  24. */
  25. require_once 'Zend/Console/Getopt.php';
  26. /**
  27. * @category Zend
  28. * @package Zend_Tool
  29. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  30. * @license http://framework.zend.com/license/new-bsd New BSD License
  31. */
  32. class Zend_Tool_Framework_Client_Console_ArgumentParser implements Zend_Tool_Framework_Registry_EnabledInterface
  33. {
  34. /**
  35. * @var Zend_Tool_Framework_Registry_Interface
  36. */
  37. protected $_registry = null;
  38. /**
  39. * @var Zend_Tool_Framework_Client_Request
  40. */
  41. protected $_request = null;
  42. /**
  43. * @var Zend_Tool_Framework_Client_Response
  44. */
  45. protected $_response = null;
  46. /**#@+
  47. * @var array
  48. */
  49. protected $_argumentsOriginal = null;
  50. protected $_argumentsWorking = null;
  51. /**#@-*/
  52. /**
  53. * @var bool
  54. */
  55. protected $_help = false;
  56. protected $_helpKnownAction = false;
  57. protected $_helpKnownProvider = false;
  58. protected $_helpKnownSpecialty = false;
  59. /**
  60. * setArguments
  61. *
  62. * @param array $arguments
  63. * @return Zend_Tool_Framework_Client_Console_ArgumentParser
  64. */
  65. public function setArguments(Array $arguments)
  66. {
  67. $this->_argumentsOriginal = $this->_argumentsWorking = $arguments;
  68. return $this;
  69. }
  70. /**
  71. * setRegistry()
  72. *
  73. * @param Zend_Tool_Framework_Registry_Interface $registry
  74. * @return Zend_Tool_Framework_Client_Console_ArgumentParser
  75. */
  76. public function setRegistry(Zend_Tool_Framework_Registry_Interface $registry)
  77. {
  78. // get the client registry
  79. $this->_registry = $registry;
  80. // set manifest repository, request, response for easy access
  81. $this->_manifestRepository = $this->_registry->getManifestRepository();
  82. $this->_request = $this->_registry->getRequest();
  83. $this->_response = $this->_registry->getResponse();
  84. return $this;
  85. }
  86. /**
  87. * Parse() - This method does the work of parsing the arguments into the enpooint request,
  88. * this will also (during help operations) fill the response in with information as needed
  89. *
  90. * @return null
  91. */
  92. public function parse()
  93. {
  94. if ($this->_request == null || $this->_response == null) {
  95. require_once 'Zend/Tool/Framework/Client/Exception.php';
  96. throw new Zend_Tool_Framework_Client_Exception('The client registry must have both a request and response registered.');
  97. }
  98. // setup the help options
  99. $helpResponseOptions = array();
  100. // check to see if the first cli arg is the script name
  101. if ($this->_argumentsWorking[0] == $_SERVER['SCRIPT_NAME' ]) {
  102. array_shift($this->_argumentsWorking);
  103. }
  104. // process global options
  105. try {
  106. $this->_parseGlobalPart();
  107. } catch (Zend_Tool_Framework_Client_Exception $exception) {
  108. $this->_createHelpResponse(array('error' => $exception->getMessage()));
  109. return;
  110. }
  111. // ensure there are arguments left
  112. if (count($this->_argumentsWorking) == 0) {
  113. $this->_request->setDispatchable(false); // at this point request is not dispatchable
  114. // check to see if this was a help request
  115. if ($this->_help) {
  116. $this->_createHelpResponse();
  117. } else {
  118. $this->_createHelpResponse(array('error' => 'An action and provider is required.'));
  119. }
  120. return;
  121. }
  122. // process the action part of the command line
  123. try {
  124. $this->_parseActionPart();
  125. } catch (Zend_Tool_Framework_Client_Exception $exception) {
  126. $this->_request->setDispatchable(false);
  127. $this->_createHelpResponse(array('error' => $exception->getMessage()));
  128. return;
  129. }
  130. if ($this->_helpKnownAction) {
  131. $helpResponseOptions = array_merge(
  132. $helpResponseOptions,
  133. array('actionName' => $this->_request->getActionName())
  134. );
  135. }
  136. /* @TODO Action Parameter Requirements */
  137. // make sure there are more "words" on the command line
  138. if (count($this->_argumentsWorking) == 0) {
  139. $this->_request->setDispatchable(false); // at this point request is not dispatchable
  140. // check to see if this is a help request
  141. if ($this->_help) {
  142. $this->_createHelpResponse($helpResponseOptions);
  143. } else {
  144. $this->_createHelpResponse(array_merge($helpResponseOptions, array('error' => 'A provider is required.')));
  145. }
  146. return;
  147. }
  148. // process the provider part of the command line
  149. try {
  150. $this->_parseProviderPart();
  151. } catch (Zend_Tool_Framework_Client_Exception $exception) {
  152. $this->_request->setDispatchable(false);
  153. $this->_createHelpResponse(array('error' => $exception->getMessage()));
  154. return;
  155. }
  156. if ($this->_helpKnownProvider) {
  157. $helpResponseOptions = array_merge(
  158. $helpResponseOptions,
  159. array('providerName' => $this->_request->getProviderName())
  160. );
  161. }
  162. if ($this->_helpKnownSpecialty) {
  163. $helpResponseOptions = array_merge(
  164. $helpResponseOptions,
  165. array('specialtyName' => $this->_request->getSpecialtyName())
  166. );
  167. }
  168. // if there are arguments on the command line, lets process them as provider options
  169. if (count($this->_argumentsWorking) != 0) {
  170. $this->_parseProviderOptionsPart();
  171. }
  172. // if there is still arguments lingering around, we can assume something is wrong
  173. if (count($this->_argumentsWorking) != 0) {
  174. $this->_request->setDispatchable(false); // at this point request is not dispatchable
  175. if ($this->_help) {
  176. $this->_createHelpResponse($helpResponseOptions);
  177. } else {
  178. $this->_createHelpResponse(array_merge(
  179. $helpResponseOptions,
  180. array('error' => 'Unknown arguments left on the command line: ' . implode(' ', $this->_argumentsWorking))
  181. ));
  182. }
  183. return;
  184. }
  185. // everything was processed and this is a request for help information
  186. if ($this->_help) {
  187. $this->_request->setDispatchable(false); // at this point request is not dispatchable
  188. $this->_createHelpResponse($helpResponseOptions);
  189. }
  190. return;
  191. }
  192. /**
  193. * Internal routine for parsing global options from the command line
  194. *
  195. * @return null
  196. */
  197. protected function _parseGlobalPart()
  198. {
  199. $getoptOptions = array();
  200. $getoptOptions['help|h'] = 'HELP';
  201. $getoptOptions['verbose|v'] = 'VERBOSE';
  202. $getoptOptions['pretend|p'] = 'PRETEND';
  203. $getoptOptions['debug|d'] = 'DEBUG';
  204. $getoptParser = new Zend_Console_Getopt($getoptOptions, $this->_argumentsWorking, array('parseAll' => false));
  205. // @todo catch any exceptions here
  206. $getoptParser->parse();
  207. foreach ($getoptParser->getOptions() as $option) {
  208. if ($option == 'pretend') {
  209. $this->_request->setPretend(true);
  210. } elseif ($option == 'debug') {
  211. $this->_request->setDebug(true);
  212. } elseif ($option == 'verbose') {
  213. $this->_request->setVerbose(true);
  214. } else {
  215. $property = '_'.$option;
  216. $this->{$property} = true;
  217. }
  218. }
  219. $this->_argumentsWorking = $getoptParser->getRemainingArgs();
  220. return;
  221. }
  222. /**
  223. * Internal routine for parsing the action name from the arguments
  224. *
  225. * @return null
  226. */
  227. protected function _parseActionPart()
  228. {
  229. // the next "word" should be the action name
  230. $consoleActionName = array_shift($this->_argumentsWorking);
  231. if ($consoleActionName == '?') {
  232. $this->_help = true;
  233. return;
  234. }
  235. // is the action name valid?
  236. $actionMetadata = $this->_manifestRepository->getMetadata(array(
  237. 'type' => 'Tool',
  238. 'name' => 'actionName',
  239. 'value' => $consoleActionName,
  240. 'clientName' => 'console'
  241. ));
  242. // if no action, handle error
  243. if (!$actionMetadata) {
  244. require_once 'Zend/Tool/Framework/Client/Exception.php';
  245. throw new Zend_Tool_Framework_Client_Exception('Action \'' . $consoleActionName . '\' is not a valid action.');
  246. }
  247. // prepare action request name
  248. $this->_helpKnownAction = true;
  249. $this->_request->setActionName($actionMetadata->getActionName());
  250. return;
  251. }
  252. /**
  253. * Internal routine for parsing the provider part of the command line arguments
  254. *
  255. * @return null
  256. */
  257. protected function _parseProviderPart()
  258. {
  259. // get the cli "word" as the provider name from command line
  260. $consoleProviderFull = array_shift($this->_argumentsWorking);
  261. $consoleSpecialtyName = '_global';
  262. // if there is notation for specialties? If so, break them up
  263. if (strstr($consoleProviderFull, '.')) {
  264. list($consoleProviderName, $consoleSpecialtyName) = explode('.', $consoleProviderFull);
  265. } else {
  266. $consoleProviderName = $consoleProviderFull;
  267. }
  268. if ($consoleProviderName == '?') {
  269. $this->_help = true;
  270. return;
  271. }
  272. // get the cli provider names from the manifest
  273. $providerMetadata = $this->_manifestRepository->getMetadata(array(
  274. 'type' => 'Tool',
  275. 'name' => 'providerName',
  276. 'value' => $consoleProviderName,
  277. 'clientName' => 'console'
  278. ));
  279. if (!$providerMetadata) {
  280. require_once 'Zend/Tool/Framework/Client/Exception.php';
  281. throw new Zend_Tool_Framework_Client_Exception(
  282. 'Provider \'' . $consoleProviderFull . '\' is not a valid provider.'
  283. );
  284. }
  285. $this->_helpKnownProvider = true;
  286. $this->_request->setProviderName($providerMetadata->getProviderName());
  287. if ($consoleSpecialtyName == '?') {
  288. $this->_help = true;
  289. return;
  290. }
  291. $providerSpecialtyMetadata = $this->_manifestRepository->getMetadata(array(
  292. 'type' => 'Tool',
  293. 'name' => 'specialtyName',
  294. 'value' => $consoleSpecialtyName,
  295. 'providerName' => $providerMetadata->getProviderName(),
  296. 'clientName' => 'console'
  297. ));
  298. if (!$providerSpecialtyMetadata) {
  299. require_once 'Zend/Tool/Framework/Client/Exception.php';
  300. throw new Zend_Tool_Framework_Client_Exception(
  301. 'Provider \'' . $consoleSpecialtyName . '\' is not a valid specialty.'
  302. );
  303. }
  304. $this->_helpKnownSpecialty = true;
  305. $this->_request->setSpecialtyName($providerSpecialtyMetadata->getSpecialtyName());
  306. return;
  307. }
  308. /**
  309. * Internal routine for parsing the provider options from the command line
  310. *
  311. * @return null
  312. */
  313. protected function _parseProviderOptionsPart()
  314. {
  315. if (current($this->_argumentsWorking) == '?') {
  316. $this->_help = true;
  317. return;
  318. }
  319. $searchParams = array(
  320. 'type' => 'Tool',
  321. 'providerName' => $this->_request->getProviderName(),
  322. 'actionName' => $this->_request->getActionName(),
  323. 'specialtyName' => $this->_request->getSpecialtyName(),
  324. 'clientName' => 'console'
  325. );
  326. $actionableMethodLongParamsMetadata = $this->_manifestRepository->getMetadata(
  327. array_merge($searchParams, array('name' => 'actionableMethodLongParams'))
  328. );
  329. $actionableMethodShortParamsMetadata = $this->_manifestRepository->getMetadata(
  330. array_merge($searchParams, array('name' => 'actionableMethodShortParams'))
  331. );
  332. $paramNameShortValues = $actionableMethodShortParamsMetadata->getValue();
  333. $getoptOptions = array();
  334. $wordArguments = array();
  335. $longParamCanonicalNames = array();
  336. $actionableMethodLongParamsMetadataReference = $actionableMethodLongParamsMetadata->getReference();
  337. foreach ($actionableMethodLongParamsMetadata->getValue() as $parameterNameLong => $consoleParameterNameLong) {
  338. $optionConfig = $consoleParameterNameLong . '|';
  339. $parameterInfo = $actionableMethodLongParamsMetadataReference['parameterInfo'][$parameterNameLong];
  340. // process ParameterInfo into array for command line option matching
  341. if ($parameterInfo['type'] == 'string' || $parameterInfo['type'] == 'bool') {
  342. $optionConfig .= $paramNameShortValues[$parameterNameLong]
  343. . (($parameterInfo['optional']) ? '-' : '=') . 's';
  344. } elseif (in_array($parameterInfo['type'], array('int', 'integer', 'float'))) {
  345. $optionConfig .= $paramNameShortValues[$parameterNameLong]
  346. . (($parameterInfo['optional']) ? '-' : '=') . 'i';
  347. } else {
  348. $optionConfig .= $paramNameShortValues[$parameterNameLong] . '-s';
  349. }
  350. $getoptOptions[$optionConfig] = ($parameterInfo['description'] != '') ? $parameterInfo['description'] : 'No description available.';
  351. // process ParameterInfo into array for command line WORD (argument) matching
  352. $wordArguments[$parameterInfo['position']]['parameterName'] = $parameterInfo['name'];
  353. $wordArguments[$parameterInfo['position']]['optional'] = $parameterInfo['optional'];
  354. $wordArguments[$parameterInfo['position']]['type'] = $parameterInfo['type'];
  355. // keep a translation of console to canonical names
  356. $longParamCanonicalNames[$consoleParameterNameLong] = $parameterNameLong;
  357. }
  358. if (!$getoptOptions) {
  359. // no options to parse here, return
  360. return;
  361. }
  362. // if non-option arguments exist, attempt to process them before processing options
  363. $wordStack = array();
  364. while ($wordOnTop = array_shift($this->_argumentsWorking)) {
  365. if (substr($wordOnTop, 0, 1) != '-') {
  366. array_push($wordStack, $wordOnTop);
  367. } else {
  368. // put word back on stack and move on
  369. array_unshift($this->_argumentsWorking, $wordOnTop);
  370. break;
  371. }
  372. if (count($wordStack) == count($wordArguments)) {
  373. // when we get at most the number of arguments we are expecting
  374. // then break out.
  375. break;
  376. }
  377. }
  378. if ($wordStack && $wordArguments) {
  379. for ($wordIndex = 1; $wordIndex <= count($wordArguments); $wordIndex++) {
  380. if (!array_key_exists($wordIndex-1, $wordStack) || !array_key_exists($wordIndex, $wordArguments)) {
  381. break;
  382. }
  383. $this->_request->setProviderParameter($wordArguments[$wordIndex]['parameterName'], $wordStack[$wordIndex-1]);
  384. unset($wordStack[$wordIndex-1]);
  385. }
  386. }
  387. $getoptParser = new Zend_Console_Getopt($getoptOptions, $this->_argumentsWorking, array('parseAll' => false));
  388. $getoptParser->parse();
  389. foreach ($getoptParser->getOptions() as $option) {
  390. $value = $getoptParser->getOption($option);
  391. $providerParamOption = $longParamCanonicalNames[$option];
  392. $this->_request->setProviderParameter($providerParamOption, $value);
  393. }
  394. /*
  395. $this->_metadataProviderOptionsLong = $actionableMethodLongParamsMetadata;
  396. $this->_metadataProviderOptionsShort = $actionableMethodShortParamsMetadata;
  397. */
  398. $this->_argumentsWorking = $getoptParser->getRemainingArgs();
  399. return;
  400. }
  401. /**
  402. * _createHelpResponse
  403. *
  404. * @param unknown_type $options
  405. */
  406. protected function _createHelpResponse($options = array())
  407. {
  408. require_once 'Zend/Tool/Framework/Client/Console/HelpSystem.php';
  409. $helpSystem = new Zend_Tool_Framework_Client_Console_HelpSystem();
  410. $helpSystem->setRegistry($this->_registry);
  411. if (isset($options['error'])) {
  412. $helpSystem->respondWithErrorMessage($options['error']);
  413. }
  414. if (isset($options['actionName']) && isset($options['providerName'])) {
  415. $helpSystem->respondWithSpecialtyAndParamHelp($options['providerName'], $options['actionName']);
  416. } elseif (isset($options['actionName'])) {
  417. $helpSystem->respondWithActionHelp($options['actionName']);
  418. } elseif (isset($options['providerName'])) {
  419. $helpSystem->respondWithProviderHelp($options['providerName']);
  420. } else {
  421. $helpSystem->respondWithGeneralHelp();
  422. }
  423. }
  424. }