123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- <?php
- namespace WorkflowBundle\Services;
- use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
- use PhpAmqpLib\Message\AMQPMessage;
- use Symfony\Component\DependencyInjection\ContainerInterface;
- class LogConsumer implements ConsumerInterface
- {
- /**
- * @var ContainerInterface
- */
- protected $serviceContainer;
- /**
- * @param ContainerInterface $serviceContainer
- */
- public function __construct(ContainerInterface $serviceContainer)
- {
- $this->serviceContainer = $serviceContainer;
- }
- /**
- * $msg will be an instance of `PhpAmqpLib\Message\AMQPMessage`
- * with the $msg->body being the data sent over RabbitMQ.
- *
- * @param AMQPMessage $msg
- */
- public function execute(AMQPMessage $msg)
- {
- $fields = [];
- $logClass = 'LogBundle\Entity\Log';
- try {
- $msgBody = json_decode($msg->body, true);
- $json_error = json_last_error();
- if (!$json_error) {
- // se hace un date format previo
- $msgBody['datetime'] = date('Y-m-d H:i:s', strtotime($msgBody['datetime']['date']));
- $fields['message'] = $this->serviceContainer->get('monolog_line_formatter')->format($msgBody);
- if (isset($msgBody['context']['deviceId']) && isset($msgBody['context']['deviceType'])) {
- $logClass = 'LogBundle\Entity\DeviceLog';
- $fields['deviceId'] = $msgBody['context']['deviceId'];
- $fields['deviceType'] = $msgBody['context']['deviceType'];
- }
- } else {
- $fields['message'] = "Error json: {$json_error}";
- }
- } catch (\Exception $ex) {
- $fields['message'] = $ex->getMessage();
- }
-
- $log = $this->createLog($fields, $logClass);
- if (is_null($log)) {
- var_dump('Error: log no creado');
- } else {
- var_dump(sprintf("ID: %s Message: %s", $log->getId(), $log->getMessage()));
- }
-
- return;
- }
-
- /**
- * Crea una entidad Log y la persiste
- *
- * @param array $fields
- * @param string $logClass
- *
- * @return \WorkflowBundle\Services\LogBundle\Entity\Log
- */
- private function createLog($fields, $logClass = 'LogBundle\Entity\Log')
- {
- if (class_exists($logClass)) {
- $em = $this->serviceContainer->get('doctrine.orm.entity_manager');
-
- $log = new $logClass();
- $log->setMessage($fields['message']);
- if (isset($fields['deviceId']) && isset($fields['deviceType'])) {
- $device = $em->getRepository('LicenseBundle:Device')->findOneBy([
- 'deviceId' => $fields['deviceId'],
- 'deviceType' => $fields['deviceType'],
- ]);
- $log->setDevice($device);
- }
- $validator = $this->serviceContainer->get('validator');
- if ($validator->validate($log)->count() == 0) {
- $em->persist($log);
- $em->flush($log);
- return $log;
- }
- }
-
- return null;
- }
- }
|