Cached result of the count query on VisitsPaginatorAdapter

This commit is contained in:
Alejandro Celaya 2020-05-03 10:44:01 +02:00
parent c4ae89a279
commit 0e4bccc4bb

View File

@ -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(),