src/AdminBundle/Services/WebsocketNotificationService.php line 28

Open in your IDE?
  1. <?php
  2. namespace AdminBundle\Services;
  3. use AdminBundle\Entity\NotificationHistory;
  4. use AdminBundle\Entity\User;
  5. use DateTime;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use ZMQ;
  8. use ZMQContext;
  9. use ZMQSocket;
  10. class WebsocketNotificationService
  11. {
  12. /** @var EntityManagerInterface */
  13. private $em;
  14. /** @var string */
  15. private $tcpServer;
  16. /** @var string */
  17. private $port;
  18. /**
  19. * @param string $tcpServer
  20. * @param string $port
  21. */
  22. public function __construct(EntityManagerInterface $em, $tcpServer, $port)
  23. {
  24. $this->em = $em;
  25. $this->tcpServer = $tcpServer;
  26. $this->port = $port;
  27. $context = new ZMQContext();
  28. $this->socket = new ZMQSocket($context, ZMQ::SOCKET_PUSH);
  29. $this->server = "tcp://{$tcpServer}:{$port}";
  30. }
  31. /**
  32. * @param array $data
  33. */
  34. public function send($data)
  35. {
  36. $this->socket->connect($this->server);
  37. $this->socket->send(json_encode($data));
  38. $this->createHistory($data);
  39. $this->socket->disconnect("tcp://{$this->tcpServer}:{$this->port}");
  40. }
  41. /**
  42. * @param array $data
  43. */
  44. private function createHistory($data)
  45. {
  46. $user = $this->em->getRepository(User::class)->findOneByApiKey($data['apiKey']);
  47. if (!$user) {
  48. return;
  49. }
  50. $this
  51. ->em
  52. ->getRepository(NotificationHistory::class)
  53. ->insert($user->getId(), $data['data']['event'], $data, new DateTime())
  54. ;
  55. }
  56. }