1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Clearcode\CommandBusConsole\Bundle\Command; |
4
|
|
|
|
5
|
|
|
use Clearcode\CommandBusConsole\CommandConsoleException; |
6
|
|
|
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; |
7
|
|
|
use Symfony\Component\Console\Input\InputArgument; |
8
|
|
|
use Symfony\Component\Console\Input\InputInterface; |
9
|
|
|
use Symfony\Component\Console\Output\OutputInterface; |
10
|
|
|
|
11
|
|
|
class CommandBusConsoleCommand extends ContainerAwareCommand |
12
|
|
|
{ |
13
|
|
|
const SUCCESS_CODE = 0; |
14
|
|
|
const ERROR_CODE = 1; |
15
|
|
|
|
16
|
|
|
protected function configure() |
17
|
|
|
{ |
18
|
|
|
$this |
19
|
|
|
->setName('command-bus:handle') |
20
|
|
|
->setDescription('CLI for command bus.') |
21
|
|
|
->addArgument('commandName', InputArgument::REQUIRED) |
22
|
|
|
->addArgument('arguments', InputArgument::IS_ARRAY); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** {@inheritdoc} */ |
26
|
|
|
protected function execute(InputInterface $input, OutputInterface $output) |
27
|
|
|
{ |
28
|
|
|
$commandLauncher = $this->getContainer()->get('command_bus_console.command_launcher'); |
29
|
|
|
|
30
|
|
|
$commandToLunch = $input->getArgument('commandName'); |
31
|
|
|
$arguments = $input->getArgument('arguments'); |
32
|
|
|
|
33
|
|
|
$arguments = $this->parseNamedArguments($arguments); |
34
|
|
|
|
35
|
|
|
try { |
36
|
|
|
$command = $commandLauncher->getCommandToLaunch($commandToLunch, $arguments); |
37
|
|
|
} catch (CommandConsoleException $e) { |
38
|
|
|
return $this->handleException($output, $e); |
39
|
|
|
} |
40
|
|
|
try { |
41
|
|
|
$this->getContainer()->get('command_bus')->handle($command); |
42
|
|
|
} catch (\Exception $e) { |
43
|
|
|
return $this->handleException($output, $e); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
return $this->handleSuccess($output, $commandToLunch); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
private function handleException(OutputInterface $output, \Exception $exception) |
50
|
|
|
{ |
51
|
|
|
$output->writeln(sprintf('<error>%s</error>', $exception->getMessage())); |
52
|
|
|
|
53
|
|
|
return self::ERROR_CODE; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
private function handleSuccess(OutputInterface $output, $commandToLunch) |
57
|
|
|
{ |
58
|
|
|
$output->writeln(sprintf('The <info>%s</info> executed with success.', $commandToLunch)); |
59
|
|
|
|
60
|
|
|
return self::SUCCESS_CODE; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param string[] $arguments |
65
|
|
|
* |
66
|
|
|
* @return string[] |
67
|
|
|
*/ |
68
|
|
|
protected function parseNamedArguments(array $arguments) |
69
|
|
|
{ |
70
|
|
|
foreach ($arguments as $key => $argument) { |
71
|
|
|
if (strpos($argument, '=')) { |
72
|
|
|
list($arg, $value) = explode('=', $argument); |
73
|
|
|
|
74
|
|
|
unset($arguments[$key]); |
75
|
|
|
$arguments[$arg] = $value; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
return $arguments; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|