From abd269aa78d72392278e1491bf69ec3f191eed51 Mon Sep 17 00:00:00 2001 From: Taylor Otwell Date: Wed, 20 Jul 2011 23:31:02 -0500 Subject: [PATCH] initial version of pagination library. --- system/db/query.php | 21 ++++- system/html.php | 12 +++ system/paginator.php | 220 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 252 insertions(+), 1 deletion(-) create mode 100644 system/paginator.php diff --git a/system/db/query.php b/system/db/query.php index 68aaae4e..c763c431 100644 --- a/system/db/query.php +++ b/system/db/query.php @@ -1,8 +1,8 @@ first()->aggregate; } + /** + * Get paginated query results. + * + * @param int $per_page + * @return Paginator + */ + public function paginate($per_page) + { + $total = $this->count(); + + // Reset the SELECT clause so we can execute another query to get the results. + $this->select = null; + + // Get the current page from the Paginator. The Paginator class will validate the page number. + $page = \System\Paginator::page(ceil($total / $per_page)); + + return new \System\Paginator($this->skip(($page - 1) * $per_page)->take($per_page)->get(), $total, $per_page); + } + /** * Execute an INSERT statement. * diff --git a/system/html.php b/system/html.php index b568efc5..5410d301 100644 --- a/system/html.php +++ b/system/html.php @@ -35,6 +35,18 @@ class HTML { return ''.PHP_EOL; } + /** + * Generate an HTML span tag. + * + * @param string $value + * @param array $attributes + * @return string + */ + public static function span($value, $attributes = array()) + { + return ''.static::entities($value).''; + } + /** * Generate a HTML link. * diff --git a/system/paginator.php b/system/paginator.php new file mode 100644 index 00000000..7989615e --- /dev/null +++ b/system/paginator.php @@ -0,0 +1,220 @@ +per_page = $per_page; + $this->results = $results; + $this->total = $total; + + // Validate and set the current page. If the given page is greater than the last page, the + // current page will be set to the last page. If the given page is not an integer or is less + // than 1, the current page will be set to 1. + $this->page = static::page($this->last_page()); + } + + /** + * Get the current page from the request query string. + * + * @param int $last_page + * @return int + */ + public static function page($last_page) + { + $page = Input::get('page', 1); + + if (is_numeric($page) and $page > $last_page) + { + return $last_page; + } + + return (filter_var($page, FILTER_VALIDATE_INT) === false or $page < 1) ? 1 : $page; + } + + /** + * Create the HTML pagination links. + * + * @param int $adjacent + * @return string + */ + public function links($adjacent = 3) + { + if ($this->last_page() > 1) + { + return '