Skip to content

Commit

Permalink
MicroblogRepository.forPage() returns count
Browse files Browse the repository at this point in the history
  • Loading branch information
danon committed Dec 6, 2023
1 parent 7c951c7 commit 5413c52
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public function countForUser($userId);
* @param int $pageNumber
* @return Microblog[]
*/
public function forPage(int $pageSize, int $pageNumber);
public function forPage(int $pageSize, int $pageNumber): array;

/**
* @param int|null $userId
Expand Down
24 changes: 12 additions & 12 deletions app/Repositories/Eloquent/MicroblogRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,19 @@ public function paginate($perPage = null, $columns = ['*'], $pageName = 'page',
/**
* @inheritDoc
*/
public function forPage(int $pageSize, int $pageNumber)
public function forPage(int $pageSize, int $pageNumber): array
{
return $this->applyCriteria(function () use ($pageSize, $pageNumber) {
return $this->model
$query = $this->model
->newQuery()
->whereNull('parent_id')
->with(['user', 'assets', 'tags'])
->withCount('comments')
->withCount('comments');
$count = $query->count();
$paginatedQuery = $query
->limit($pageSize)
->offset(\max(0, $pageNumber - 1) * $pageSize)
->get();
->offset(\max(0, $pageNumber - 1) * $pageSize);
return [$paginatedQuery->get(), $count];
});
}

Expand All @@ -64,21 +66,19 @@ public function popular(int $pageSize, int $pageNumber): array
{
$this->applyCriteria();
try {
$query = $this
->model
$query = $this->model
->newQuery()
->whereNull('parent_id')
->with(['user', 'assets', 'tags'])
->withCount('comments')
->where(fn(Builder $query) => $query
->where('votes', '>=', 1)
->where('votes', '>=', 0)
->orWhere('is_sponsored', true));
$count = $query->count();
$fetched = $query
$pagedQuery = $query
->limit($pageSize)
->offset(\max(0, $pageNumber - 1) * $pageSize)
->get();
return [$fetched, $count];
->offset(\max(0, $pageNumber - 1) * $pageSize);
return [$pagedQuery->get(), $count];
} finally {
$this->resetModel();
}
Expand Down
4 changes: 2 additions & 2 deletions app/Services/Microblogs/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,11 @@ public function withTag(string $tag): self

public function paginate(): LengthAwarePaginator
{
$count = (int)$this->microblog->applyCriteria(fn() => $this->microblog->count());
$page = LengthAwarePaginator::resolveCurrentPage();
$this->loadUserScope();
[$items, $count] = $this->microblog->forPage(10, $page);
$paginator = new LengthAwarePaginator(
$this->microblog->forPage(10, $page),
$items,
$count,
10,
$page,
Expand Down

0 comments on commit 5413c52

Please sign in to comment.