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.

95 lines
2.0 KiB

  1. <?php
  2. class SqlCriteria
  3. {
  4. private $select = array();
  5. private $distinct = '';
  6. private $where = array();
  7. private $order = array('sort' => array(), 'order' => array());
  8. private $limit = '';
  9. /**
  10. * @var SqlModel
  11. */
  12. private $model;
  13. /**
  14. * @param $model SqlModel
  15. */
  16. public function __construct($model)
  17. {
  18. $this->model = $model;
  19. }
  20. /**
  21. * @return SqlResultProvider
  22. */
  23. public function find()
  24. {
  25. return $this->model->find($this->select, $this->distinct, $this->where, $this->order, $this->limit);
  26. }
  27. /**
  28. * @param $cond string Condition with "?" placeholder @ex 'field=?'
  29. * @param $value string|array|DbExpr Value. Array transformed to DbExpr(implode(',' Array)) All elements in the array mast be integer
  30. * @return SqlCriteria
  31. * @desc Allow multiple calls
  32. */
  33. public function where($cond, $value)
  34. {
  35. $this->where[$cond] = $value;
  36. return $this;
  37. }
  38. /**
  39. * @param $field string Field @ex 'field'
  40. * @param $order_desc bool Descendant sort direction
  41. * @return SqlCriteria
  42. * @desc Allow multiple calls
  43. */
  44. public function order($field, $order_desc = false)
  45. {
  46. $this->order['sort'][] = $field;
  47. if ($order_desc) {
  48. $this->order['order'][$field] = 'desc';
  49. }
  50. return $this;
  51. }
  52. /**
  53. * @param $limit int
  54. * @param $offset int
  55. * @return SqlCriteria
  56. */
  57. public function limit($limit, $offset = 0)
  58. {
  59. if ($offset) {
  60. $this->limit = (int) $offset . ',';
  61. }
  62. $this->limit .= (int) $limit;
  63. return $this;
  64. }
  65. /**
  66. * @param string $field
  67. * @return SqlCriteria
  68. */
  69. public function select($field)
  70. {
  71. $this->select[] = $field;
  72. return $this;
  73. }
  74. /**
  75. * @param $field string
  76. * @return SqlCriteria
  77. */
  78. public function distinct($field)
  79. {
  80. $this->distinct = $field;
  81. return $this;
  82. }
  83. }