CommandConsumer.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace WorkflowBundle\Services;
  3. use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
  4. use PhpAmqpLib\Message\AMQPMessage;
  5. use Symfony\Component\DependencyInjection\ContainerInterface;
  6. use Symfony\Component\Process\Process;
  7. use Symfony\Component\Process\Exception\ProcessFailedException;
  8. class CommandConsumer implements ConsumerInterface
  9. {
  10. /**
  11. * @var ContainerInterface
  12. */
  13. protected $serviceContainer;
  14. /**
  15. * @param ContainerInterface $serviceContainer
  16. */
  17. public function __construct(ContainerInterface $serviceContainer)
  18. {
  19. $this->serviceContainer = $serviceContainer;
  20. }
  21. /**
  22. * $msg will be an instance of `PhpAmqpLib\Message\AMQPMessage`
  23. * with the $msg->body being the data sent over RabbitMQ.
  24. *
  25. * @param AMQPMessage $msg
  26. */
  27. public function execute(AMQPMessage $msg)
  28. {
  29. $msgBody = unserialize($msg->body);
  30. if (isset($msgBody['name']) && isset($msgBody['args'])) {
  31. // command name and args
  32. $name = $msgBody['name'];
  33. $args = $msgBody['args'];
  34. $input = array();
  35. foreach ($args as $arg) {
  36. $arg = str_replace('\\', '\\\\', $arg);
  37. $pos = strpos($arg, ':');
  38. $pos2 = strpos($arg, '--');
  39. if ($pos2 === false) {
  40. // command argument, no option
  41. $input[] = substr($arg, $pos + 1);
  42. } else {
  43. // reemplazo el primer : por = para las options
  44. $input[] = preg_replace('/:/', '=', $arg, 1);
  45. }
  46. }
  47. $consolePath = $this->serviceContainer->get('kernel')->getRootDir() . '/../bin/console';
  48. $command = $name . ' ' . implode(' ', $input);
  49. try {
  50. $process = new Process("{$consolePath} {$command}");
  51. $process->setTimeout(10 * 60);
  52. $process->run();
  53. $content = $process->getOutput();
  54. echo $content;
  55. } catch (ProcessFailedException $e) {
  56. echo 'KILL COMMAND: ', $e->getMessage(), "\n";
  57. } catch (\Exception $e) {
  58. echo 'KILL COMMAND: ', $e->getMessage(), "\n";
  59. }
  60. return true;
  61. }
  62. return false;
  63. }
  64. }