Created
July 12, 2013 21:47
-
-
Save attitude/5988120 to your computer and use it in GitHub Desktop.
Generate {{mustache}} ready data for pagination
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 | |
/** | |
* Returns {{mustache}} ready data for pagination | |
* | |
* Pagination array for `prev`, `next`, `start`, `end` and `jump` | |
* to direct pages | |
* | |
* @author Martin Adamko <@martin_adamko> | |
* @licence The MIT Licence <http://opensource.org/licenses/MIT> | |
* | |
* @param array $args Settings | |
* @returns array Pagination data | |
* | |
*/ | |
function get_pagination_data(array $args=array()) | |
{ | |
$defaults = array( | |
'page' => 1, | |
'total' => null, | |
'perpage' => null, | |
'type' => 'paginate', | |
'radius' => 5, | |
'uri' => $_SERVER['REQUEST_URI'], | |
'key' => 'page' | |
); | |
// Remove undefined | |
foreach ($args as $k => &$v) { | |
if (empty($v)) { | |
unset($args[$k]); | |
} | |
} | |
$args = array_merge($defaults, $args); | |
extract($args, EXTR_SKIP); | |
// There is no pagination if... | |
if ((int) $total<1 || (int) $page<1 || (int) $perpage<1 || (int) $total <= (int) $perpage) { | |
return array(); | |
} | |
// Shorthand | |
$p =& $page; | |
// Total pages | |
$pages = ceil($total/$perpage); | |
$pagination = array( | |
'current' => $p, | |
'total' => $total, | |
); | |
if (($p-1) > 0) { | |
$pagination['prev'] = array( 'link' => remove_query_arg($key, $uri)); | |
if ($p-1>1) { | |
$pagination['start'] = array( 'link' => remove_query_arg($key, $uri)); | |
} | |
} | |
if ($p+1 <= ceil($total/$perpage)) { | |
$pagination['next'] = array( 'link' => add_query_arg($key, $p+1, $uri)); | |
if ($p+1<$pages) { | |
$pagination['end'] = array( 'link' => add_query_arg($key, $pages, $uri)); | |
} | |
} | |
$p_start = $p- (($radius-1)/2); | |
$p_end = $p_start+($radius-1); | |
while($p_start <= 0) { | |
$p_start++; | |
$p_end++; | |
} | |
while($p_end > $pages) { | |
$p_end--; | |
if($p_start > 1) { | |
$p_start--; | |
} | |
} | |
for( $i = $p_start; $i <= $p_end; $i++) { | |
$active = $i==$p ? true : false; | |
$pagination['jump'][] = array( 'link' => ($i===1) ? remove_query_arg($key, $uri) : add_query_arg($key, $i, $uri), 'text'=>$i, 'active' => $active ); | |
} | |
return $pagination; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment