<?php

class MCriteriaGrid extends MObjectGrid
{
    public $totalRecords;

    public function __construct($criteria, $columns, $href, $pagelength = 15, $index = 0)
    {
        parent::__construct(NULL, NULL, $href, $pagelength, $index);

        $db = $criteria->getClassMap()->getDB();
        $sql = $criteria->getSqlStatement(false);
        $countSQL = clone $sql;
        $countSQL->columns = array('count(*) as CNT');
        $queryCNT = $db->getQuery($countSQL);
        $this->totalRecords = $queryCNT->fields('CNT');

        $range = new MRange($this->pageNumber, $this->pageLength, $this->totalRecords);
        $sql->setRange($range);
        $query = $db->getQuery($sql);
        $cursor = new Cursor($query, $criteria->getClassMap(), false, $criteria->getManager());

        $this->objArray = $cursor->getObjects();
        $this->rowCount = count($this->objArray);

        $this->setColumns($columns);

    }

    public function generateData()
    {
        global $page, $state;

        if ($this->objArray == NULL)
            return;

        foreach ($this->objArray as $i => $row)
        {
            foreach ($this->columns as $k => $col)
            {
                eval("\$v = \$row->{$col->attribute};");
                // if $col->attribute is a Association and retrieveAutomatic = false
                // it is necessary to get the value explicity
                if(!$v)
                {
                    $attr = str_replace('->','.',$col->attribute);
                    $v = $row->getValue($attr);
                }
                $this->data[$i][$k] = $v;
            }
        }

        $this->orderby = $page->request('orderby');

        if ($this->ordered = isset($this->orderby))
        {
            $this->applyOrder($this->orderby);
            $state->set('orderby', $this->orderby, $this->name);
        }

        if ($this->getFiltered())
        {
            $this->applyFilter();
        }

        if ($this->pageLength)
        {
            $this->pn->setGridParameters($this->pageLength, $this->totalRecords, $this->getURL($this->filtered, $this->ordered), $this);
        }
        else
        {
            $this->pn = null;
        }
    }

}
?>