1-messages_get_endpoint.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace cx_newsletter;
  3. use \wp_rest_request;
  4. class messages_get_endpoint
  5. extends rest_endpoint
  6. implements rest_endpoint_interface {
  7. use rest_endpoint_with_apikey;
  8. public function get_method() : string {
  9. return 'GET';
  10. }
  11. public function get_route() : string {
  12. return '/messages/';
  13. }
  14. public function action(wp_rest_request $request) : array {
  15. if (!$this->check_request_apikey($request)) {
  16. return $this->bad_apikey_response();
  17. }
  18. $response = new response_builder();
  19. return $response
  20. ->set_code(response_code::SUCCESS)
  21. ->set_status(response_status::SUCCESS)
  22. ->set_message('List of messages to send.')
  23. ->set_content($this->load_messages())
  24. ->build();
  25. }
  26. private function load_messages() : array {
  27. $this->prepare();
  28. $next_campaign = $this->select_campaign();
  29. if ($next_campaign === null) {
  30. return [];
  31. }
  32. $customers = $this->load_customers($next_campaign);
  33. $list = [];
  34. foreach ($customers as $customer) {
  35. $count = [
  36. 'Message' => $next_campaign->message->content,
  37. 'PhoneNumber' => $customer->phone_number,
  38. 'Campaign' => $next_campaign->get_id()
  39. ];
  40. array_push($list, $count);
  41. // FIX FOR CxSMS app
  42. $this->send_log_repository->mark_send($next_campaign, $customer);
  43. }
  44. if (empty($list)) {
  45. $next_campaign->finalize();
  46. $this->campaigns_repository->save($next_campaign);
  47. }
  48. return $list;
  49. }
  50. private function select_campaign() : ?campaign {
  51. return $this->campaigns_repository->load_next(campaign_type::sms);
  52. }
  53. private function load_customers(campaign $next) : array {
  54. return $this->send_log_repository->load_all(
  55. $next,
  56. $this->get_settings()->get('sms_count'),
  57. false
  58. );
  59. }
  60. private function prepare() : void {
  61. $this->campaigns_repository = new campaigns_repository(
  62. $this->get_database(),
  63. $this->get_tables()
  64. );
  65. $this->send_log_repository = new send_log_repository(
  66. $this->get_database(),
  67. $this->get_tables()
  68. );
  69. $this->customers_mapper = new customers_mapper(
  70. $this->get_database(),
  71. $this->get_tables()
  72. );
  73. $this->messages_mapper = new messages_mapper(
  74. $this->get_database(),
  75. $this->get_tables()
  76. );
  77. }
  78. private campaigns_repository $campaigns_repository;
  79. private send_log_repository $send_log_repository;
  80. private customers_mapper $customers_mapper;
  81. private messages_mapper $messages_mapper;
  82. }