07-cron_emails_sender.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace cx_newsletter;
  3. class cron_emails_sender
  4. extends service
  5. implements service_interface {
  6. public function prepare() : self {
  7. $this->campaigns_repository = new campaigns_repository(
  8. $this->get_database(),
  9. $this->get_tables()
  10. );
  11. $this->send_log_repository = new send_log_repository(
  12. $this->get_database(),
  13. $this->get_tables()
  14. );
  15. $this->customers_mapper = new customers_mapper(
  16. $this->get_database(),
  17. $this->get_tables()
  18. );
  19. $this->messages_mapper = new messages_mapper(
  20. $this->get_database(),
  21. $this->get_tables()
  22. );
  23. return $this;
  24. }
  25. public function process() : self {
  26. $next_campaign = $this->campaigns_repository->load_next(
  27. campaign_type::email
  28. );
  29. if ($next_campaign === null) {
  30. return $this;
  31. }
  32. $customers = $this->send_log_repository->load_all(
  33. $next_campaign,
  34. $this->get_settings()->get('email_count'),
  35. false
  36. );
  37. if (empty($customers)) {
  38. $next_campaign->finalize();
  39. $this->campaigns_repository->save($next_campaign);
  40. return $this->process();
  41. }
  42. foreach ($customers as $customer) {
  43. if ($this->send($customer, $next_campaign->message)) {
  44. $this->send_log_repository->mark_send($next_campaign, $customer);
  45. }
  46. }
  47. return $this;
  48. }
  49. private function send(customer $to, message $what) : bool {
  50. if (empty($to->email)) {
  51. return false;
  52. }
  53. if (!$what->is_complete()) {
  54. return false;
  55. }
  56. $headers = [];
  57. $headers['From'] = $this->get_settings()->get('source_address');
  58. $headers['Reply-To'] = $this->get_settings()->get('reply_to_address');
  59. $headers['MIME-Version'] = '1.0';
  60. $headers['Content-Type'] = 'text/html';
  61. return \wp_mail($to->email, $what->title, $what->content, $headers);
  62. }
  63. private campaigns_repository $campaigns_repository;
  64. private send_log_repository $send_log_repository;
  65. private customers_mapper $customers_mapper;
  66. private messages_mapper $messages_mapper;
  67. private campaign $what;
  68. }