CompletionHandler.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. <?php
  2. namespace Stecman\Component\Symfony\Console\BashCompletion;
  3. use Stecman\Component\Symfony\Console\BashCompletion\Completion\CompletionAwareInterface;
  4. use Stecman\Component\Symfony\Console\BashCompletion\Completion\CompletionInterface;
  5. use Symfony\Component\Console\Application;
  6. use Symfony\Component\Console\Command\Command;
  7. use Symfony\Component\Console\Input\ArrayInput;
  8. use Symfony\Component\Console\Input\InputArgument;
  9. use Symfony\Component\Console\Input\InputOption;
  10. class CompletionHandler
  11. {
  12. /**
  13. * Application to complete for
  14. * @var \Symfony\Component\Console\Application
  15. */
  16. protected $application;
  17. /**
  18. * @var Command
  19. */
  20. protected $command;
  21. /**
  22. * @var CompletionContext
  23. */
  24. protected $context;
  25. /**
  26. * Array of completion helpers.
  27. * @var CompletionInterface[]
  28. */
  29. protected $helpers = array();
  30. public function __construct(Application $application, CompletionContext $context = null)
  31. {
  32. $this->application = $application;
  33. $this->context = $context;
  34. $this->addHandler(
  35. new Completion(
  36. 'help',
  37. 'command_name',
  38. Completion::TYPE_ARGUMENT,
  39. array_keys($application->all())
  40. )
  41. );
  42. $this->addHandler(
  43. new Completion(
  44. 'list',
  45. 'namespace',
  46. Completion::TYPE_ARGUMENT,
  47. $application->getNamespaces()
  48. )
  49. );
  50. }
  51. public function setContext(CompletionContext $context)
  52. {
  53. $this->context = $context;
  54. }
  55. /**
  56. * @return CompletionContext
  57. */
  58. public function getContext()
  59. {
  60. return $this->context;
  61. }
  62. /**
  63. * @param CompletionInterface[] $array
  64. */
  65. public function addHandlers(array $array)
  66. {
  67. $this->helpers = array_merge($this->helpers, $array);
  68. }
  69. /**
  70. * @param CompletionInterface $helper
  71. */
  72. public function addHandler(CompletionInterface $helper)
  73. {
  74. $this->helpers[] = $helper;
  75. }
  76. /**
  77. * Do the actual completion, returning an array of strings to provide to the parent shell's completion system
  78. *
  79. * @throws \RuntimeException
  80. * @return string[]
  81. */
  82. public function runCompletion()
  83. {
  84. if (!$this->context) {
  85. throw new \RuntimeException('A CompletionContext must be set before requesting completion.');
  86. }
  87. $cmdName = $this->getInput()->getFirstArgument();
  88. try {
  89. $this->command = $this->application->find($cmdName);
  90. } catch (\InvalidArgumentException $e) {
  91. // Exception thrown, when multiple or none commands are found.
  92. }
  93. $process = array(
  94. 'completeForOptionValues',
  95. 'completeForOptionShortcuts',
  96. 'completeForOptionShortcutValues',
  97. 'completeForOptions',
  98. 'completeForCommandName',
  99. 'completeForCommandArguments'
  100. );
  101. foreach ($process as $methodName) {
  102. $result = $this->{$methodName}();
  103. if (false !== $result) {
  104. // Return the result of the first completion mode that matches
  105. return $this->filterResults((array) $result);
  106. }
  107. }
  108. return array();
  109. }
  110. /**
  111. * Get an InputInterface representation of the completion context
  112. *
  113. * @return ArrayInput
  114. */
  115. public function getInput()
  116. {
  117. // Filter the command line content to suit ArrayInput
  118. $words = $this->context->getWords();
  119. array_shift($words);
  120. $words = array_filter($words);
  121. return new ArrayInput($words);
  122. }
  123. /**
  124. * Attempt to complete the current word as a long-form option (--my-option)
  125. *
  126. * @return array|false
  127. */
  128. protected function completeForOptions()
  129. {
  130. $word = $this->context->getCurrentWord();
  131. if (substr($word, 0, 2) === '--') {
  132. $options = array();
  133. foreach ($this->getAllOptions() as $opt) {
  134. $options[] = '--'.$opt->getName();
  135. }
  136. return $options;
  137. }
  138. return false;
  139. }
  140. /**
  141. * Attempt to complete the current word as an option shortcut.
  142. *
  143. * If the shortcut exists it will be completed, but a list of possible shortcuts is never returned for completion.
  144. *
  145. * @return array|false
  146. */
  147. protected function completeForOptionShortcuts()
  148. {
  149. $word = $this->context->getCurrentWord();
  150. if (strpos($word, '-') === 0 && strlen($word) == 2) {
  151. $definition = $this->command ? $this->command->getNativeDefinition() : $this->application->getDefinition();
  152. if ($definition->hasShortcut(substr($word, 1))) {
  153. return array($word);
  154. }
  155. }
  156. return false;
  157. }
  158. /**
  159. * Attempt to complete the current word as the value of an option shortcut
  160. *
  161. * @return array|false
  162. */
  163. protected function completeForOptionShortcutValues()
  164. {
  165. $wordIndex = $this->context->getWordIndex();
  166. if ($this->command && $wordIndex > 1) {
  167. $left = $this->context->getWordAtIndex($wordIndex - 1);
  168. // Complete short options
  169. if ($left[0] == '-' && strlen($left) == 2) {
  170. $shortcut = substr($left, 1);
  171. $def = $this->command->getNativeDefinition();
  172. if (!$def->hasShortcut($shortcut)) {
  173. return false;
  174. }
  175. $opt = $def->getOptionForShortcut($shortcut);
  176. if ($opt->isValueRequired() || $opt->isValueOptional()) {
  177. return $this->completeOption($opt);
  178. }
  179. }
  180. }
  181. return false;
  182. }
  183. /**
  184. * Attemp to complete the current word as the value of a long-form option
  185. *
  186. * @return array|false
  187. */
  188. protected function completeForOptionValues()
  189. {
  190. $wordIndex = $this->context->getWordIndex();
  191. if ($this->command && $wordIndex > 1) {
  192. $left = $this->context->getWordAtIndex($wordIndex - 1);
  193. if (strpos($left, '--') === 0) {
  194. $name = substr($left, 2);
  195. $def = $this->command->getNativeDefinition();
  196. if (!$def->hasOption($name)) {
  197. return false;
  198. }
  199. $opt = $def->getOption($name);
  200. if ($opt->isValueRequired() || $opt->isValueOptional()) {
  201. return $this->completeOption($opt);
  202. }
  203. }
  204. }
  205. return false;
  206. }
  207. /**
  208. * Attempt to complete the current word as a command name
  209. *
  210. * @return array|false
  211. */
  212. protected function completeForCommandName()
  213. {
  214. if (!$this->command || (count($this->context->getWords()) == 2 && $this->context->getWordIndex() == 1)) {
  215. $commands = $this->application->all();
  216. $names = array_keys($commands);
  217. if ($key = array_search('_completion', $names)) {
  218. unset($names[$key]);
  219. }
  220. return $names;
  221. }
  222. return false;
  223. }
  224. /**
  225. * Attempt to complete the current word as a command argument value
  226. *
  227. * @see Symfony\Component\Console\Input\InputArgument
  228. * @return array|false
  229. */
  230. protected function completeForCommandArguments()
  231. {
  232. if (!$this->command || strpos($this->context->getCurrentWord(), '-') === 0) {
  233. return false;
  234. }
  235. $definition = $this->command->getNativeDefinition();
  236. $argWords = $this->mapArgumentsToWords($definition->getArguments());
  237. $wordIndex = $this->context->getWordIndex();
  238. if (isset($argWords[$wordIndex])) {
  239. $name = $argWords[$wordIndex];
  240. } elseif (!empty($argWords) && $definition->getArgument(end($argWords))->isArray()) {
  241. $name = end($argWords);
  242. } else {
  243. return false;
  244. }
  245. if ($helper = $this->getCompletionHelper($name, Completion::TYPE_ARGUMENT)) {
  246. return $helper->run();
  247. }
  248. if ($this->command instanceof CompletionAwareInterface) {
  249. return $this->command->completeArgumentValues($name, $this->context);
  250. }
  251. return false;
  252. }
  253. /**
  254. * Find a CompletionInterface that matches the current command, target name, and target type
  255. *
  256. * @param string $name
  257. * @param string $type
  258. * @return CompletionInterface|null
  259. */
  260. protected function getCompletionHelper($name, $type)
  261. {
  262. foreach ($this->helpers as $helper) {
  263. if ($helper->getType() != $type && $helper->getType() != CompletionInterface::ALL_TYPES) {
  264. continue;
  265. }
  266. if ($helper->getCommandName() == CompletionInterface::ALL_COMMANDS || $helper->getCommandName() == $this->command->getName()) {
  267. if ($helper->getTargetName() == $name) {
  268. return $helper;
  269. }
  270. }
  271. }
  272. return null;
  273. }
  274. /**
  275. * Complete the value for the given option if a value completion is availble
  276. *
  277. * @param InputOption $option
  278. * @return array|false
  279. */
  280. protected function completeOption(InputOption $option)
  281. {
  282. if ($helper = $this->getCompletionHelper($option->getName(), Completion::TYPE_OPTION)) {
  283. return $helper->run();
  284. }
  285. if ($this->command instanceof CompletionAwareInterface) {
  286. return $this->command->completeOptionValues($option->getName(), $this->context);
  287. }
  288. return false;
  289. }
  290. /**
  291. * Step through the command line to determine which word positions represent which argument values
  292. *
  293. * The word indexes of argument values are found by eliminating words that are known to not be arguments (options,
  294. * option values, and command names). Any word that doesn't match for elimination is assumed to be an argument value,
  295. *
  296. * @param InputArgument[] $argumentDefinitions
  297. * @return array as [argument name => word index on command line]
  298. */
  299. protected function mapArgumentsToWords($argumentDefinitions)
  300. {
  301. $argumentPositions = array();
  302. $argumentNumber = 0;
  303. $previousWord = null;
  304. $argumentNames = array_keys($argumentDefinitions);
  305. // Build a list of option values to filter out
  306. $optionsWithArgs = $this->getOptionWordsWithValues();
  307. foreach ($this->context->getWords() as $wordIndex => $word) {
  308. // Skip program name, command name, options, and option values
  309. if ($wordIndex < 2
  310. || ($word && '-' === $word[0])
  311. || in_array($previousWord, $optionsWithArgs)) {
  312. $previousWord = $word;
  313. continue;
  314. } else {
  315. $previousWord = $word;
  316. }
  317. // If argument n exists, pair that argument's name with the current word
  318. if (isset($argumentNames[$argumentNumber])) {
  319. $argumentPositions[$wordIndex] = $argumentNames[$argumentNumber];
  320. }
  321. $argumentNumber++;
  322. }
  323. return $argumentPositions;
  324. }
  325. /**
  326. * Build a list of option words/flags that will have a value after them
  327. * Options are returned in the format they appear as on the command line.
  328. *
  329. * @return string[] - eg. ['--myoption', '-m', ... ]
  330. */
  331. protected function getOptionWordsWithValues()
  332. {
  333. $strings = array();
  334. foreach ($this->getAllOptions() as $option) {
  335. if ($option->isValueRequired()) {
  336. $strings[] = '--' . $option->getName();
  337. if ($option->getShortcut()) {
  338. $strings[] = '-' . $option->getShortcut();
  339. }
  340. }
  341. }
  342. return $strings;
  343. }
  344. /**
  345. * Filter out results that don't match the current word on the command line
  346. *
  347. * @param string[] $array
  348. * @return string[]
  349. */
  350. protected function filterResults(array $array)
  351. {
  352. $curWord = $this->context->getCurrentWord();
  353. return array_filter($array, function($val) use ($curWord) {
  354. return fnmatch($curWord.'*', $val);
  355. });
  356. }
  357. /**
  358. * Get the combined options of the application and entered command
  359. *
  360. * @return InputOption[]
  361. */
  362. protected function getAllOptions()
  363. {
  364. if (!$this->command) {
  365. return $this->application->getDefinition()->getOptions();
  366. }
  367. return array_merge(
  368. $this->command->getNativeDefinition()->getOptions(),
  369. $this->application->getDefinition()->getOptions()
  370. );
  371. }
  372. }