Adds method to subscribe to single or multiple lists

This commit is contained in:
Vlad
2017-05-10 22:05:40 -04:00
parent 5e34bbf9d5
commit 5e23fa4295
2 changed files with 45 additions and 5 deletions

View File

@ -2,6 +2,9 @@
namespace MailPoet\API\MP\v1;
use MailPoet\Models\CustomField;
use MailPoet\Models\Segment;
use MailPoet\Models\Subscriber;
use MailPoet\Models\SubscriberSegment;
if(!defined('ABSPATH')) exit;
@ -32,4 +35,39 @@ class API {
return $data;
}
function subscribeToList($subscriber_id, $segment_id) {
return $this->subscribeToLists($subscriber_id, array($segment_id));
}
function subscribeToLists($subscriber_id, array $segments_ids) {
$subscriber = Subscriber::findOne((int)$subscriber_id);
// throw exception when subscriber does not exist
if(!$subscriber) {
throw new \Exception(__('This subscriber does not exist.', 'mailpoet'));
}
// throw exception when none of the segments exist
$found_segments = Segment::whereIn('id', $segments_ids)->findMany();
if(!$found_segments) {
throw new \Exception(__('These lists do not exists.', 'mailpoet'));
}
// throw exception when trying to subscribe to a WP Users segment
$found_segments_ids = array();
foreach($found_segments as $found_segment) {
if($found_segment->type === Segment::TYPE_WP_USERS) {
throw new \Exception(__(sprintf("Can't subscribe to a WordPress Users list with ID %d.", $found_segment->id), 'mailpoet'));
}
$found_segments_ids[] = $found_segment->id;
}
// throw an exception when one or more segments do not exist
if(count($found_segments_ids) !== count($segments_ids)) {
$missing_ids = array_values(array_diff($segments_ids, $found_segments_ids));
throw new \Exception(__(sprintf('Lists with ID %s do not exist.', implode(', ', $missing_ids)), 'mailpoet'));
}
return SubscriberSegment::subscribeToSegments($subscriber, $found_segments_ids);
}
}