NotifyVisitToMercure.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. declare(strict_types=1);
  3. namespace Shlinkio\Shlink\Core\EventDispatcher;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Psr\Log\LoggerInterface;
  6. use Shlinkio\Shlink\Core\Entity\Visit;
  7. use Shlinkio\Shlink\Core\EventDispatcher\Event\VisitLocated;
  8. use Shlinkio\Shlink\Core\Mercure\MercureUpdatesGeneratorInterface;
  9. use Symfony\Component\Mercure\PublisherInterface;
  10. use Symfony\Component\Mercure\Update;
  11. use Throwable;
  12. use function Functional\each;
  13. class NotifyVisitToMercure
  14. {
  15. private PublisherInterface $publisher;
  16. private MercureUpdatesGeneratorInterface $updatesGenerator;
  17. private EntityManagerInterface $em;
  18. private LoggerInterface $logger;
  19. public function __construct(
  20. PublisherInterface $publisher,
  21. MercureUpdatesGeneratorInterface $updatesGenerator,
  22. EntityManagerInterface $em,
  23. LoggerInterface $logger
  24. ) {
  25. $this->publisher = $publisher;
  26. $this->em = $em;
  27. $this->logger = $logger;
  28. $this->updatesGenerator = $updatesGenerator;
  29. }
  30. public function __invoke(VisitLocated $shortUrlLocated): void
  31. {
  32. $visitId = $shortUrlLocated->visitId();
  33. /** @var Visit|null $visit */
  34. $visit = $this->em->find(Visit::class, $visitId);
  35. if ($visit === null) {
  36. $this->logger->warning('Tried to notify mercure for visit with id "{visitId}", but it does not exist.', [
  37. 'visitId' => $visitId,
  38. ]);
  39. return;
  40. }
  41. try {
  42. each($this->determineUpdatesForVisit($visit), fn (Update $update) => ($this->publisher)($update));
  43. } catch (Throwable $e) {
  44. $this->logger->debug('Error while trying to notify mercure hub with new visit. {e}', [
  45. 'e' => $e,
  46. ]);
  47. }
  48. }
  49. /**
  50. * @return Update[]
  51. */
  52. private function determineUpdatesForVisit(Visit $visit): array
  53. {
  54. if ($visit->isOrphan()) {
  55. return [$this->updatesGenerator->newOrphanVisitUpdate($visit)];
  56. }
  57. return [
  58. $this->updatesGenerator->newShortUrlVisitUpdate($visit),
  59. $this->updatesGenerator->newVisitUpdate($visit),
  60. ];
  61. }
  62. }