Refactor MPAPI subscribeToLists to Doctrine

[MAILPOET-3820]
This commit is contained in:
Brezo Cordero
2021-12-02 16:13:08 -06:00
committed by Veljko V
parent 2bb04ed5bd
commit 81e0772459
6 changed files with 683 additions and 567 deletions

View File

@ -2,60 +2,33 @@
namespace MailPoet\API\MP\v1;
use MailPoet\Entities\SubscriberEntity;
use MailPoet\Models\Segment;
use MailPoet\Models\Subscriber;
use MailPoet\Models\SubscriberSegment;
use MailPoet\Newsletter\Scheduler\WelcomeScheduler;
use MailPoet\Settings\SettingsController;
use MailPoet\Subscribers\ConfirmationEmailMailer;
use MailPoet\Subscribers\NewSubscriberNotificationMailer;
use MailPoet\Subscribers\RequiredCustomFieldValidator;
use MailPoet\Subscribers\Source;
use MailPoet\Subscribers\SubscribersRepository;
use MailPoet\Tasks\Sending;
use MailPoet\Util\Helpers;
use MailPoet\WP\Functions as WPFunctions;
class API {
/** @var NewSubscriberNotificationMailer */
private $newSubscriberNotificationMailer;
/** @var ConfirmationEmailMailer */
private $confirmationEmailMailer;
/** @var RequiredCustomFieldValidator */
private $requiredCustomFieldValidator;
/** @var WelcomeScheduler */
private $welcomeScheduler;
/** @var SettingsController */
private $settings;
/** @var CustomFields */
private $customFields;
/** @var SubscribersRepository */
private $subscribersRepository;
/** @var Subscribers */
private $subscribers;
public function __construct(
NewSubscriberNotificationMailer $newSubscriberNotificationMailer,
ConfirmationEmailMailer $confirmationEmailMailer,
RequiredCustomFieldValidator $requiredCustomFieldValidator,
WelcomeScheduler $welcomeScheduler,
CustomFields $customFields,
SettingsController $settings,
SubscribersRepository $subscribersRepository
Subscribers $subscribers
) {
$this->newSubscriberNotificationMailer = $newSubscriberNotificationMailer;
$this->confirmationEmailMailer = $confirmationEmailMailer;
$this->requiredCustomFieldValidator = $requiredCustomFieldValidator;
$this->welcomeScheduler = $welcomeScheduler;
$this->settings = $settings;
$this->customFields = $customFields;
$this->subscribersRepository = $subscribersRepository;
$this->subscribers = $subscribers;
}
public function getSubscriberFields() {
@ -70,99 +43,18 @@ class API {
}
}
public function subscribeToList($subscriberId, $listId, $options = []) {
/**
* @throws APIException
*/
public function subscribeToList($subscriberId, $listId, $options = []): array {
return $this->subscribeToLists($subscriberId, [$listId], $options);
}
/**
* @throws APIException
*/
public function subscribeToLists($subscriberId, array $listIds, $options = []) {
$scheduleWelcomeEmail = (isset($options['schedule_welcome_email']) && $options['schedule_welcome_email'] === false) ? false : true;
$sendConfirmationEmail = (isset($options['send_confirmation_email']) && $options['send_confirmation_email'] === false) ? false : true;
$skipSubscriberNotification = (isset($options['skip_subscriber_notification']) && $options['skip_subscriber_notification'] === true) ? true : false;
$signupConfirmationEnabled = (bool)$this->settings->get('signup_confirmation.enabled');
if (empty($listIds)) {
throw new APIException(__('At least one segment ID is required.', 'mailpoet'), APIException::SEGMENT_REQUIRED);
}
// throw exception when subscriber does not exist
$subscriber = Subscriber::findOne($subscriberId);
if (!$subscriber) {
throw new APIException(__('This subscriber does not exist.', 'mailpoet'), APIException::SUBSCRIBER_NOT_EXISTS);
}
// throw exception when none of the segments exist
$foundSegments = Segment::whereIn('id', $listIds)->findMany();
if (!$foundSegments) {
$exception = WPFunctions::get()->_n('This list does not exist.', 'These lists do not exist.', count($listIds), 'mailpoet');
throw new APIException($exception, APIException::LIST_NOT_EXISTS);
}
// throw exception when trying to subscribe to WP Users or WooCommerce Customers segments
$foundSegmentsIds = [];
foreach ($foundSegments as $foundSegment) {
if ($foundSegment->type === Segment::TYPE_WP_USERS) {
throw new APIException(__(sprintf("Can't subscribe to a WordPress Users list with ID %d.", $foundSegment->id), 'mailpoet'), APIException::SUBSCRIBING_TO_WP_LIST_NOT_ALLOWED);
}
if ($foundSegment->type === Segment::TYPE_WC_USERS) {
throw new APIException(__(sprintf("Can't subscribe to a WooCommerce Customers list with ID %d.", $foundSegment->id), 'mailpoet'), APIException::SUBSCRIBING_TO_WC_LIST_NOT_ALLOWED);
}
if ($foundSegment->type !== Segment::TYPE_DEFAULT) {
throw new APIException(__(sprintf("Can't subscribe to a list with ID %d.", $foundSegment->id), 'mailpoet'), APIException::SUBSCRIBING_TO_LIST_NOT_ALLOWED);
}
$foundSegmentsIds[] = $foundSegment->id;
}
// throw an exception when one or more segments do not exist
if (count($foundSegmentsIds) !== count($listIds)) {
$missingIds = array_values(array_diff($listIds, $foundSegmentsIds));
$exception = sprintf(
WPFunctions::get()->_n('List with ID %s does not exist.', 'Lists with IDs %s do not exist.', count($missingIds), 'mailpoet'),
implode(', ', $missingIds)
);
throw new APIException(sprintf($exception, implode(', ', $missingIds)), APIException::LIST_NOT_EXISTS);
}
SubscriberSegment::subscribeToSegments($subscriber, $foundSegmentsIds);
// set status depending on signup confirmation setting
if ($subscriber->status !== Subscriber::STATUS_SUBSCRIBED) {
if ($signupConfirmationEnabled === true) {
$subscriber->set('status', Subscriber::STATUS_UNCONFIRMED);
} else {
$subscriber->set('status', Subscriber::STATUS_SUBSCRIBED);
}
$subscriber->save();
if ($subscriber->getErrors() !== false) {
throw new APIException(
__(sprintf('Failed to save a status of a subscriber : %s', strtolower(implode(', ', $subscriber->getErrors()))), 'mailpoet'),
APIException::FAILED_TO_SAVE_SUBSCRIBER
);
}
}
// schedule welcome email
if ($scheduleWelcomeEmail && $subscriber->status === Subscriber::STATUS_SUBSCRIBED) {
$this->_scheduleWelcomeNotification($subscriber, $foundSegmentsIds);
}
// send confirmation email
if ($sendConfirmationEmail) {
try {
$this->_sendConfirmationEmail($subscriber);
} catch (\Exception $e) {
throw new APIException(
__(sprintf('Subscriber added to lists, but confirmation email failed to send: %s', strtolower($e->getMessage())), 'mailpoet'),
APIException::CONFIRMATION_FAILED_TO_SEND
);
}
}
if (!$skipSubscriberNotification && ($subscriber->status === Subscriber::STATUS_SUBSCRIBED)) {
$this->sendSubscriberNotification($subscriber, $foundSegmentsIds);
}
return $subscriber->withCustomFields()->withSubscriptions()->asArray();
return $this->subscribers->subscribeToLists($subscriberId, $listIds, $options);
}
public function unsubscribeFromList($subscriberId, $listId) {
@ -331,30 +223,4 @@ class API {
}
return $subscriber->withCustomFields()->withSubscriptions()->asArray();
}
protected function _sendConfirmationEmail(Subscriber $subscriber) {
$subscriberEntity = $this->subscribersRepository->findOneById($subscriber->id);
if ($subscriberEntity instanceof SubscriberEntity) {
return $this->confirmationEmailMailer->sendConfirmationEmailOnce($subscriberEntity);
}
}
protected function _scheduleWelcomeNotification(Subscriber $subscriber, array $segments) {
$result = $this->welcomeScheduler->scheduleSubscriberWelcomeNotification($subscriber->id, $segments);
if (is_array($result)) {
foreach ($result as $queue) {
if ($queue instanceof Sending && $queue->getErrors()) {
throw new APIException(
__(sprintf('Subscriber added, but welcome email failed to send: %s', strtolower(implode(', ', $queue->getErrors()))), 'mailpoet'),
APIException::WELCOME_FAILED_TO_SEND
);
}
}
}
return $result;
}
private function sendSubscriberNotification(Subscriber $subscriber, array $segmentIds) {
$this->newSubscriberNotificationMailer->send($subscriber, Segment::whereIn('id', $segmentIds)->findMany());
}
}