You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
1.8 KiB

  1. <?php
  2. class SqlCriteria
  3. {
  4. public $select = array('*');
  5. public $distinct = '';
  6. public $where = array();
  7. public $order = array();
  8. public $limit = '';
  9. /**
  10. * @return SqlCriteria
  11. */
  12. public static function getInstance()
  13. {
  14. return self;
  15. }
  16. /**
  17. * @param $conditions array @ex array('field=?' => $value, 'field in ? => new DbExpr('(1,2,3)'))
  18. * @return SqlCriteria
  19. */
  20. public function where($conditions)
  21. {
  22. $this->where = $conditions;
  23. return $this;
  24. }
  25. /**
  26. * @param $fields array()
  27. * @param array $fields_to_desc
  28. * @return SqlCriteria
  29. */
  30. public function order($fields, $fields_to_desc = array())
  31. {
  32. if (!is_array($fields)) {
  33. $fields = array($fields);
  34. }
  35. foreach ($fields as $term) {
  36. $term = $this->db->quoteIdentifier($term) . (in_array($term, $fields_to_desc) ? ' DESC' : '');
  37. }
  38. $this->order = implode(',', $fields);
  39. return $this;
  40. }
  41. /**
  42. * @param $limit int
  43. * @param $offset int
  44. * @return SqlCriteria
  45. */
  46. public function limit($limit, $offset = 0)
  47. {
  48. if (empty($offset)) {
  49. $this->limit = (int) $limit;
  50. }
  51. $this->limit = (int)$limit . ',' . (int) $offset;
  52. return $this;
  53. }
  54. /**
  55. * @param mixed $select array @ex array('field1', 'field2', 'field3' => 'field')
  56. * @return string
  57. */
  58. public function select($select)
  59. {
  60. if (!is_array($select)) {
  61. $select = array($select);
  62. }
  63. $this->select = implode(',', $select);
  64. return $this;
  65. }
  66. /**
  67. * @param $field string
  68. * @return SqlCriteria
  69. */
  70. public function distinct($field)
  71. {
  72. $this->distinct = $field;
  73. return $this;
  74. }
  75. }