|
- <?php
-
- namespace App\Knockout;
-
- use Illuminate\Http\Request;
-
- class Dataset
- {
-
- private $records = [];
-
- private $totalRecords = null;
- private $currentPage = null;
- private $recordsPerPage = null;
-
- public function __serialize(): array
- {
- return [
- 'records' => $this->records,
- 'totalRecords' => $this->totalRecords,
- 'currentPage' => $this->currentPage,
- 'recordsPerPage' => $this->recordsPerPage
- ];
- }
-
- public function __unserialize(array $data): void
- {
- $this->records = $data['records'] ?? [];
- $this->totalRecords = $data['totalRecords'] ?? null;
- $this->currentPage = $data['currentPage'] ?? null;
- $this->recordsPerPage = $data['recordsPerPage'] ?? null;
- }
-
- public function __construct($records)
- {
- if (!is_array($records)) $records = [$records];
- $this->records = $records;
- }
-
- public function setTotalRecords(int $total)
- {
- $this->totalRecords = $total;
- return $this;
- }
-
- public function setCurrentPage(int $page)
- {
- $this->currentPage = $page;
- return $this;
- }
-
- public function setRecordsPerPage(int $count)
- {
- $this->recordsPerPage = $count;
- return $this;
- }
-
- public function getRecords()
- {
- return $this->records;
- }
-
- public function getRecord()
- {
- return $this->records[0] ?? null;
- }
-
- private function getPageCount()
- {
- $exactPages = ($this->totalRecords / $this->recordsPerPage);
- $pages = ceil($exactPages);
- $pages = ($pages == $exactPages) ? floor($exactPages) : $pages;
- return ($pages < 1) ? 1 : $pages;
- }
-
- private function queryParams(array $query)
- {
- $output = [];
- foreach ($query as $key => $item) {
- $output[] = sprintf('%s=%s', $key, urlencode($item));
- }
- return '?' . implode('&', $output);
- }
-
- public function getPaginator(Request $request)
- {
- if (is_null($this->totalRecords)) return null;
- if (is_null($this->currentPage)) return null;
- if (is_null($this->recordsPerPage)) return null;
-
- $route = $request->route();
- $query = $request->query();
- $alias = $route[1]['as'] ?? 'index';
- $params = $route[2] ?? [];
-
- $pages = array_map(function($page) use($alias, $params, $query) {
- $currentPage = $params['page'] ?? 1;
- return (object) [
- 'number' => $page,
- 'active' => ($page == $currentPage),
- 'link' => route($alias, array_merge($params, ['page' => $page])) //. $this->queryParams($query)
- ];
- }, range(1, $this->getPageCount()));
-
- return view('partial/paginator', [
- 'pages' => $pages
- ]);
- }
-
- }
|