CommandConsumer.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. if(in_array("--executeName",$input)) {
  48. $execute = $name;
  49. } else {
  50. $consolePath = $this->serviceContainer->get('kernel')->getRootDir() . '/../bin/console';
  51. $command = $name . ' ' . implode(' ', $input);
  52. $execute = "{$consolePath} {$command}";
  53. }
  54. try {
  55. $process = new Process($execute);
  56. $process->setTimeout(10 * 60);
  57. $process->run();
  58. $content = $process->getOutput();
  59. echo $content;
  60. } catch (ProcessFailedException $e) {
  61. echo 'KILL COMMAND: ', $e->getMessage(), "\n";
  62. } catch (\Exception $e) {
  63. echo 'KILL COMMAND: ', $e->getMessage(), "\n";
  64. }
  65. return true;
  66. }
  67. return false;
  68. }
  69. }