From 877a609724ec7cfb76ba8a575c9d6973a5df932f Mon Sep 17 00:00:00 2001 From: Will Rossiter Date: Wed, 7 Feb 2024 16:25:27 +1300 Subject: [PATCH] feat: better paginated results --- src/PaginatedList.php | 61 +++++++++++++++++++++++++++---------------- src/ResultList.php | 1 + 2 files changed, 40 insertions(+), 22 deletions(-) diff --git a/src/PaginatedList.php b/src/PaginatedList.php index 9af899e..ceb9c8d 100644 --- a/src/PaginatedList.php +++ b/src/PaginatedList.php @@ -2,51 +2,68 @@ namespace Heyday\Elastica; +use SilverStripe\Control\HTTPRequest; +use \SilverStripe\ORM\PaginatedList as SilverStripePaginatedList; /** * Class PaginatedList * * @package Heyday\Elastica */ -class PaginatedList extends \SilverStripe\ORM\PaginatedList +class PaginatedList extends SilverStripePaginatedList { - protected $list; + protected $resultList; - public function __construct(ResultList $list, $request = []) + public function __construct(ResultList $resultList, $request = []) { + $this->resultList = $resultList; $this->setRequest($request); - $this->list = $list; + + $start = 0; + + if ($request instanceof HTTPRequest) { + if ($request->getVar('start') !== null) { + $start = (int) $request->getVar('start'); + } + } + + $this->list = $resultList->limit($this->getPageLength(), $start)->toArrayList(); + + $list = new SilverStripePaginatedList($this->list, $request); + + parent::__construct($list, $request); + + $this->setTotalItems($resultList->getTotalItems()); + $this->setPageStart($this->getPageStart()); + $this->setLimitItems(false); } - /** - * Use the ResultList's total items method to determine this value - * - * @return int - */ - public function getTotalItems() + public function setPageStart($start) { - if ($this->list instanceof ResultList) { - return $this->list->getTotalItems(); - } + $this->list = $this->resultList->limit($this->getPageLength(), $start)->toArrayList(); - return parent::getTotalItems(); + return $this; } - public function FirstItem() + public function setPageLength($length) { - if ($this->list instanceof ResultList) { - return $this->list->getFirstItem(); - } + $this->setPageLength($length); + $this->list = $this->resultList->limit($length, $this->getPageStart())->toArrayList(); - return parent::getTotalItems(); + return $this; } - public function LastItem() + /** + * Use the ResultList's total items method to determine this value + * + * @return int + */ + public function getTotalItems() { - if ($this->list instanceof ResultList) { - return $this->list->getLastItem(); + if ($this->resultList instanceof ResultList) { + return $this->resultList->getTotalItems(); } return parent::getTotalItems(); diff --git a/src/ResultList.php b/src/ResultList.php index a7c3466..e36e330 100644 --- a/src/ResultList.php +++ b/src/ResultList.php @@ -297,6 +297,7 @@ public function getFirstItem() try { $from = $this->getQuery()->getParam('from'); } catch (Exception $e) { + dd($e); $from = 1; }