LogConsumer.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 = isset($msgBody['level_name']) ? $msgBody['level_name'] : $level;
  35. $channel = isset($msgBody['channel']) ? $msgBody['channel'] : $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. * @param string $level
  53. * @param string $channel
  54. *
  55. * @return \WorkflowBundle\Services\LogBundle\Entity\Log
  56. */
  57. private function createLog($message, $level, $channel)
  58. {
  59. $logClass = 'LogBundle\Entity\Log';
  60. if ($message !== '' && class_exists($logClass)) {
  61. $log = new $logClass();
  62. $log->setMessage($message);
  63. $log->setLevel($level);
  64. $log->setChannel($channel);
  65. $em = $this->serviceContainer->get('doctrine.orm.entity_manager');
  66. $validator = $this->serviceContainer->get('validator');
  67. if ($validator->validate($log)->count() == 0) {
  68. $em->persist($log);
  69. $em->flush($log);
  70. return $log;
  71. }
  72. }
  73. return null;
  74. }
  75. }