Ensured visits tracking is run transactionally together with the event dispatched afterwards

This commit is contained in:
Alejandro Celaya 2021-04-07 11:33:23 +02:00
parent 3a6a1f25a7
commit 0621ae7735
2 changed files with 16 additions and 5 deletions

View file

@ -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()));
});
}
}

View file

@ -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();
}