CommandConsumer.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace WorkflowBundle\Services;
  3. use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
  4. use PhpAmqpLib\Message\AMQPMessage;
  5. use Symfony\Bundle\FrameworkBundle\Console\Application;
  6. use Symfony\Component\DependencyInjection\ContainerInterface;
  7. use Symfony\Component\Console\Input\ArrayInput;
  8. use Symfony\Component\Console\Output\BufferedOutput;
  9. class CommandConsumer
  10. {
  11. /**
  12. * @var ContainerInterface
  13. */
  14. protected $serviceContainer;
  15. /**
  16. * @param ContainerInterface $serviceContainer
  17. */
  18. public function __construct(ContainerInterface $serviceContainer)
  19. {
  20. $this->serviceContainer = $serviceContainer;
  21. }
  22. /**
  23. * $msg will be an instance of `PhpAmqpLib\Message\AMQPMessage`
  24. * with the $msg->body being the data sent over RabbitMQ.
  25. *
  26. * @param AMQPMessage $msg
  27. */
  28. public function execute(AMQPMessage $msg)
  29. {
  30. $msgBody = unserialize($msg->getBody());
  31. if (isset($msgBody['name']) && isset($msgBody['args'])) {
  32. // command name and args
  33. $name = $msgBody['name'];
  34. $args = $msgBody['args'];
  35. $kernel = $this->serviceContainer->get('kernel');
  36. $application = new Application($kernel);
  37. $application->setAutoExit(false);
  38. $input = array('command' => $name,);
  39. foreach ($args as $arg) {
  40. $pieces = explode(':', $arg);
  41. if (isset($pieces[0]) && isset($pieces[1])) {
  42. $input["--{$pieces[0]}"] = $pieces[1];
  43. } elseif (isset($pieces[0])) {
  44. $input[] = $pieces[0];
  45. }
  46. }
  47. $input = new ArrayInput($input);
  48. $output = new BufferedOutput();
  49. $application->run($input, $output);
  50. // return the output
  51. $content = $output->fetch();
  52. echo $content;
  53. return true;
  54. }
  55. return false;
  56. }
  57. }