CommandConsumer.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 implements ConsumerInterface
  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->body);
  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. }
  44. }
  45. $input = new ArrayInput($input);
  46. $output = new BufferedOutput();
  47. $application->run($input, $output);
  48. // return the output
  49. $content = $output->fetch();
  50. echo $content;
  51. return true;
  52. }
  53. return false;
  54. }
  55. }