01-database_converter.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace cx_newsletter;
  3. abstract class database_converter
  4. implements database_converter_interface {
  5. public function __construct() {
  6. $this->target = null;
  7. }
  8. protected function check_target() : void {
  9. if ($this->target === null) {
  10. throw $this->not_loaded_exception();
  11. }
  12. if (!$this->target->is_complete()) {
  13. throw $this->not_complete_exception();
  14. }
  15. }
  16. protected function not_complete_exception() : \exception {
  17. $exception = "\n\n";
  18. $exception .= 'Item in the builder is not complete.';
  19. $exception .= "\n\n";
  20. return new \exception($exception);
  21. }
  22. protected function check_all_exists(array $target, array $list) : void {
  23. foreach ($list as $name) {
  24. if (!array_key_exists($name, $target)) {
  25. throw $this->not_found_exception($name);
  26. }
  27. }
  28. }
  29. protected function id_or_null(array $target, string $name = 'id') : ?int {
  30. if (array_key_exists($name, $target)) {
  31. return intval($target[$name]);
  32. }
  33. return null;
  34. }
  35. protected function not_loaded_exception() : \exception {
  36. $exception = "\n\n";
  37. $exception .= 'Any content had not being loaded to this converter.';
  38. $exception .= "\n\n";
  39. return new \exception($exception);
  40. }
  41. protected function not_found_exception(string $name) : \exception {
  42. $exception = "\n\n";
  43. $exception .= 'Item with name "'.$name.'" not found.';
  44. $exception .= "\n\n";
  45. return new \exception($exception);
  46. }
  47. public function load_object(object $target) : self {
  48. $this->target = $target;
  49. return $this;
  50. }
  51. public function get_object() : object {
  52. return $this->target;
  53. }
  54. protected function is_loaded() : bool {
  55. return $this->target !== null;
  56. }
  57. protected function string_from_date(?\datetime $what) : ?string {
  58. if ($what === null) {
  59. return null;
  60. }
  61. return $what->format(\datetimeinterface::RFC3339);
  62. }
  63. protected function date_or_null(?string $what) : ?\datetime {
  64. if ($what === null or strtoupper($what) === 'NULL') {
  65. return null;
  66. }
  67. $time = \datetime::createfromformat(
  68. 'Y-m-d H:i:s',
  69. $what
  70. );
  71. if ($time === false) {
  72. return null;
  73. }
  74. return $time;
  75. }
  76. protected \exception $not_loaded_exception;
  77. protected ?object $target;
  78. }