02-database_worker.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace cx_newsletter;
  3. use \wpdb;
  4. abstract class database_worker {
  5. public function __construct(
  6. wpdb $database,
  7. table_names $tables,
  8. ) {
  9. $this->database = $database;
  10. $this->tables = $tables;
  11. }
  12. protected function parse_limit(?int $limit) : string {
  13. if ($limit === null) {
  14. return '';
  15. }
  16. return 'limit '.strval($limit).' ';
  17. }
  18. protected function parse_filters(
  19. array $filters,
  20. filter_type $type = filter_type::equal,
  21. filter_glue $glue = filter_glue::all
  22. ) : string {
  23. if (empty($filters)) {
  24. return '';
  25. }
  26. $result = new \cx_appengine\string_builder('where ');
  27. foreach ($filters as $name => $content) {
  28. $result->push($name);
  29. if ($content === null) {
  30. $result->push(' is null');
  31. } elseif (is_numeric($content)) {
  32. $result->push($type->value.strval($content));
  33. } elseif (is_string($content)) {
  34. $result->push($type->value.'"'.$content.'"');
  35. } else {
  36. throw $this->get_exception('parse_filters');
  37. }
  38. $result->push($glue->value);
  39. }
  40. return $result->cut(strlen($glue->value))->push(' ')->get();
  41. }
  42. protected function get_exception(string $operation) : \exception {
  43. $exception = "\n\n";
  44. $exception .= 'Can not make operation on database in class: ';
  45. $exception .= get_class($this).'. Trying to make: '.$operation.'.';
  46. $exception .= "\n\n";
  47. return new \exception($exception);
  48. }
  49. protected function get_has_id_exception() : \exception {
  50. $exception = "\n\n";
  51. $exception .= 'Can not make operation on database in class: ';
  52. $exception .= get_class($this).'. Trying to insert item with ID.';
  53. $exception .= "\n\n";
  54. return new \exception($exception);
  55. }
  56. protected function get_blank_id_exception() : \exception {
  57. $exception = "\n\n";
  58. $exception .= 'Can not make operation on database in class: ';
  59. $exception .= get_class($this).'. Trying to load target without ID.';
  60. $exception .= "\n\n";
  61. return new \exception($exception);
  62. }
  63. protected function get_tables() : table_names {
  64. return $this->tables;
  65. }
  66. protected function get_database() : wpdb {
  67. return $this->database;
  68. }
  69. private table_names $tables;
  70. private wpdb $database;
  71. }