private function _find(array $criteria = null, array $group = null, array $order = null, $limit = null, $offset = null, $countRecords = null)
{
$class = get_class($this);
$iterator = $this->getIterator();
if (is_array($criteria) && array_key_exists(static::STMT_FROM, $criteria)) {
$stmtFrom = "FROM " . $criteria[static::STMT_FROM];
unset($criteria[static::STMT_FROM]);
} else {
$stmtFrom = "FROM {$this->table()}";
}
if (is_array($criteria) && array_key_exists(static::STMT_WHERE, $criteria)) {
$stmtWhere = "WHERE " . $criteria[static::STMT_WHERE];
$rawWhere = !empty($criteria[static::STMT_WHERE]);
unset($criteria[static::STMT_WHERE]);
} else {
$stmtWhere = "WHERE";
}
if (!empty($criteria)) {
$built = $this->_buildQuery($criteria);
}
if (!empty($group)) {
$sGroup = '';
foreach ($group as $col) {
$field = $iterator->getField($col);
if (!$field) {
throw new InvalidArgumentException(sprintf("Property %s does not exist in %s", $col, $class));
}
$sGroup .= ', ' . $field->getColumnName();
}
$sGroup = $sGroup != '' ? 'GROUP BY ' . substr($sGroup, 2) : '';
}
if (!empty($order)) {
$sOrder = '';
foreach ($order as $k => $v) {
$field = $iterator->getField($k);
if (!$field) {
throw new InvalidArgumentException(sprintf("Property %s does not exist in %s", $k, $class));
}
$sOrder .= ', ' . $field->getColumnName() . ($v ? '' : ' DESC');
}
$sOrder = $sOrder != '' ? 'ORDER BY ' . substr($sOrder, 2) : '';
}
$bcnt = $countRecords && isset($limit);
$builtWhere = !empty($built['where']) ? $built['where'] : '1=1';
$stmt = "\n SELECT " . ($bcnt ? 'SQL_CALC_FOUND_ROWS ' : '') . (!empty($criteria[static::STMT_DISTINCT]) ? 'DISTINCT ' : '') . $this->fields() . " {$stmtFrom}\n {$stmtWhere} " . (!empty($rawWhere) ? "AND (" . $builtWhere . ")" : $builtWhere) . "\n " . (!empty($sOrder) ? $sOrder : "") . "\n " . (isset($limit) ? "LIMIT " . ($offset ? intval($offset) . ',' : '') . intval($limit) : "") . "\n ";
$res = $this->db()->Execute($stmt);
if ($this->resultType === self::RESULT_ENTITY_COLLECTION) {
$ret = new ArrayCollection();
while ($item = $res->FetchRow()) {
$obj = new $class();
$obj->load($item);
$ret->append($obj);
unset($obj);
}
} else {
if ($this->resultType === self::RESULT_ENTITY_ITERATOR) {
$ret = new EntityIterator($class, $res);
} else {
if ($this->resultType === self::RESULT_RAW) {
$this->resultType = self::DEFAULT_RESULT_TYPE;
return $res;
}
}
}
if ($bcnt) {
$ret->totalNumber = $this->db()->getOne('SELECT FOUND_ROWS()');
} else {
if ($countRecords) {
$ret->totalNumber = $res->RowCount();
}
}
//Restores default result type
$this->resultType = self::DEFAULT_RESULT_TYPE;
return $ret;
}