]> git.andy128k.dev Git - ipf.git/commitdiff
extract pager layout algorithm
authorAndrey Kutejko <andy128k@gmail.com>
Sun, 24 Aug 2014 16:06:22 +0000 (19:06 +0300)
committerAndrey Kutejko <andy128k@gmail.com>
Sun, 24 Aug 2014 16:06:22 +0000 (19:06 +0300)
ipf/pager.php [new file with mode: 0644]

diff --git a/ipf/pager.php b/ipf/pager.php
new file mode 100644 (file)
index 0000000..3f50ef7
--- /dev/null
@@ -0,0 +1,92 @@
+<?php
+
+class IPF_Pager_Layout
+{
+    public $rangeLength = 10;
+    public $range = 'sliding'; // or 'jumping'
+    public $arrows = true;
+
+    public function layout($page, $pages)
+    {
+        if ($pages <= 1)
+            return array();
+
+        switch ($this->range) {
+        case 'sliding':
+            $range = $this->rangeAroundPageSliding($page, $pages);
+            break;
+        case 'jumping':
+            $range = $this->rangeAroundPageJumping($page, $pages);
+            break;
+        default:
+            throw new IPF_Exception("Bad range algorithm '{$this->range}'.");
+        }
+
+        if ($this->arrows) {
+            $result = array();
+
+            if ($range[0] > 1) {
+                $result[] = 1;
+
+                if ($range[0] > 2)
+                    $result[] = 2;
+
+                if ($range[0] > 3)
+                    $result[] = null;
+            }
+
+            $result = array_merge($result, $range);
+
+            $last_range = $range[count($range)-1];
+            if ($last_range < $pages) {
+                if ($last_range < $pages - 2)
+                    $result[] = null;
+
+                if ($last_range < $pages - 1)
+                    $result[] = $pages - 1;
+
+                if ($last_range < $pages)
+                    $result[] = $pages;
+            }
+
+            return $result;
+        } else {
+            return array_merge($result, $range);
+        }
+    }
+
+    private function rangeAroundPageJumping($page, $pages)
+    {
+        // Define initial assignments for StartPage and EndPage
+        $start = $page - ($page - 1) % $this->rangeLength;
+        $end = ($start + $this->rangeLength) - 1;
+
+        // Check for EndPage out-range
+        if ($end > $pages)
+            $end = $pages;
+
+        // No need to check for out-range in start, it will never happens
+
+        return range($start, $end);
+    }
+
+    private function rangeAroundPageSliding($page, $pages)
+    {
+        if ($this->rangeLength > $pages)
+            return range(1, $pages);
+
+        $start = $page - floor($this->rangeLength / 2);
+        $end   = $page + ceil($this->rangeLength / 2) - 1;
+
+        if ($start < 1) {
+            $start = 1;
+            $end = $this->rangeLength - 1;
+        } elseif ($end > $pages) {
+            $start = $pages - $this->rangeLength + 1;
+            $end = $pages;
+        }
+
+        return range($start, $end);
+    }
+}
+