constraint.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. class Constraint {
  3. const TYPE_LESS_THAN = 0;
  4. const TYPE_LESS_THAN_OR_EQUAL = 1;
  5. const TYPE_EQUALS = 2;
  6. const TYPE_MORE_THAN_OR_EQUAL = 3;
  7. const TYPE_MORE_THAN = 4;
  8. const TYPE_BETWEEN = 5;
  9. const TYPE_BEGINS_WITH = 6;
  10. const TYPE_CONTAINS = 7;
  11. const TYPE_ENDS_WITH = 8;
  12. const TYPE_NOT_EQUALS = 9;
  13. const TYPE_IS_NULL = 10;
  14. const TYPE_IS_NOT_NULL = 11;
  15. const TYPE_NOT_IN = 12;
  16. private $type;
  17. private $values = [];
  18. public static function contains(string $string): Constraint {
  19. $constraint = new Constraint("CONTAINS");
  20. $constraint->setValues($string);
  21. return $constraint;
  22. }
  23. public static function between(string $start, string $end): Constraint {
  24. $constraint = new Constraint("BETWEEN");
  25. $constraint->setValues($start, $end);
  26. return $constraint;
  27. }
  28. /**
  29. * Constraint constructor.
  30. * @param string $type
  31. * @throws Exception
  32. */
  33. public function __construct(string $type) {
  34. $type = "TYPE_" . strtoupper($type);
  35. if(!defined("Constraint::$type")) throw new Exception("Constraint::$type is not defined.");
  36. $this->type = constant("Constraint::$type");
  37. }
  38. public function setValues(...$values) {
  39. $this->values = array_map("db::escape", $values);
  40. return $this;
  41. }
  42. public function getConstraintString() {
  43. $value_1 = $this->values[0] ?? 0;
  44. $value_2 = $this->values[1] ?? 0;
  45. switch($this->type) {
  46. case self::TYPE_LESS_THAN:
  47. return " < '$value_1'";
  48. case self::TYPE_LESS_THAN_OR_EQUAL:
  49. return " <= '$value_1'";
  50. case self::TYPE_EQUALS:
  51. return " = '$value_1'";
  52. case self::TYPE_MORE_THAN_OR_EQUAL:
  53. return " >= '$value_1'";
  54. case self::TYPE_MORE_THAN:
  55. return " > '$value_1'";
  56. case self::TYPE_BETWEEN:
  57. return " BETWEEN '$value_1' AND '$value_2'";
  58. case self::TYPE_BEGINS_WITH:
  59. return " LIKE '$value_1%'";
  60. case self::TYPE_CONTAINS:
  61. return " LIKE '%$value_1%'";
  62. case self::TYPE_ENDS_WITH:
  63. return " LIKE '%$value_1'";
  64. case self::TYPE_NOT_EQUALS:
  65. return " != '$value_1'";
  66. case self::TYPE_IS_NULL:
  67. return " IS NULL";
  68. case self::TYPE_IS_NOT_NULL:
  69. return " IS NOT NULL";
  70. case self::TYPE_NOT_IN:
  71. if(empty($this->values)) return false;
  72. $values = array_map(function($value) {
  73. return sprintf("'%s'", $value);
  74. }, $this->values);
  75. return sprintf(" NOT IN (%s)", implode(", ", $values));
  76. }
  77. return false;
  78. }
  79. }