LogConsumer.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace WorkflowBundle\Services;
  3. use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
  4. use PhpAmqpLib\Message\AMQPMessage;
  5. use Symfony\Component\DependencyInjection\ContainerInterface;
  6. class LogConsumer implements ConsumerInterface
  7. {
  8. /**
  9. * @var ContainerInterface
  10. */
  11. protected $serviceContainer;
  12. /**
  13. * @param ContainerInterface $serviceContainer
  14. */
  15. public function __construct(ContainerInterface $serviceContainer)
  16. {
  17. $this->serviceContainer = $serviceContainer;
  18. }
  19. /**
  20. * $msg will be an instance of `PhpAmqpLib\Message\AMQPMessage`
  21. * with the $msg->body being the data sent over RabbitMQ.
  22. *
  23. * @param AMQPMessage $msg
  24. */
  25. public function execute(AMQPMessage $msg)
  26. {
  27. $message = '';
  28. $level = '';
  29. $channel = '';
  30. try {
  31. $msgBody = json_decode($msg->body, true);
  32. if (!json_last_error() && isset($msgBody['message']) && !empty($msgBody['message'])) {
  33. $message = $msgBody['message'];
  34. $level = $msgBody['level_name'];
  35. $channel = $msgBody['channel'];
  36. }
  37. } catch (\Exception $ex) {
  38. $message = $ex->getMessage();
  39. }
  40. $log = $this->createLog($message, $level, $channel);
  41. if (is_null($log)) {
  42. var_dump('Error: log no creado');
  43. } else {
  44. var_dump(sprintf("ID: %s Message: %s", $log->getId(), $log->getMessage()));
  45. }
  46. return;
  47. }
  48. /**
  49. * Crea una entidad Log y la persiste
  50. *
  51. * @param string $message
  52. *
  53. * @return \WorkflowBundle\Services\LogBundle\Entity\Log
  54. */
  55. private function createLog($message, $level, $channel)
  56. {
  57. $logClass = 'LogBundle\Entity\Log';
  58. if ($message && class_exists($logClass)) {
  59. $log = new $logClass();
  60. $log->setMessage($message);
  61. $log->setLevel($level);
  62. $log->setChannel($channel);
  63. $em = $this->serviceContainer->get('doctrine.orm.entity_manager');
  64. $validator = $this->serviceContainer->get('validator');
  65. if ($validator->validate($log)->count() == 0) {
  66. $em->persist($log);
  67. $em->flush($log);
  68. return $log;
  69. }
  70. }
  71. return null;
  72. }
  73. }