diff --git a/lib/API/MP/v1/API.php b/lib/API/MP/v1/API.php index b62f6ee8e2..61a09f8557 100644 --- a/lib/API/MP/v1/API.php +++ b/lib/API/MP/v1/API.php @@ -133,6 +133,37 @@ class API { return $new_subscriber->withCustomFields()->withSubscriptions()->asArray(); } + function addList(array $list) { + // throw exception when list name is missing + if(empty($list['name'])) { + throw new \Exception( + __('List name is required.', 'mailpoet') + ); + } + + // throw exception when list already exists + if(Segment::where('name', $list['name'])->findOne()) { + throw new \Exception( + __('This list already exists.', 'mailpoet') + ); + } + + // add list + $new_list = Segment::create(); + $new_list->hydrate($list); + $new_list->save(); + if($new_list->getErrors() !== false) { + throw new \Exception( + __(sprintf('Failed to add list: %s', strtolower(implode(', ', $new_list->getErrors()))), 'mailpoet') + ); + } + + // reload list to get the saved created|updated|delete dates/other fields + $new_list = Segment::findOne($new_list->id); + + return $new_list->asArray(); + } + protected function _sendConfirmationEmail(Subscriber $subscriber) { return $subscriber->sendConfirmationEmail(); } diff --git a/tests/unit/API/MP/APITest.php b/tests/unit/API/MP/APITest.php index 3cd15881b3..e8895db3ad 100644 --- a/tests/unit/API/MP/APITest.php +++ b/tests/unit/API/MP/APITest.php @@ -319,6 +319,37 @@ class APITest extends \MailPoetTest { $API->addSubscriber($subscriber, $segments, $options); } + function testItRequiresNameToAddList() { + try { + API::MP(self::VERSION)->addList(array()); + $this->fail('List name required exception should have been thrown.'); + } catch(\Exception $e) { + expect($e->getMessage())->equals('List name is required.'); + } + } + + function testItDoesNotAddExistingList() { + $segment = Segment::create(); + $segment->name = 'Test segment'; + $segment->save(); + try { + API::MP(self::VERSION)->addList(array('name' => $segment->name)); + $this->fail('List exists exception should have been thrown.'); + } catch(\Exception $e) { + expect($e->getMessage())->equals('This list already exists.'); + } + } + + function testItAddsList() { + $segment = array( + 'name' => 'Test segment' + ); + + $result = API::MP(self::VERSION)->addList($segment); + expect($result['id'])->greaterThan(0); + expect($result['name'])->equals($segment['name']); + } + function _after() { \ORM::raw_execute('TRUNCATE ' . Subscriber::$_table); \ORM::raw_execute('TRUNCATE ' . CustomField::$_table);