15
15
use App \Entity \Tag ;
16
16
use Doctrine \Bundle \DoctrineBundle \Repository \ServiceEntityRepository ;
17
17
use Doctrine \Common \Persistence \ManagerRegistry ;
18
- use Doctrine \ORM \Query ;
19
- use Pagerfanta \Adapter \DoctrineORMAdapter ;
20
- use Pagerfanta \Pagerfanta ;
18
+ use Doctrine \ORM \QueryBuilder ;
19
+ use Doctrine \ORM \Tools \Pagination \Paginator ;
21
20
22
21
/**
23
22
* This custom Doctrine repository contains some methods which are useful when
@@ -36,31 +35,23 @@ public function __construct(ManagerRegistry $registry)
36
35
parent ::__construct ($ registry , Post::class);
37
36
}
38
37
39
- public function findLatest (int $ page = 1 , Tag $ tag = null ): Pagerfanta
38
+ public function findLatest (int $ page = 1 , Tag $ tag = null ): array
40
39
{
41
40
$ qb = $ this ->createQueryBuilder ('p ' )
42
41
->addSelect ('a ' , 't ' )
43
42
->innerJoin ('p.author ' , 'a ' )
44
43
->leftJoin ('p.tags ' , 't ' )
45
44
->where ('p.publishedAt <= :now ' )
46
45
->orderBy ('p.publishedAt ' , 'DESC ' )
47
- ->setParameter ('now ' , new \DateTime ());
46
+ ->setParameter ('now ' , new \DateTime ())
47
+ ;
48
48
49
49
if (null !== $ tag ) {
50
50
$ qb ->andWhere (':tag MEMBER OF p.tags ' )
51
51
->setParameter ('tag ' , $ tag );
52
52
}
53
53
54
- return $ this ->createPaginator ($ qb ->getQuery (), $ page );
55
- }
56
-
57
- private function createPaginator (Query $ query , int $ page ): Pagerfanta
58
- {
59
- $ paginator = new Pagerfanta (new DoctrineORMAdapter ($ query ));
60
- $ paginator ->setMaxPerPage (Post::NUM_ITEMS );
61
- $ paginator ->setCurrentPage ($ page );
62
-
63
- return $ paginator ;
54
+ return $ this ->createPaginator ($ qb , $ page );
64
55
}
65
56
66
57
/**
@@ -110,4 +101,31 @@ private function extractSearchTerms(string $searchQuery): array
110
101
return 2 <= mb_strlen ($ term );
111
102
});
112
103
}
104
+
105
+ private function createPaginator (QueryBuilder $ queryBuilder , int $ currentPage , int $ pageSize = Post::NUM_ITEMS )
106
+ {
107
+ $ currentPage = $ currentPage < 1 ? 1 : $ currentPage ;
108
+ $ firstResult = ($ currentPage - 1 ) * $ pageSize ;
109
+
110
+ $ query = $ queryBuilder
111
+ ->setFirstResult ($ firstResult )
112
+ ->setMaxResults ($ pageSize )
113
+ ->getQuery ();
114
+
115
+ $ paginator = new Paginator ($ query );
116
+ $ numResults = $ paginator ->count ();
117
+ $ hasPreviousPage = $ currentPage > 1 ;
118
+ $ hasNextPage = ($ currentPage * $ pageSize ) < $ numResults ;
119
+
120
+ return [
121
+ 'results ' => $ paginator ->getIterator (),
122
+ 'currentPage ' => $ currentPage ,
123
+ 'hasPreviousPage ' => $ hasPreviousPage ,
124
+ 'hasNextPage ' => $ hasNextPage ,
125
+ 'previousPage ' => $ hasPreviousPage ? $ currentPage - 1 : null ,
126
+ 'nextPage ' => $ hasNextPage ? $ currentPage + 1 : null ,
127
+ 'numPages ' => (int ) ceil ($ numResults / $ pageSize ),
128
+ 'haveToPaginate ' => $ numResults > $ pageSize ,
129
+ ];
130
+ }
113
131
}
0 commit comments