<?php

require_once('db/criteria.class.phps');

class 
Query    {

    
/**
     *    SQL statement
     *    @access    private
     **/
    
var    $query;

    
/**
     *    array of criteria statements
     *    @access    private
     **/
    
var    $criteria;
    
    
/**
     *    array of order by statements
     *    @access    private
     **/
    
var    $orderby;

    
/**
     *    array of key value pairs (for insert/update statements)
     *    @access    private
     **/
    
var    $set;

    
/**
     *    Constructor
     *    @param    string query
     *    @access    public
     **/
    
    
function Query($query null)    {
        
$this->query        =    $query;
        
$this->criteria        =    array();
        
$this->orderby        =    array();
        
$this->set            =    null;
    }

    
/**
     *    set a query apart from the constructor
     *    @param    string query
     *    @access    public
     **/
    
    
function setQuery($query)    {
        
$this->query    =    $query;
    }

    
/**
     *    Add criteria to build
     *    @param    object Criteria
     *    @access    public
     **/
    
    
function addCriteria(&$Criteria)    {
        switch (
str_replace('mock'''strtolower(get_class($Criteria) ) )    ) {
            
            case 
"orderbycriteria":
                
$this->orderby[]    =&    $Criteria;
                break;
            
            case 
"setfieldscriteria":
                
$this->set    =&    $Criteria;
                break;
                
            default:
                
$this->criteria[]    =&    $Criteria;
                break;
        }
    }
    
    
/**
     *    Generate the whole SQL statement
     *    @return    string SQL statement
     *    @access    public
     **/

    
function generateSql()    {
    
//    handle SET
        
if (is_object($this->set) )    {
            
$this->query    .=    ' SET ';
            
$this->query    .=    $this->set->generateSql();
        }

    
//    handle WHERE
        
if (count($this->criteria) > 0)    {
            
$this->query    .=    ' WHERE';
        }

        foreach(
$this->criteria as $obj)    {
            
$this->query    .=    ' '.$obj->generateSql().' AND';
        }
        
        if (
substr($this->query, -3) == 'AND')    {
            
$this->query    =    substr($this->query0, -4);
        }
    
//    handle ORDER BY
        
if (count($this->orderby) > 0)    {
            
$this->query    .=    ' ORDER BY';
        }
        
        foreach(
$this->orderby as $obj)    {
            
$this->query    .=    ' '.$obj->generateSql().',';
        }
        
        if (
count($this->orderby) > 0)    {
            
$this->query    =    substr($this->query0, -1);
        }
    
//    done!
        
return $this->query;
    }

}

?>