Created
December 7, 2021 11:02
-
-
Save andrewandante/bae122718aa908586a8e93badc4c8ed5 to your computer and use it in GitHub Desktop.
How to hack your pagination - a guide
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
## use statments ## | |
class PageController extends BasePageController | |
{ | |
public const PAGE_LENGTH = 10; | |
public const BIG_PAGE_LENGTH = 100; | |
public function results($data, $form, $request) | |
{ | |
$keywords = $data['Search']; | |
$service = Injector::inst()->get(AppSearchService::class); | |
$query = Injector::inst()->create(SearchQuery::class); | |
$query->setQuery($keywords); | |
$start = $request->getVar('start'); | |
// Elastic will only let you have 100 pages, so 100 pages of 10 results is the max | |
// Instead, we request in batches of 100 | |
if ($start >= 1000) { | |
$query->setPagination(self::BIG_PAGE_LENGTH, ($start / self::BIG_PAGE_LENGTH) + 1); | |
} | |
$results = null; | |
try { | |
$results = $service->search($query, $this->getElasticEngineName(), $this->getRequest()); | |
} catch (Exception $e) { | |
Injector::inst()->get(LoggerInterface::class)->error( | |
'Error calling ElasticSearch Service for Keywords in Document Library', | |
['exception' => $e] | |
); | |
} | |
$resultsList = ''; | |
if ($start >= 1000) { | |
// If we have hacked the pagination, hack it back | |
$resultsList = $results->getResults(); | |
$resultsList->setPageLength(self::PAGE_LENGTH); | |
$resultsList->setPageStart($start); | |
// Make sure we reset the underlying list with an updated offset | |
$resultsList->setList( | |
$resultsList->getList()->limit(self::PAGE_LENGTH, $start % self::BIG_PAGE_LENGTH) | |
); | |
} elseif ($results) { | |
$resultsList = $results->getResults(); | |
} | |
$this->customise( | |
[ | |
'Keywords' => $keywords, | |
'Results' => $resultsList, | |
] | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment