Last active
May 5, 2021 09:10
-
-
Save Jeckerson/08be8255c541fca381d9c32713916f1c to your computer and use it in GitHub Desktop.
Model Paginator with object instead array
This file contains 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 | |
declare(strict_types=1); | |
/** | |
* Change this namespace to your and put this file whenever you want, | |
* according to your project structure. This is just example name. | |
*/ | |
namespace App\Phalcon\Paginator\Adapter; | |
use Phalcon\Helper\Arr; | |
use Phalcon\Paginator\Adapter\AbstractAdapter; | |
use Phalcon\Paginator\RepositoryInterface; | |
class Model extends AbstractAdapter | |
{ | |
/** | |
* Returns a slice of the resultset to show in the pagination | |
*/ | |
public function paginate(): RepositoryInterface | |
{ | |
$items = null; | |
$limit = (int)$this->limitRows; | |
$config = $this->config; | |
$pageNumber = (int)$this->page; | |
$modelClass = $config['model']; | |
$parameters = Arr::get($config, "parameters", [], "array"); | |
//Prevents 0 or negative page numbers | |
if ($pageNumber <= 0) { | |
$pageNumber = 1; | |
} | |
$rowcount = (int)call_user_func([$modelClass, "count"], $parameters); | |
if ($rowcount % $limit != 0) { | |
$totalPages = (int)($rowcount / $limit + 1); | |
} else { | |
$totalPages = (int)($rowcount / $limit); | |
} | |
if ($rowcount > 0) { | |
$parameters["limit"] = $limit; | |
$parameters["offset"] = $limit * ($pageNumber - 1); | |
$items = call_user_func([$modelClass, "find"], $parameters); | |
} | |
//Fix next | |
$next = $pageNumber + 1; | |
if ($next > $totalPages) { | |
$next = $totalPages; | |
} | |
if ($pageNumber > 1) { | |
$previous = $pageNumber - 1; | |
} else { | |
$previous = 1; | |
} | |
return $this->getRepository([ | |
RepositoryInterface::PROPERTY_ITEMS => $items, | |
RepositoryInterface::PROPERTY_TOTAL_ITEMS => $rowcount, | |
RepositoryInterface::PROPERTY_LIMIT => $this->limitRows, | |
RepositoryInterface::PROPERTY_FIRST_PAGE => 1, | |
RepositoryInterface::PROPERTY_PREVIOUS_PAGE => $previous, | |
RepositoryInterface::PROPERTY_CURRENT_PAGE => $pageNumber, | |
RepositoryInterface::PROPERTY_NEXT_PAGE => $next, | |
RepositoryInterface::PROPERTY_LAST_PAGE => $totalPages, | |
]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!