<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
	<channel>
		<title><![CDATA[Hoa Forum - Hoathis_Pagination]]></title>
		<link>http://forum.hoa-project.net/topic/328/hoathispagination/</link>
		<description><![CDATA[Le post le plus récent sur Hoathis_Pagination.]]></description>
		<lastBuildDate>Thu, 04 Feb 2010 17:43:04 +0000</lastBuildDate>
		<generator>PunBB</generator>
		<item>
			<title><![CDATA[Re : Hoathis_Pagination]]></title>
			<link>http://forum.hoa-project.net/post/1950/#p1950</link>
			<description><![CDATA[Il reste encore quelques espaces à ajouter par-ci par-là, mais ça reste du détail (et je me retiens, car il paraît que je peux vite devenir insupportable … [i]dixit[/i] mes binômes rescapés). Tu peux aussi supprimer des lignes vides : par exemple à la fin }\n\n\n}, tu peux sûrement toutes les virer ;).

L'avantage d'avoir ta propre classe exception est pour les utilisateurs. Ils sauront exactement d'où vient l'exception. Ça peut être très pratique pour débugger :).]]></description>
			<author><![CDATA[dummy@example.com (Hywan)]]></author>
			<pubDate>Thu, 04 Feb 2010 17:43:04 +0000</pubDate>
			<guid>http://forum.hoa-project.net/post/1950/#p1950</guid>
		</item>
		<item>
			<title><![CDATA[Re : Hoathis_Pagination]]></title>
			<link>http://forum.hoa-project.net/post/1949/#p1949</link>
			<description><![CDATA[Hop me revoilà avec la dernière version du bazard!

Les améliorations:
[list=*]
[*]Gestion des paramètres via Hoa_Framework_Parameterizable
(Et du coup ajout de la branche attr.* pour ajouter autant d'attributs html que l'on souhaite)[/*]
[*]Aération du code + réindentation propre[/*]
[*]Correction de quelques fautes :-°[/*]
[/list]
Reste à peaufiner:[list=*]
[*]La gestion des erreurs...
Pour l'instant les exeptions lancées sont de type Exception et non pas Hoa_Exception, pourquoi pas aller jusqu'a Hoathis_Pagination_Exception, quel est l'interet?[/*]
[*]Uniformiser les commentaires, peut-être repasser à l'anglais?[/*]
[*]What else?[/*]
[/list]

Voilà la classe revue:[code]<?php

/**
 * Hoa Framework
 *
 *
 * @license
 *
 * GNU General Public License
 *
 * This file is part of HOA Open Accessibility.
 * Copyright (c) 2007, 2008 Ivan ENDERLIN. All rights reserved.
 *
 * HOA Open Accessibility is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * HOA Open Accessibility is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with HOA Open Accessibility; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *
 * @category    Framework
 * @package     Hoa_Framework
 *
 */

/**
 * Hoa_Framework
 */
require_once 'Framework.php';

/**
 * Hoa_Database
 */
import('Database.Dal.~');

/**
 * Hoathis_Pagination_Exception
 */
importModule('Pagination.Exception');

/**
 * Class Hoathis_Pagination
 *
 * @author      joris MULLIEZ <joris.mulliez@gmail.com>
 * @license     http://gnu.org/licenses/gpl.txt GNU GPL
 * @since       PHP 5
 * @version     0.1
 * @package     Hoathis_Pagination
 */
class Hoathis_Pagination implements Hoa_Framework_Parameterizable {

    /**
     * Instance d'Hoa_Database
     */
    private $db = null;


    /**
     * Hoathis_Pagination::__construct
     *
     * Initialise les variables
     *
     * @access public
     * @param  array      $arguments    tableau contenant les différents arguments : 
     *         'sql'            requête de sélection (Sans clause LIMIT)
     *        'sqlcount'         requête de comptage
     *         'nbresults'        Si nombre de résultats connus, remplace sqlcount
     *         'nbelmts'        Nombre d'éléments par pages
     *         'attr.*'         Attributs des liens <a>
     *         'page'            Page courante (paramètre get ou encore
     *                           valeur par défaut pour le JS)
     *        'nbpagesgrpes'    Nombre de page par groupement de page
     *                           ex si = 2:
     *                           1 2 3 ... 5 6 [7] 8 9 ... 15 16 17
     *         'prefix'          Texte de début de la pagination
     *         'elipse'           Caractères affichés pour les ellipses
     *         'needpagi1'        Indique si on affiche la pagination lorsqu'il
     *                         n'y a qu'une seule page
     *         'arroundcurrentpage'
     *                         Code html pour habiller la page courante
     *                         ex: <b>%d</b>
     *         'separator'        séparateurs de pages
     *
     * @return none
     */
    public function __construct( $parameters = array() ){
        
        // Récupération de l'instance de connexion
        if($this->db === null) {
            
            $this->db = Hoa_Database_Dal::getLastInstance();
            
            // A garder ou non selon la configuration serveur
            $this->db->query("SET NAMES 'utf8'");
        }
        
        
        $this->_parameters = new Hoa_Framework_Parameter(
            $this,
            array(),
            array(
                'sql'                     => null,
                'sqlcount'                 => null,
                'nbresults'                => null,
                'nbelmts'                => 10,
                'page'                    => isset($_GET['page']) ? (int)$_GET['page'] : 1,
                'prefix'                => 'Page(s) :',
                'needpagi1'             => false,
                'nbpagesgrpes'            => 2,
                'elipse'                => '...',
                'attr.href'                => null,
                'attr.title'            => 'Aller à la page %d',
                'arroundcurrentpage'    => '<b>%d</b>',
                'separator'                => ' | '
                
            )
        );
        
        // Initialisation des paramètres
        $this->setParameters($parameters);
        
        // récupération des paramètres
        $params = $this->getParameters();
        
        // Requête d'affichage (obligatoire)
        if( $params['sql'] === null ){
            
            throw new Exception('You have to give an sql request');
        }
        
        
        // Requête de comptage ou résultat directement (obligatoire)
        if( $params['sqlcount'] === null ) {
            
            if( $params['nbresults'] === null){
                
                throw new Exception('You have to give a counting sql 
                    request    or directly the number of results');
            }
        }
        else {
            
            $this->setParameter(
                'nbresults',
                $this->queryCount()
            );
        }
    
        $attr=$this->unlinearizeBranche('attr');
    
        if($attr['href'] === null){
            
            $this->setParameter(
                'attr.href',
                $this->buildUrl()
            );
        }
        

    }
    
    /**
     * Hoathis_Pagination::buildUrl
     *
     * Retourne l'url de la page avec tous les arguments formatés pour
     * le sprintf à venir (ie ajout du page=%d)
     *
     * @access private
     * @param  none
     * @return string    L'url utilisée dans la méthode Hoathis_Pagination::navi
     */
    private function buildUrl() {
                
        $args = '';
        
        foreach($_GET as $key=>$val) {
            
          if($key!=='page') {
              
            $args .= (!empty($args) ? '&':'') . $key . '=' . urlencode($val);
          }
        }
        
        return PUBLIC_URL.'/index.php?'.$args.'&page=%d';
    }

    /**
     * Hoathis_Pagination::queryCount
     *
     * Retourne le nombre de résultats avec la requête de comptage
     *
     * @access private
     * @param  none
     * @return int    Result of 'sqlcount'
     */
    private function queryCount() {
        
        $sqlcount = $this->getParameter('sqlcount'); 
          
        try {
            
            $statement         = $this->db->query( $sqlcount );
            list($results)     = $statement->fetchAll();
            
        }
        catch ( Hoa_Database_Dal_Exception $e ) {
         
            $statement->closeCursor();
        }
        
        return (int)reset($results);
    }

    /**
     * Hoathis_Pagination::navi
     *
     * Produit le code html de navigation
     *
     * @access   public
     * @param    none
     * @return   string  Le code html de la barre de navigation
     */
    public function navi() {
        
        $params     = $this->getParameters();
        
        // Nombre de pages nécessaires
        $nbPages    = ceil($params['nbresults']/$params['nbelmts']);
        

        // Construction des attributs
        $attrHtml     = array();
        $attr        = $this->unlinearizeBranche('attr');

        foreach($attr as $key=>$value){
            
            $attrHtml[] = htmlspecialchars($key).'="'.htmlspecialchars($value).'"';
        }
        
        // Un seul paramètre sera passé à sprintf, on nomme donc les arguments
        $attrHtml = str_replace('%d','%1$d',implode(' ',$attrHtml));
        
        
        // S'il y a au moins une page à afficher
        if($nbPages >= 1) {
            
            // Contiendra chaque élément de la navigation
            $navi = array();
        
            //si la page demandée n'existe pas, alors on blance une exeption
            if($params['page'] > $nbPages) {
              
                throw new Exception('This page ('.$params['page'].') does\'nt exist...');
            }
            elseif($params['page'] < 0) {
              
                throw new Exception('This page ('.$params['page'].') does\'nt exist...');
            }
        
            // S'il y a plus d'une page
            if($nbPages > 1) {
              
                // Pages précédentes
                for($i=1; $i<$params['page']; $i++) {
                
                    $navi[] = '<a '.sprintf($attrHtml,$i).' >'.$i.'</a>';
            
                    // Si on arrive à l'ellipse
                    if( 
                        $params['nbpagesgrpes'] == $i && 
                        ($params['page']-$i) > ($params['nbpagesgrpes']+1)
                    ) {
                      
                        $navi[] = $params['elipse'];
                        
                        // On sort de la boucle
                        $i = $params['page'] - $params['nbpagesgrpes'] - 1;
                    }
                }
        
                //page en cours
                if($params['page'] > 0) {
                
                    $navi[] = sprintf($params['arroundcurrentpage'],$params['page']);
                }
        
                // Pages suivantes
                for( $j=($params['page']+1); $j<=$nbPages; $j++ ) {
                    
                    $navi[] = '<a '.sprintf($attrHtml,$j).' >'.$j.'</a>';
        
                    // Si on arrive à l'ellipse
                    if(
                        ($params['nbpagesgrpes'] + $params['page']) == $j
                        && ($nbPages-$j) > $params['nbpagesgrpes']
                    ) {
                        
                        $navi[] = $params['elipse'];
                        
                        // On sort de la boucle
                        $j = $nbPages-$params['nbpagesgrpes'];
                    }
                }
        
            }
            // Une seule page, on ne fait pas de traitement
            else {
                if ($params['needpagi1'] == true) {
                    
                    $navi[] = sprintf($params['arroundcurrentpage'],1);
                }
            }
          
            // Formatage final
            $navi = $params['prefix'].' '.implode($params['separator'],$navi);
        }
        // Pas de résultats
        else {
            $navi='';
        }
        
        return $navi;
    }
    
    /**
     * Hoathis_Pagination::query
     *
     * Execute la requète avec le limit, et renvoi une resource
     *
     * @access   public
     * @param    none
     * @return   mixed    Hoa_Database_Dal_DalStatement  or false when 
     *                     errors occurs
     */
    public function query(){
        
        
        $params = $this->getParameters();
        
        $limit=    " LIMIT ".( ($params['page']-1) * $params['nbelmts'] ).
                ",".$params['nbelmts'];
        
        try {
            
            $statement = $this->db->query( $params['sql'].$limit );
            return $statement;
            
        }
        catch ( Hoa_Database_Dal_Exception $e ) {

            echo $e;
            $statement->closeCursor();
            return false;
        }
        
    }

    /*
     * 
     * Fonctions à implémenter pour Hoa_Framework_Parameterizable
     * 
     */


    /**
     * Set many parameters to a class.
     *
     * @access  public
     * @param   array   $in    Parameters to set.
     * @return  void
     * @throw   Hoa_Exception
     */
    public function setParameters ( Array $in ) {

        return $this->_parameters->setParameters($this, $in);
    }

    /**
     * Get many parameters from a class.
     *
     * @access  public
     * @return  array
     * @throw   Hoa_Exception
     */
    public function getParameters ( ) {

        return $this->_parameters->getParameters($this);
    }

    /**
     * Set a parameter to a class.
     *
     * @access  public
     * @param   string  $key      Key.
     * @param   mixed   $value    Value.
     * @return  mixed
     * @throw   Hoa_Exception
     */
    public function setParameter ( $key, $value ) {

        return $this->_parameters->setParameter($this, $key, $value);
    }

    /**
     * Get a parameter from a class.
     *
     * @access  public
     * @param   string  $key    Key.
     * @return  mixed
     * @throw   Hoa_Exception
     */
    public function getParameter ( $key ) {

        return $this->_parameters->getParameter($this, $key);
    }

    /**
     * Get a formatted parameter from a class (i.e. zFormat with keywords and
     * other parameters).
     *
     * @access  public
     * @param   string  $key    Key.
     * @return  mixed
     * @throw   Hoa_Exception
     */
    public function getFormattedParameter ( $key ) {

        return $this->_parameters->getFormattedParameter($this, $key);
    }
    
    /**
     * Unlinearize a branche to an array.
     *
     * @access  public
     * @param   string  $branche    Branche.
     * @return  array
     */
    public function unlinearizeBranche($branche){
        
        return $this->_parameters->unlinearizeBranche($this,$branche);
    }


}
[/code]

Oups il semblerait que le forum me bouffe quelque alignements... :/]]></description>
			<author><![CDATA[dummy@example.com (jojolapine)]]></author>
			<pubDate>Thu, 04 Feb 2010 17:09:38 +0000</pubDate>
			<guid>http://forum.hoa-project.net/post/1949/#p1949</guid>
		</item>
		<item>
			<title><![CDATA[Re : Hoathis_Pagination]]></title>
			<link>http://forum.hoa-project.net/post/1948/#p1948</link>
			<description><![CDATA[Huhu, comme quoi c'est pratique aussi pour ça :P.]]></description>
			<author><![CDATA[dummy@example.com (Hywan)]]></author>
			<pubDate>Thu, 04 Feb 2010 14:28:12 +0000</pubDate>
			<guid>http://forum.hoa-project.net/post/1948/#p1948</guid>
		</item>
		<item>
			<title><![CDATA[Re : Hoathis_Pagination]]></title>
			<link>http://forum.hoa-project.net/post/1947/#p1947</link>
			<description><![CDATA[Et non :) j'ai eu l'info via ton twitter :)]]></description>
			<author><![CDATA[dummy@example.com (jojolapine)]]></author>
			<pubDate>Thu, 04 Feb 2010 14:17:57 +0000</pubDate>
			<guid>http://forum.hoa-project.net/post/1947/#p1947</guid>
		</item>
		<item>
			<title><![CDATA[Re : Hoathis_Pagination]]></title>
			<link>http://forum.hoa-project.net/post/1946/#p1946</link>
			<description><![CDATA[Tu reçois les notifications par mail maintenant ?]]></description>
			<author><![CDATA[dummy@example.com (Hywan)]]></author>
			<pubDate>Thu, 04 Feb 2010 13:49:10 +0000</pubDate>
			<guid>http://forum.hoa-project.net/post/1946/#p1946</guid>
		</item>
		<item>
			<title><![CDATA[Re : Hoathis_Pagination]]></title>
			<link>http://forum.hoa-project.net/post/1945/#p1945</link>
			<description><![CDATA[Yeah!!!!! :)
Je test ça ce soir ;)
Merci merci :)]]></description>
			<author><![CDATA[dummy@example.com (jojolapine)]]></author>
			<pubDate>Thu, 04 Feb 2010 13:45:45 +0000</pubDate>
			<guid>http://forum.hoa-project.net/post/1945/#p1945</guid>
		</item>
		<item>
			<title><![CDATA[Re : Hoathis_Pagination]]></title>
			<link>http://forum.hoa-project.net/post/1944/#p1944</link>
			<description><![CDATA[C'est tout bon, c'est corrigé. Depuis 9h ce matin que j'y suis …
J'ai repensé complètement l'analyse (avec un [i]callback[/i]). Bref, ça marche, et il n'y a plus de bidouille (j'en avais ajouté une pour Tetardo, mais maintenant c'est uniformisé).

On applaudira donc [url=http://svn-view.hoa-project.net/view?view=revision&revision=656]la révision 656[/url] ;).

Édition : plus besoin de [i]blackslashes[/i] n'y rien du tout, tout fonctionne bien :).]]></description>
			<author><![CDATA[dummy@example.com (Hywan)]]></author>
			<pubDate>Thu, 04 Feb 2010 13:14:02 +0000</pubDate>
			<guid>http://forum.hoa-project.net/post/1944/#p1944</guid>
		</item>
		<item>
			<title><![CDATA[Re : Hoathis_Pagination]]></title>
			<link>http://forum.hoa-project.net/post/1943/#p1943</link>
			<description><![CDATA[C'est le principe du bug en général ^^.]]></description>
			<author><![CDATA[dummy@example.com (Hywan)]]></author>
			<pubDate>Wed, 03 Feb 2010 23:19:41 +0000</pubDate>
			<guid>http://forum.hoa-project.net/post/1943/#p1943</guid>
		</item>
		<item>
			<title><![CDATA[Re : Hoathis_Pagination]]></title>
			<link>http://forum.hoa-project.net/post/1942/#p1942</link>
			<description><![CDATA[Te bile pas pour ce soir ;)
de toute façon, moi je vais au lit, donc j'en profiterais pas :)
Et demain, ça sera pas avant 18h que je m'y remettrais (pis bon dans l'absolu, je peux avancer sur d'autres plans, c'est juste que ça m'énerve de bloquer sur un bug sur lequel je n'ai aucun pouvoir!!!! :( )]]></description>
			<author><![CDATA[dummy@example.com (jojolapine)]]></author>
			<pubDate>Wed, 03 Feb 2010 23:18:53 +0000</pubDate>
			<guid>http://forum.hoa-project.net/post/1942/#p1942</guid>
		</item>
		<item>
			<title><![CDATA[Re : Hoathis_Pagination]]></title>
			<link>http://forum.hoa-project.net/post/1941/#p1941</link>
			<description><![CDATA[Je vais corriger ça soit cette nuit, ça demain matin (je vais essayer de dormir au moins 2h).]]></description>
			<author><![CDATA[dummy@example.com (Hywan)]]></author>
			<pubDate>Wed, 03 Feb 2010 23:14:52 +0000</pubDate>
			<guid>http://forum.hoa-project.net/post/1941/#p1941</guid>
		</item>
		<item>
			<title><![CDATA[Re : Hoathis_Pagination]]></title>
			<link>http://forum.hoa-project.net/post/1940/#p1940</link>
			<description><![CDATA[Et je ne parle pas de références arrière dans mon post de tout à l'heure, mais du fait de pouvoir dire:
[quote]parenthèse non précédée d'un backslash[/quote]
et [code][^\]([/code]ne semble pas vouloir marcher!]]></description>
			<author><![CDATA[dummy@example.com (jojolapine)]]></author>
			<pubDate>Wed, 03 Feb 2010 23:13:35 +0000</pubDate>
			<guid>http://forum.hoa-project.net/post/1940/#p1940</guid>
		</item>
		<item>
			<title><![CDATA[Re : Hoathis_Pagination]]></title>
			<link>http://forum.hoa-project.net/post/1939/#p1939</link>
			<description><![CDATA[Ben m'amuser, j'en sais rien... c'est juste que j'aimerais que mon histoire fonctionne!
Qui plus est c'est pas vraiment une utilisation extraordinaire des paramètres, du coup ça serais cool que ça ne bug plus...
Le zFormat n'est aps encore au point :/
Ou alors il faudrait prévoir une méthode zFormat_quote() ...]]></description>
			<author><![CDATA[dummy@example.com (jojolapine)]]></author>
			<pubDate>Wed, 03 Feb 2010 23:09:23 +0000</pubDate>
			<guid>http://forum.hoa-project.net/post/1939/#p1939</guid>
		</item>
		<item>
			<title><![CDATA[Re : Hoathis_Pagination]]></title>
			<link>http://forum.hoa-project.net/post/1938/#p1938</link>
			<description><![CDATA[Si tu veux t'amuser avec les caractères précédentes, regarde dans Hoa_Console_Core_Cli_Parser ;).]]></description>
			<author><![CDATA[dummy@example.com (Hywan)]]></author>
			<pubDate>Wed, 03 Feb 2010 22:52:57 +0000</pubDate>
			<guid>http://forum.hoa-project.net/post/1938/#p1938</guid>
		</item>
		<item>
			<title><![CDATA[Re : Hoathis_Pagination]]></title>
			<link>http://forum.hoa-project.net/post/1937/#p1937</link>
			<description><![CDATA[Oué, j'ai beau essayer de comprendre, et de modifier cette regexp... :/
Dans l'idéal il faudrait rajouter un truc genre:[code]|
    ([^\(]+)?
    (?:
        (?:
            [^\\]?\(:(.*?):\)      # où on indique que le caractère précédent (s'il y en a un) ne doit pas être un backslash
        )|
        (?:
            [^\\]\(:(.*?)[^\\]\)   # idem ici, pour la parenthèse ouvrante et fermante
        )
    )?
|[/code]
Mais bon ça marche pô :/]]></description>
			<author><![CDATA[dummy@example.com (jojolapine)]]></author>
			<pubDate>Wed, 03 Feb 2010 21:24:13 +0000</pubDate>
			<guid>http://forum.hoa-project.net/post/1937/#p1937</guid>
		</item>
		<item>
			<title><![CDATA[Re : Hoathis_Pagination]]></title>
			<link>http://forum.hoa-project.net/post/1936/#p1936</link>
			<description><![CDATA[Je regarderai cette nuit, je n'ai pas le temps maintenant, désolé :(.]]></description>
			<author><![CDATA[dummy@example.com (Hywan)]]></author>
			<pubDate>Wed, 03 Feb 2010 20:52:15 +0000</pubDate>
			<guid>http://forum.hoa-project.net/post/1936/#p1936</guid>
		</item>
	</channel>
</rss>

