PageRenderTime 50ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

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

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