Refactoring. Add SqlResultProvider. Add TODO in SqlDbDriver.whereExpr().
This commit is contained in:
@ -2,44 +2,50 @@
|
|||||||
|
|
||||||
class SqlCriteria
|
class SqlCriteria
|
||||||
{
|
{
|
||||||
public $select = '*';
|
private $select = array();
|
||||||
|
|
||||||
public $distinct = '';
|
private $distinct = '';
|
||||||
|
|
||||||
public $where = array();
|
private $where = array();
|
||||||
|
|
||||||
public $order = array();
|
private $order = array('sort' => array(), 'order' => array());
|
||||||
|
|
||||||
public $limit = '';
|
private $limit = '';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return SqlCriteria
|
* @var SqlModel
|
||||||
*/
|
*/
|
||||||
public static function getInstance()
|
private $model;
|
||||||
|
|
||||||
|
public function find()
|
||||||
{
|
{
|
||||||
return self;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param $conditions array @ex array('field=?' => $value, 'field in ? => new DbExpr('(1,2,3)'))
|
* @param $cond string Condition with "?" placeholder @ex 'field=?'
|
||||||
|
* @param $value string|array|DbExpr Value. Array transformed to DbExpr(implode(',' Array)) All elements in the array mast be integer
|
||||||
* @return SqlCriteria
|
* @return SqlCriteria
|
||||||
|
* @desc Allow multiple calls
|
||||||
*/
|
*/
|
||||||
public function where($conditions)
|
public function where($cond, $value)
|
||||||
{
|
{
|
||||||
$this->where = $conditions;
|
$this->where[$cond] = $value;
|
||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param $fields array @ex array('field1', 'field2' => SqlModel::ORDER_DESC)
|
* @param $field string Field @ex 'field'
|
||||||
|
* @param $order_desc bool Descendant sort direction
|
||||||
* @return SqlCriteria
|
* @return SqlCriteria
|
||||||
|
* @desc Allow multiple calls
|
||||||
*/
|
*/
|
||||||
public function order($fields)
|
public function order($field, $order_desc = false)
|
||||||
{
|
{
|
||||||
if (!is_array($fields)) {
|
$this->order['sort'][] = $field;
|
||||||
$fields = array($fields);
|
if ($order_desc) {
|
||||||
|
$this->order['order'][$field] = 'desc';
|
||||||
}
|
}
|
||||||
$this->order = $fields;
|
|
||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -50,23 +56,20 @@ class SqlCriteria
|
|||||||
*/
|
*/
|
||||||
public function limit($limit, $offset = 0)
|
public function limit($limit, $offset = 0)
|
||||||
{
|
{
|
||||||
if (empty($offset)) {
|
if ($offset) {
|
||||||
$this->limit = (int) $limit;
|
$this->limit = (int) $offset . ',';
|
||||||
}
|
}
|
||||||
$this->limit = (int)$limit . ',' . (int) $offset;
|
$this->limit .= (int) $limit;
|
||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param mixed $select array @ex array('field1', 'field2', 'field3' => 'field')
|
* @param string $field
|
||||||
* @return string
|
* @return SqlCriteria
|
||||||
*/
|
*/
|
||||||
public function select($select)
|
public function select($field)
|
||||||
{
|
{
|
||||||
if (!is_array($select)) {
|
$this->select[] = $field;
|
||||||
$select = array($select);
|
|
||||||
}
|
|
||||||
$this->select = $select;
|
|
||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -127,6 +127,7 @@ abstract class SqlDbDriver extends DbDriver
|
|||||||
/**
|
/**
|
||||||
* @param mixed $where
|
* @param mixed $where
|
||||||
* @return string
|
* @return string
|
||||||
|
* TODO: Если cond Это int и term Это тоже int - кидать Exception (иначе эта ошибка повлечет обновление всех записей в таблице
|
||||||
*/
|
*/
|
||||||
protected function whereExpr($where)
|
protected function whereExpr($where)
|
||||||
{
|
{
|
||||||
|
@ -15,29 +15,6 @@
|
|||||||
*/
|
*/
|
||||||
abstract class SqlModel extends Model
|
abstract class SqlModel extends Model
|
||||||
{
|
{
|
||||||
const SELECT = 10;
|
|
||||||
const DISTINCT = 11;
|
|
||||||
const WHERE = 12;
|
|
||||||
const ORDER = 13;
|
|
||||||
const LIMIT = 15;
|
|
||||||
const OFFSET = 16;
|
|
||||||
|
|
||||||
const ORDER_DESC = 20;
|
|
||||||
const ORDER_ASC = 21;
|
|
||||||
|
|
||||||
const ASSOC_BY_FIELD = 30;
|
|
||||||
const ASSOC_AS_ARRAY = 31;
|
|
||||||
const ASSOC_BY_FIELD_IN_ARRAY = 32;
|
|
||||||
|
|
||||||
protected static $criteria_data_keys = array(
|
|
||||||
self::SELECT,
|
|
||||||
self::DISTINCT,
|
|
||||||
self::WHERE,
|
|
||||||
self::ORDER,
|
|
||||||
self::LIMIT,
|
|
||||||
/** self::OFFSET // that key no to be a process in foreach criteria_data @see SqlModel::find() */
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param string $ident
|
* @param string $ident
|
||||||
* @return string Quoted identifier.
|
* @return string Quoted identifier.
|
||||||
@ -100,9 +77,21 @@ abstract class SqlModel extends Model
|
|||||||
{
|
{
|
||||||
$sql = '';
|
$sql = '';
|
||||||
if (isset($params['sort'])) {
|
if (isset($params['sort'])) {
|
||||||
$order = (isset($params['order']) && $params['order'] == 'desc') ? 'DESC' : 'ASC';
|
if (!is_array($params['sort'])) {
|
||||||
if (in_array($params['sort'], $sortable)) {
|
if (isset($params['order'])) {
|
||||||
$sql = ' ORDER BY ' . $this->identify($params['sort']) . ' ' . $order;
|
$params['order'] = array($params['sort'] => $params['order']);
|
||||||
|
}
|
||||||
|
$params['sort'] = array($params['sort']);
|
||||||
|
}
|
||||||
|
$order_list = array();
|
||||||
|
for ($i = 0; $i < count($params['sort']); $i++) {
|
||||||
|
$order = (isset($params['order'][$params['sort'][$i]]) && $params['order'][$params['sort'][$i]] == 'desc') ? 'DESC' : 'ASC';
|
||||||
|
if (in_array($params['sort'][$i], $sortable)) {
|
||||||
|
$order_list[] = $this->identify($params['sort'][$i]) . ' ' . $order;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($order_list) {
|
||||||
|
$sql = ' ORDER BY ' . implode(',', $order_list);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return $sql;
|
return $sql;
|
||||||
@ -200,16 +189,13 @@ abstract class SqlModel extends Model
|
|||||||
return $result;
|
return $result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @param $criteria SqlCriteria
|
public function find($select, $distinct, $where, $order, $limit)
|
||||||
* @return string Sql string expression
|
|
||||||
*/
|
|
||||||
protected function criteria($criteria)
|
|
||||||
{
|
{
|
||||||
if (!is_array($criteria->select)) {
|
if (!$select) {
|
||||||
$criteria->select = array(new DbExpr($criteria->select));
|
$select = array(new DbExpr('*'));
|
||||||
}
|
}
|
||||||
foreach ($criteria->select as $field => &$term) {
|
foreach ($select as $field => &$term) {
|
||||||
if (is_int($field)) {
|
if (is_int($field)) {
|
||||||
if ($term instanceof DbExpr) {
|
if ($term instanceof DbExpr) {
|
||||||
$term = (string) $term;
|
$term = (string) $term;
|
||||||
@ -220,158 +206,31 @@ abstract class SqlModel extends Model
|
|||||||
$term = $this->db->quoteIdentifier($field) . ' as ' . $this->db->quoteIdentifier($term);
|
$term = $this->db->quoteIdentifier($field) . ' as ' . $this->db->quoteIdentifier($term);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
foreach ($criteria->where as $cond => &$term) {
|
foreach ($where as $cond => &$term) {
|
||||||
if (is_int($cond)) {
|
if (is_array($term)) {
|
||||||
if ($term instanceof DbExpr) {
|
$term = new DbExpr('(' . implode(',', array_map(function($item){return intval($item);}, $term)) . ')');
|
||||||
$term = (string) $term;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (is_array($term)) {
|
|
||||||
$term = new DbExpr('(' . implode(',', array_map(function($item){return intval($item);}, $term)) . ')');
|
|
||||||
}
|
|
||||||
$term = $this->db->quoteInto($cond, $term);
|
|
||||||
}
|
}
|
||||||
|
$term = $this->db->quoteInto($cond, $term);
|
||||||
}
|
}
|
||||||
foreach ($criteria->order as $field => $term) {
|
if ($distinct != '') {
|
||||||
if (is_int($field)) {
|
$distinct = 'DISTINCT ' . $this->db->quoteIdentifier($distinct);
|
||||||
$term = $this->db->quoteIdentifier($term);
|
|
||||||
} else {
|
|
||||||
$order_direction = '';
|
|
||||||
switch ($term) {
|
|
||||||
case self::ORDER_DESC:
|
|
||||||
$order_direction .= ' DESC';
|
|
||||||
break;
|
|
||||||
case self::ORDER_ASC:
|
|
||||||
$order_direction .= ' ASC';
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
$term = $this->db->quoteIdentifier($field) . $order_direction;
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if ($criteria->distinct != '') {
|
if ($limit != '') {
|
||||||
$criteria->distinct = 'DISTINCT ' . $this->db->quoteIdentifier($criteria->distinct);
|
$limit = implode(',',array_map(function($item){return intval($item);},explode(',',$limit)));
|
||||||
}
|
}
|
||||||
if ($criteria->limit != '') {
|
$result_items = parent::fetchAll('SELECT ' . (($distinct) ? $distinct : implode(',', $select))
|
||||||
$criteria->limit = implode(',',array_map(function($item){return intval($item);},explode(',',$criteria->limit)));
|
. ' FROM ' . $this->table()
|
||||||
}
|
. (($where) ? (' WHERE ' . implode(' AND ', $where)) : '')
|
||||||
return 'SELECT ' . (($criteria->distinct) ? $criteria->distinct : implode(',', $criteria->select))
|
. (($order) ? ($this->order($order, $order['sort'])) : '')
|
||||||
. ' FROM ' . $this->table()
|
. (($limit) ? (' LIMIT ' . $limit) : ''));
|
||||||
. (($criteria->where) ? (' WHERE ' . implode(' AND ', $criteria->where)) : '')
|
return new SqlResultProvider($result_items);
|
||||||
. (($criteria->order) ? (' ORDER BY ' . implode(',', $criteria->order)) : '')
|
|
||||||
. (($criteria->limit) ? (' LIMIT ' . $criteria->limit) : '');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param $criteria_data array
|
* @return SqlCriteria
|
||||||
* @ex array(
|
|
||||||
* SqlModel::SELECT => '*',
|
|
||||||
* SqlModel::WHERE => array('field=?', 1),
|
|
||||||
* SqlModel::ORDER => array('last_name', 'first_name' => SqlModel::ORDER_DESC),
|
|
||||||
* SqlModel::LIMIT => 10)
|
|
||||||
* @return mixed|DbStatement[]
|
|
||||||
*/
|
*/
|
||||||
public function find($criteria_data)
|
public function criteria()
|
||||||
{
|
{
|
||||||
$criteria = new SqlCriteria();
|
return new SqlCriteria();
|
||||||
foreach (self::$criteria_data_keys as $criteria_data_key) {
|
|
||||||
if (isset($criteria_data[$criteria_data_key])) {
|
|
||||||
$value = $criteria_data[$criteria_data_key];
|
|
||||||
switch ($criteria_data_key) {
|
|
||||||
case self::SELECT:
|
|
||||||
$criteria->select($value);
|
|
||||||
break;
|
|
||||||
case self::DISTINCT:
|
|
||||||
$criteria->distinct($value);
|
|
||||||
break;
|
|
||||||
case self::WHERE:
|
|
||||||
$criteria->where($value);
|
|
||||||
break;
|
|
||||||
case self::ORDER:
|
|
||||||
$criteria->order($value);
|
|
||||||
break;
|
|
||||||
case self::LIMIT:
|
|
||||||
$criteria->limit($value, ((isset($criteria_data[self::OFFSET])) ? $criteria_data[self::OFFSET] : null));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$data = $this->criteria($criteria);
|
|
||||||
if (isset($criteria_data[self::ASSOC_BY_FIELD])) {
|
|
||||||
return self::fetchAllAssocByField($data, array(), $criteria_data[self::ASSOC_BY_FIELD], ((isset($criteria_data[self::ASSOC_AS_ARRAY])) ? $criteria_data[self::ASSOC_AS_ARRAY] : false), ((isset($criteria_data[self::ASSOC_BY_FIELD_IN_ARRAY])) ? $criteria_data[self::ASSOC_BY_FIELD_IN_ARRAY] : null));
|
|
||||||
} else {
|
|
||||||
return self::fetchAll($data);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param $data string
|
|
||||||
* @param $params array
|
|
||||||
* @param null|string $field
|
|
||||||
* @param bool $assoc_as_array
|
|
||||||
* @param null|string $field_assoc_in_array
|
|
||||||
* @return array
|
|
||||||
* @throws ErrorException|GeneralException
|
|
||||||
*/
|
|
||||||
protected function fetchAllAssocByField($data, $params, $field = null, $assoc_as_array = false, $field_assoc_in_array = null)
|
|
||||||
{
|
|
||||||
$items = self::fetchAll($data, $params);
|
|
||||||
if (is_null($field)) {
|
|
||||||
$field = $this->key;
|
|
||||||
}
|
|
||||||
return self::assocByField($items, $field, $assoc_as_array, $field_assoc_in_array);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param $items
|
|
||||||
* @param $field
|
|
||||||
* @param bool $assoc_as_array
|
|
||||||
* @param $field_assoc_in_array null|string
|
|
||||||
* @param $disable_assoc_in_array bool
|
|
||||||
* @return array
|
|
||||||
* @throws ErrorException|GeneralException
|
|
||||||
*/
|
|
||||||
public function assocByField($items, $field, $assoc_as_array = false, $field_assoc_in_array = null, $disable_assoc_in_array = false)
|
|
||||||
{
|
|
||||||
$items_assoc_by_field = array();
|
|
||||||
$primary_key_not_exists_in_items = false;
|
|
||||||
foreach ($items as $item) {
|
|
||||||
if (!isset($item->{$field})) {
|
|
||||||
throw new GeneralException('Undefined field. ' . $field);
|
|
||||||
}
|
|
||||||
if ($assoc_as_array) {
|
|
||||||
if (!isset($items_assoc_by_field[$item->{$field}])) {
|
|
||||||
$items_assoc_by_field[$item->{$field}] = array();
|
|
||||||
}
|
|
||||||
$items_assoc_by_field[$item->{$field}][] = $item;
|
|
||||||
if (!$primary_key_not_exists_in_items && $this->key && !isset($item->{$this->key})) {
|
|
||||||
$primary_key_not_exists_in_items = true;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (isset($items_assoc_by_field[$item->{$field}])) {
|
|
||||||
throw new ErrorException('Field not unique. May be use assoc_as_array. ' . $field);
|
|
||||||
}
|
|
||||||
$items_assoc_by_field[$item->{$field}] = $item;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Ассоциирование внутри каждого элемента массива по первичному ключу
|
|
||||||
// Если первичного ключа нет (не указан в модели или нет поля с первичным ключом в результах выборки) - ассоциирование внутри не производится
|
|
||||||
// Если указан $field_assoc_in_array - ассоциирование произовдится по этому полю (вернет ошибку, если этого поля нет в результатх выборки)
|
|
||||||
// Параметр $disable_assoc_in_array отключает ассоциирование внутри результирующего массива
|
|
||||||
if ($assoc_as_array && !$disable_assoc_in_array &&
|
|
||||||
(($this->key && !$primary_key_not_exists_in_items) || $field_assoc_in_array)
|
|
||||||
) {
|
|
||||||
foreach ($items_assoc_by_field as $key => $value) {
|
|
||||||
$items_assoc_by_field[$key] = self::assocByField($items_assoc_by_field[$key], (($field_assoc_in_array) ? $field_assoc_in_array : $this->key));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return $items_assoc_by_field;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function assocByFieldAndGetKeys($items, $field)
|
|
||||||
{
|
|
||||||
$items = self::assocByField($items, $field, true, null, true);
|
|
||||||
return array_keys($items);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
73
model/SqlResultProvider.php
Normal file
73
model/SqlResultProvider.php
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
class SqlResultProvider
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
private $result_items;
|
||||||
|
|
||||||
|
private $result_items_base;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param $result_items array
|
||||||
|
*/
|
||||||
|
public function __construct($result_items)
|
||||||
|
{
|
||||||
|
$this->result_items = $result_items;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function assoc($field, $assoc_as_array = false, $field_assoc_in_array = null)
|
||||||
|
{
|
||||||
|
if (is_null($this->result_items_base)) {
|
||||||
|
$this->result_items_base = $this->result_items;
|
||||||
|
}
|
||||||
|
$result_items_assoc = array();
|
||||||
|
foreach ($this->result_items_base as $item) {
|
||||||
|
if (!isset($item->{$field})) {
|
||||||
|
throw new ErrorException('Undefined field. ' . $field);
|
||||||
|
}
|
||||||
|
if ($assoc_as_array) {
|
||||||
|
if (!isset($result_items_assoc[$item->{$field}])) {
|
||||||
|
$result_items_assoc[$item->{$field}] = array();
|
||||||
|
}
|
||||||
|
$result_items_assoc[$item->{$field}][] = $item;
|
||||||
|
} else {
|
||||||
|
if (isset($result_items_assoc[$item->{$field}])) {
|
||||||
|
throw new ErrorException('Field not unique. May be use assoc_as_array. ' . $field);
|
||||||
|
}
|
||||||
|
$result_items_assoc[$item->{$field}] = $item;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Ассоциирование внутри каждого элемента массива
|
||||||
|
// $field_assoc_in_array - ассоциирование произовдится по этому полю (вернет ошибку, если этого поля нет в результатх выборки)
|
||||||
|
if ($assoc_as_array && $field_assoc_in_array) {
|
||||||
|
foreach ($result_items_assoc as &$value) {
|
||||||
|
$sql_result_provider = new SqlResultProvider($value);
|
||||||
|
$value = $sql_result_provider->assoc($field_assoc_in_array)->fetchAll();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$this->result_items = $result_items_assoc;
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getKeys()
|
||||||
|
{
|
||||||
|
return array_keys($this->result_items);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function fetchAll()
|
||||||
|
{
|
||||||
|
return $this->result_items;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function fetchKey($key)
|
||||||
|
{
|
||||||
|
return $this->result_items[$key];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function fetch()
|
||||||
|
{
|
||||||
|
return current($this->result_items);
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user