|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace PHPCR\Shell\Subscriber; |
| 4 | + |
| 5 | +use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
| 6 | +use PHPCR\Shell\Console\Helper\ConfigHelper; |
| 7 | +use PHPCR\Shell\Event\PhpcrShellEvents; |
| 8 | +use PHPCR\Shell\Event\CommandPreRunEvent; |
| 9 | +use PHPCR\Shell\Console\Input\StringInput; |
| 10 | + |
| 11 | +/** |
| 12 | + * Check to see if the input references a command alias and |
| 13 | + * modify the input to represent the command which it represents. |
| 14 | + * |
| 15 | + * @author Daniel Leech <daniel@dantleech.com> |
| 16 | + */ |
| 17 | +class AliasSubscriber implements EventSubscriberInterface |
| 18 | +{ |
| 19 | + protected $config; |
| 20 | + |
| 21 | + public function __construct(ConfigHelper $config) |
| 22 | + { |
| 23 | + $this->config = $config; |
| 24 | + } |
| 25 | + |
| 26 | + public static function getSubscribedEvents() |
| 27 | + { |
| 28 | + return array( |
| 29 | + PhpcrShellEvents::COMMAND_PRE_RUN => 'handleAlias', |
| 30 | + ); |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Check for an alias and replace the input with a new string command |
| 35 | + * if the alias exists. |
| 36 | + * |
| 37 | + * @return string New command string (for testing purposes) |
| 38 | + */ |
| 39 | + public function handleAlias(CommandPreRunEvent $event) |
| 40 | + { |
| 41 | + $input = $event->getInput(); |
| 42 | + |
| 43 | + $commandName = $input->getFirstArgument(); |
| 44 | + |
| 45 | + $aliasConfig = $this->config->getConfig('alias'); |
| 46 | + |
| 47 | + if (!isset($aliasConfig[$commandName])) { |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + $commandTemplate = $aliasConfig[$commandName]; |
| 52 | + $replaces = array(); |
| 53 | + |
| 54 | + preg_match_all('{\{arg[0-9]+\}}', $commandTemplate, $matches); |
| 55 | + |
| 56 | + $args = array(); |
| 57 | + if (isset($matches[0])) { |
| 58 | + $args = $matches[0]; |
| 59 | + } |
| 60 | + |
| 61 | + $tokens = $input->getTokens(); |
| 62 | + |
| 63 | + foreach ($tokens as $i => $token) { |
| 64 | + $replaces['{arg' . $i . '}'] = $token; |
| 65 | + } |
| 66 | + |
| 67 | + $command = strtr($commandTemplate, $replaces); |
| 68 | + |
| 69 | + foreach ($args as $arg) { |
| 70 | + $command = str_replace($arg, '', $command); |
| 71 | + } |
| 72 | + |
| 73 | + $command = trim($command); |
| 74 | + error_log($command); |
| 75 | + |
| 76 | + $newInput = new StringInput($command); |
| 77 | + $event->setInput($newInput); |
| 78 | + |
| 79 | + return $command; |
| 80 | + } |
| 81 | +} |
0 commit comments