limitting the recently sent templates to 12

This commit is contained in:
Amine Ben hammou
2018-02-09 16:43:40 +00:00
parent 3721694f4d
commit a754cfaa52
3 changed files with 53 additions and 0 deletions

View File

@ -45,9 +45,12 @@ class NewsletterTemplates extends APIEndpoint {
$data['id'] = $template['id'];
}
}
$template = NewsletterTemplate::createOrUpdate($data);
$errors = $template->getErrors();
NewsletterTemplate::cleanRecentlySent($data);
if(!empty($errors)) {
return $this->errorResponse($errors);
} else {

View File

@ -6,6 +6,9 @@ if(!defined('ABSPATH')) exit;
class NewsletterTemplate extends Model {
public static $_table = MP_NEWSLETTER_TEMPLATES_TABLE;
const RECENTLY_SENT_CATEGORIES = '["recent"]';
const RECENTLY_SENT_COUNT = 12;
function __construct() {
parent::__construct();
@ -17,6 +20,22 @@ class NewsletterTemplate extends Model {
));
}
static function cleanRecentlySent($data) {
if(!empty($data['categories']) && $data['categories'] === self::RECENTLY_SENT_CATEGORIES) {
$ids = parent::where('categories', self::RECENTLY_SENT_CATEGORIES)
->select('id')
->orderByDesc('id')
->limit(self::RECENTLY_SENT_COUNT)
->findMany();
$ids = array_map(function ($template) {
return $template->id;
}, $ids);
parent::where('categories', self::RECENTLY_SENT_CATEGORIES)
->whereNotIn('id', $ids)
->deleteMany();
}
}
function asArray() {
$template = parent::asArray();
if(isset($template['body'])) {

View File

@ -76,6 +76,37 @@ class NewsletterTemplateTest extends \MailPoetTest {
expect($template->name)->equals('Another template updated');
}
function testItCanCleanRecentlySent() {
$total = NewsletterTemplate::RECENTLY_SENT_COUNT + 5;
for($i = 0; $i < $total; $i++) {
NewsletterTemplate::createOrUpdate(array(
'name' => 'Testing template ' . $i,
'description' => 'template description',
'body' => '{content: {}, globalStyles: {}}',
'categories' => NewsletterTemplate::RECENTLY_SENT_CATEGORIES
));
}
NewsletterTemplate::cleanRecentlySent(array());
$count = NewsletterTemplate::where(
'categories', NewsletterTemplate::RECENTLY_SENT_CATEGORIES
)->count();
expect($count)->equals($total);
NewsletterTemplate::cleanRecentlySent(array(
'categories' => NewsletterTemplate::RECENTLY_SENT_CATEGORIES
));
$count = NewsletterTemplate::where(
'categories', NewsletterTemplate::RECENTLY_SENT_CATEGORIES
)->count();
expect($count)->equals(NewsletterTemplate::RECENTLY_SENT_COUNT);
$first = NewsletterTemplate::where(
'categories', NewsletterTemplate::RECENTLY_SENT_CATEGORIES
)->findOne();
expect($first->name)->equals('Testing template 5');
}
function _after() {
\ORM::for_table(NewsletterTemplate::$_table)
->deleteMany();