Advertisement
LucianoCharles2017

Class Pagination

May 24th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 9.81 KB | None | 0 0
  1. <?php
  2.  
  3. /*
  4.  * Class Pagination
  5.  *
  6.  * @author Luciano Charles de Souza
  7.  * E-mail: souzacomprog@gmail.com
  8.  * Github: https://github.com/LucianoCharlesdeSouza
  9.  * YouTube: https://www.youtube.com/channel/UC2bpyhuQp3hWLb8rwb269ew?view_as=subscriber
  10.  */
  11.  
  12. class Pagination
  13. {
  14.  
  15.     private $pdo;
  16.     private $indexPage  = 0;
  17.     private $links      = '';
  18.     private $maxPage    = 2;
  19.     private $maxLinks   = 2;
  20.     private $places     = [];
  21.     private $page       = 'page';
  22.     private $query      = '';
  23.     private $queryCount = null;
  24.  
  25.  
  26.     public function __construct(\PDO $pdo)
  27.     {
  28.       $this->pdo = $pdo;
  29.     }
  30.     /**
  31.      * Método que recebe o valor máximo de registros por página
  32.      * @param $max int
  33.      * @throws Exception
  34.      */
  35.     public function maxPerPage($max)
  36.     {
  37.         if (!is_int($max) || !is_numeric($max)) {
  38.             throw new Exception("Passe um valor inteiro para o máximo de registro por páginas!");
  39.         }
  40.         $this->maxPage = (int) $max;
  41.     }
  42.  
  43.     /**
  44.      * Método que recebe o nome do page
  45.      * @param $namePage string
  46.      * @throws Exception
  47.      */
  48.     public function page($namePage)
  49.     {
  50.         if (!is_string($namePage)) {
  51.             throw new Exception("O nome do paginador deve ser tipo string!");
  52.         }
  53.         $this->page = (string) $namePage;
  54.     }
  55.  
  56.     /**
  57.      * Método que recebe o valor máximo de links visiveis a esquerda e direita
  58.      * @param $maxlinks int
  59.      * @throws Exception
  60.      */
  61.     public function maxLinks($maxlinks)
  62.     {
  63.         if (!is_int($maxlinks) || !is_numeric($maxlinks)) {
  64.             throw new Exception("Passe um valor para o máximo de links!");
  65.         }
  66.         $this->maxLinks = (int) $maxlinks;
  67.     }
  68.  
  69.     /**
  70.      * Método que retorna
  71.      * os itens para a paginação
  72.      * @return array
  73.      */
  74.     public function paginate($where = null)
  75.     {
  76.         $Query = "SELECT DISTINCT * FROM {$this->table} {$where}";
  77.         $this->getIndexPage();
  78.         $this->query .= $Query . " LIMIT " . $this->indexPage . "," . $this->maxPage;
  79.         return $this->fullSql($this->query, $this->places);
  80.     }
  81.  
  82.     /**
  83.      * Método que recebe uma string SQL para retornar
  84.      * os itens para a paginação
  85.      * @param $Query string
  86.      * @return array
  87.      */
  88.     public function createPagination($Query)
  89.     {
  90.         $this->getIndexPage();
  91.         $this->query .= $Query . " LIMIT " . $this->indexPage . "," . $this->maxPage;
  92.         return $this->fullSql($this->query, $this->places);
  93.     }
  94.  
  95.     /**
  96.      * Método que recebe um array para usar como substitutos no Bind
  97.      * @param array $placesValues
  98.      */
  99.     public function bindValues(array $placesValues)
  100.     {
  101.         $this->places = $placesValues;
  102.     }
  103.  
  104.     /**
  105.      * Método que gera os links de paginação
  106.      * @return string
  107.      */
  108.     public function createLinks()
  109.     {
  110.         $this->pagingNumberExceeded();
  111.         if ($this->totalRecords() > $this->maxPage) {
  112.             $this->firstLink();
  113.             $this->previousLink();
  114.             $this->currentLink();
  115.             $this->nextLink();
  116.             $this->lastLink();
  117.         }
  118.         return $this->links;
  119.     }
  120.  
  121.     /**
  122.      * Método que recebe o valor atual da paginação
  123.      * @return int|string
  124.      */
  125.     private function getPager()
  126.     {
  127.         $pager = filter_input(INPUT_GET, $this->page);
  128.         return (isset($pager) ? (int) $pager : $pager . 1);
  129.     }
  130.  
  131.     /**
  132.      * Método que recebe objeto PDO mais o array Places,
  133.      * gerando os Bind's
  134.      * @param $stmt
  135.      * @param null $Fields array
  136.      */
  137.     private function createBind($stmt, $Fields = null)
  138.     {
  139.         if ($Fields != null) {
  140.             foreach ($Fields as $key => $value) {
  141.                 $stmt->bindValue(":$key", $value);
  142.             }
  143.         }
  144.     }
  145.  
  146.     private function debugueParamns($stmt)
  147.     {
  148.        echo '<pre>';
  149.        return var_dump($stmt->debugDumpParams());
  150.     }
  151.  
  152.     /**
  153.      * Método que recebe uma string SQL,
  154.      * podendo ou não receber também um array para as substituições
  155.      * no Bind
  156.      * @param $Query string
  157.      * @param array|null $Fields
  158.      * @return array
  159.      */
  160.     private function fullSql($Query, array $Fields = null)
  161.     {
  162.         try {
  163.             $sql = strtolower($Query);
  164.  
  165.             $update = (strpos($sql, "update") !== false) ? true : false;
  166.             $delete = (strpos($sql, "delete") !== false) ? true : false;
  167.             $insert = (strpos($sql, "insert") !== false) ? true : false;
  168.  
  169.             $stmt = $this->pdo->prepare($Query);
  170.             $this->createBind($stmt, $Fields);
  171.             $stmt->execute();
  172.  
  173.             if ($update) {
  174.                 return true;
  175.             }
  176.  
  177.             if ($delete) {
  178.                 return true;
  179.             }
  180.  
  181.             if ($insert) {
  182.                 return true;
  183.             }
  184.  
  185.             if ($stmt->rowCount() > 0) {
  186.                 return $stmt->fetchAll();
  187.             }
  188.  
  189.             return false;
  190.         } catch (\PDOException $e) {
  191.             die($e->getMessage());
  192.         }
  193.     }
  194.  
  195.     /**
  196.      * Método que retorna o número da página
  197.      * @return int
  198.      */
  199.     private function getIndexPage()
  200.     {
  201.         if ((($this->maxPage * $this->getPager()) - $this->maxPage) > 0) {
  202.             return $this->indexPage = (($this->maxPage * $this->getPager()) - $this->maxPage);
  203.         }
  204.         return $this->indexPage = 0;
  205.     }
  206.  
  207.     /**
  208.      * Método que retorna a quantidade de registros da consulta,
  209.      * que é usada para auxiliar na lágica da paginação
  210.      * @return mixed
  211.      */
  212.     private function totalRecords()
  213.     {
  214.         $sql = str_replace(" LIMIT " . $this->indexPage . "," . $this->maxPage, '', $this->query);
  215.         $total = ($this->fullSql($sql, $this->places)) ? count($this->fullSql($sql, $this->places)) : 0;
  216.         return $total;
  217.     }
  218.  
  219.     /**
  220.      * Método que retorna o total de páginas que terá a paginação
  221.      * @return float
  222.      */
  223.     private function totalPages()
  224.     {
  225.         return ceil($this->totalRecords() / $this->maxPage);
  226.     }
  227.  
  228.     /**
  229.      * Método que fará o redirecionamento sempre para a última página,
  230.      * caso o usuário passe uma valor não existente de forma manual na url
  231.      */
  232.     private function pagingNumberExceeded()
  233.     {
  234.         if (($this->getPager() > $this->totalPages() || $this->getPager() < 1) && $this->totalRecords() != 0) {
  235.             header("Location: " . $this->ReturnPageValid($this->page) . "?" . $this->page . "=" . $this->totalPages());
  236.         }
  237.     }
  238.  
  239.     /**
  240.      * Método que gera o html para o primeiro item da paginação
  241.      */
  242.     private function firstLink()
  243.     {
  244.         $this->links .= "<div class=\"col-sm-12 text-center\"><ul class=\"pagination\">";
  245.         $first = "<li class=\"page-item\"><a class=\"page-link\" href = \"?" . $this->page . "=1\">&laquo;</a></li>";
  246.         $this->links .= $first;
  247.     }
  248.  
  249.     /**
  250.      * Método que gera o html para o item anterior da paginação atual
  251.      */
  252.     private function previousLink()
  253.     {
  254.         for ($i = $this->getPager() - $this->maxLinks; $i <= $this->getPager() - 1; $i++) {
  255.             if ($i >= 1) {
  256.                 $this->links .= "<li class=\"page-item\"><a class=\"page-link\" href=\"?" . $this->page . "=" . $i . "\">" . $i . "</a></li>";
  257.             }
  258.         }
  259.     }
  260.  
  261.     /**
  262.      * Método que gera o html para o item atual da paginação
  263.      */
  264.     private function currentLink()
  265.     {
  266.         $this->links .= "<li class=\"page-item active\"><a class=\"page-link\" href='#'>" . $this->getPager() . " <span class=\"sr-only\">(current)</span></a></li>";
  267.     }
  268.  
  269.     /**
  270.      * Método que gera o html para o próximo item da paginação atual
  271.      */
  272.     private function nextLink()
  273.     {
  274.         for ($i = $this->getPager() + 1; $i <= $this->getPager() + $this->maxLinks; $i++) {
  275.             if ($i <= $this->totalPages()) {
  276.                 $this->links .= "<li class=\"page-item\"><a class=\"page-link\" href=\"?" . $this->page . "=" . $i . "\">" . $i . "</a></li>";
  277.             }
  278.         }
  279.     }
  280.  
  281.     /**
  282.      * Método que gera o html para o último item da paginação
  283.      */
  284.     private function lastLink()
  285.     {
  286.         $last = "<li class=\"page-item\"><a class=\"page-link\" href=\"?" . $this->page . "=" . $this->totalPages() . "\">&raquo;</a></li></ul></div>";
  287.         $this->links .= $last;
  288.     }
  289.  
  290.     /**
  291.      * Método que retorna a url com o nome do page, porem sem o valor da paginação
  292.      * @param $namePager
  293.      * @return bool|string
  294.      */
  295.     private function ReturnPageValid($namePager)
  296.     {
  297.         $URL = filter_input(INPUT_SERVER, 'HTTP_HOST');
  298.         $url = "http://" . $URL . filter_input(INPUT_SERVER, 'REQUEST_URI');
  299.         $https = filter_input(INPUT_SERVER, 'HTTPS');
  300.         if (isset($https) && $https == 'on') {
  301.             $url = "https://" . $URL . filter_input(INPUT_SERVER, 'REQUEST_URI');
  302.         }
  303.         return substr($url, 0, strpos($url, "?" . $namePager));
  304.     }
  305.  
  306. }
  307.  
  308.  
  309.  
  310.  
  311. USO DA CLASSE
  312.  
  313.     //Objeto PDO para ser injetado no construtor da classe Pagination
  314.     $pdo = ConnPDO::getInstance();
  315.  
  316.     require('Pagination.php');
  317.     $pagination = new Pagination($pdo);
  318.         try {
  319.             $listagem = $pagination->CreatePagination("SELECT * FROM menu");
  320.             $links = $pagination->CreateLinks();
  321.         } catch (Exception $e) {
  322.             die($e->getMessage());
  323.         }
  324.         /* Aqui em listagem voce pode criar uma tabela em html e extrair os dados nesta tabela */
  325.         echo "<pre>";
  326.         var_dump($listagem);
  327.         echo "<pre>";
  328.  
  329.         echo $links;
  330.  
  331.  
  332.  
  333.  
  334. Se herdares esta classe, poderas colocar um atributo pretected $table = 'nome_da_tabela_no_banco';
  335. para poder usar o metodo paginate para paginações simples
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement