diff --git a/module/Core/src/Visit/VisitsTracker.php b/module/Core/src/Visit/VisitsTracker.php index 306da7a9..f8c82b49 100644 --- a/module/Core/src/Visit/VisitsTracker.php +++ b/module/Core/src/Visit/VisitsTracker.php @@ -65,9 +65,11 @@ class VisitsTracker implements VisitsTrackerInterface private function trackVisit(Visit $visit, Visitor $visitor): void { - $this->em->persist($visit); - $this->em->flush(); + $this->em->transactional(function () use ($visit, $visitor): void { + $this->em->persist($visit); + $this->em->flush(); - $this->eventDispatcher->dispatch(new UrlVisited($visit->getId(), $visitor->getRemoteAddress())); + $this->eventDispatcher->dispatch(new UrlVisited($visit->getId(), $visitor->getRemoteAddress())); + }); } } diff --git a/module/Core/test/Visit/VisitsTrackerTest.php b/module/Core/test/Visit/VisitsTrackerTest.php index 118ebc06..bba4e919 100644 --- a/module/Core/test/Visit/VisitsTrackerTest.php +++ b/module/Core/test/Visit/VisitsTrackerTest.php @@ -29,6 +29,11 @@ class VisitsTrackerTest extends TestCase public function setUp(): void { $this->em = $this->prophesize(EntityManager::class); + $this->em->transactional(Argument::any())->will(function (array $args) { + [$callback] = $args; + return $callback(); + }); + $this->eventDispatcher = $this->prophesize(EventDispatcherInterface::class); $this->options = new UrlShortenerOptions(); @@ -41,11 +46,14 @@ class VisitsTrackerTest extends TestCase */ public function trackPersistsVisitAndDispatchesEvent(string $method, array $args): void { - $this->em->persist(Argument::that(fn (Visit $visit) => $visit->setId('1')))->shouldBeCalledOnce(); - $this->em->flush()->shouldBeCalledOnce(); + $persist = $this->em->persist(Argument::that(fn (Visit $visit) => $visit->setId('1')))->will(function (): void { + }); $this->visitsTracker->{$method}(...$args); + $persist->shouldHaveBeenCalledOnce(); + $this->em->transactional(Argument::cetera())->shouldHaveBeenCalledOnce(); + $this->em->flush()->shouldHaveBeenCalledOnce(); $this->eventDispatcher->dispatch(Argument::type(UrlVisited::class))->shouldHaveBeenCalled(); } @@ -68,6 +76,7 @@ class VisitsTrackerTest extends TestCase $this->visitsTracker->{$method}(Visitor::emptyInstance()); $this->eventDispatcher->dispatch(Argument::cetera())->shouldNotHaveBeenCalled(); + $this->em->transactional(Argument::cetera())->shouldNotHaveBeenCalled(); $this->em->persist(Argument::cetera())->shouldNotHaveBeenCalled(); $this->em->flush()->shouldNotHaveBeenCalled(); }