From 0e4bccc4bbb0525bb3b3efba7b488f80160d0dd9 Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Sun, 3 May 2020 10:44:01 +0200 Subject: [PATCH] Cached result of the count query on VisitsPaginatorAdapter --- .../Paginator/Adapter/VisitsPaginatorAdapter.php | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/module/Core/src/Paginator/Adapter/VisitsPaginatorAdapter.php b/module/Core/src/Paginator/Adapter/VisitsPaginatorAdapter.php index 247ea93e..6a42ecbc 100644 --- a/module/Core/src/Paginator/Adapter/VisitsPaginatorAdapter.php +++ b/module/Core/src/Paginator/Adapter/VisitsPaginatorAdapter.php @@ -15,6 +15,8 @@ class VisitsPaginatorAdapter implements AdapterInterface private ShortUrlIdentifier $identifier; private VisitsParams $params; + private ?int $count = null; + public function __construct( VisitRepositoryInterface $visitRepository, ShortUrlIdentifier $identifier, @@ -38,7 +40,17 @@ class VisitsPaginatorAdapter implements AdapterInterface public function count(): int { - return $this->visitRepository->countVisitsByShortCode( + // Since a new adapter instance is created every time visits are fetched, it is reasonably safe to internally + // cache the count value. + // The reason it is cached is because the Paginator is actually calling the method twice. + // An inconsistent value could be returned if between the first call and the second one, a new visit is created. + // However, it's almost instant, and then the adapter instance is discarded immediately after. + + if ($this->count !== null) { + return $this->count; + } + + return $this->count = $this->visitRepository->countVisitsByShortCode( $this->identifier->shortCode(), $this->identifier->domain(), $this->params->getDateRange(),