constraint.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. /**
  24. * Constraint constructor.
  25. * @param string $type
  26. * @throws Exception
  27. */
  28. public function __construct(string $type) {
  29. $type = "TYPE_" . strtoupper($type);
  30. if(!defined("Constraint::$type")) throw new Exception("Constraint::$type is not defined.");
  31. $this->type = constant("Constraint::$type");
  32. }
  33. public function setValues(...$values) {
  34. $this->values = array_map("db::escape", $values);
  35. return $this;
  36. }
  37. public function getConstraintString() {
  38. $value_1 = $this->values[0] ?? 0;
  39. $value_2 = $this->values[1] ?? 0;
  40. switch($this->type) {
  41. case self::TYPE_LESS_THAN:
  42. return " < '$value_1'";
  43. case self::TYPE_LESS_THAN_OR_EQUAL:
  44. return " <= '$value_1'";
  45. case self::TYPE_EQUALS:
  46. return " = '$value_1'";
  47. case self::TYPE_MORE_THAN_OR_EQUAL:
  48. return " >= '$value_1'";
  49. case self::TYPE_MORE_THAN:
  50. return " > '$value_1'";
  51. case self::TYPE_BETWEEN:
  52. return " BETWEEN '$value_1' AND '$value_2'";
  53. case self::TYPE_BEGINS_WITH:
  54. return " LIKE '$value_1%'";
  55. case self::TYPE_CONTAINS:
  56. return " LIKE '%$value_1%'";
  57. case self::TYPE_ENDS_WITH:
  58. return " LIKE '%$value_1'";
  59. case self::TYPE_NOT_EQUALS:
  60. return " != '$value_1'";
  61. case self::TYPE_IS_NULL:
  62. return " IS NULL";
  63. case self::TYPE_IS_NOT_NULL:
  64. return " IS NOT NULL";
  65. case self::TYPE_NOT_IN:
  66. if(empty($this->values)) return false;
  67. $values = array_map(function($value) {
  68. return sprintf("'%s'", $value);
  69. }, $this->values);
  70. return sprintf(" NOT IN (%s)", implode(", ", $values));
  71. }
  72. return false;
  73. }
  74. }