1515use App \Entity \Tag ;
1616use Doctrine \Bundle \DoctrineBundle \Repository \ServiceEntityRepository ;
1717use 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 ;
2120
2221/**
2322 * This custom Doctrine repository contains some methods which are useful when
@@ -36,31 +35,23 @@ public function __construct(ManagerRegistry $registry)
3635 parent ::__construct ($ registry , Post::class);
3736 }
3837
39- public function findLatest (int $ page = 1 , Tag $ tag = null ): Pagerfanta
38+ public function findLatest (int $ page = 1 , Tag $ tag = null ): array
4039 {
4140 $ qb = $ this ->createQueryBuilder ('p ' )
4241 ->addSelect ('a ' , 't ' )
4342 ->innerJoin ('p.author ' , 'a ' )
4443 ->leftJoin ('p.tags ' , 't ' )
4544 ->where ('p.publishedAt <= :now ' )
4645 ->orderBy ('p.publishedAt ' , 'DESC ' )
47- ->setParameter ('now ' , new \DateTime ());
46+ ->setParameter ('now ' , new \DateTime ())
47+ ;
4848
4949 if (null !== $ tag ) {
5050 $ qb ->andWhere (':tag MEMBER OF p.tags ' )
5151 ->setParameter ('tag ' , $ tag );
5252 }
5353
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 );
6455 }
6556
6657 /**
@@ -110,4 +101,31 @@ private function extractSearchTerms(string $searchQuery): array
110101 return 2 <= mb_strlen ($ term );
111102 });
112103 }
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+ }
113131}
0 commit comments