Implement NewsletterTempates::save() API using Doctrine

[MAILPOET-2647]
This commit is contained in:
Jan Jakeš
2020-03-05 17:22:14 +01:00
committed by Veljko V
parent 4d110bbb68
commit 32f5777945
3 changed files with 42 additions and 28 deletions

View File

@ -56,26 +56,13 @@ class NewsletterTemplates extends APIEndpoint {
public function save($data = []) {
ignore_user_abort(true);
if (!empty($data['newsletter_id'])) {
$template = NewsletterTemplate::whereEqual('newsletter_id', $data['newsletter_id'])->findOne();
if ($template instanceof NewsletterTemplate) {
$data['id'] = $template->id;
}
}
$template = NewsletterTemplate::createOrUpdate($data);
$errors = $template->getErrors();
NewsletterTemplate::cleanRecentlySent($data);
if (!empty($errors)) {
return $this->errorResponse($errors);
} else {
$template = NewsletterTemplate::findOne($template->id);
if(!$template instanceof NewsletterTemplate) return $this->errorResponse();
return $this->successResponse(
$template->asArray()
);
try {
$template = $this->newsletterTemplatesRepository->createOrUpdate($data);
NewsletterTemplate::cleanRecentlySent($data);
$data = $this->newsletterTemplatesResponseBuilder->build($template);
return $this->successResponse($data);
} catch (\Throwable $e) {
return $this->errorResponse();
}
}

View File

@ -45,12 +45,4 @@ class NewsletterTemplate extends Model {
->deleteMany();
}
}
public function asArray() {
$template = parent::asArray();
if (isset($template['body'])) {
$template['body'] = json_decode($template['body'], true);
}
return $template;
}
}

View File

@ -3,6 +3,7 @@
namespace MailPoet\NewsletterTemplates;
use MailPoet\Doctrine\Repository;
use MailPoet\Entities\NewsletterEntity;
use MailPoet\Entities\NewsletterTemplateEntity;
/**
@ -29,4 +30,38 @@ class NewsletterTemplatesRepository extends Repository {
->getQuery()
->getResult();
}
public function createOrUpdate(array $data): NewsletterTemplateEntity {
$template = !empty($data['newsletter_id'])
? $this->findOneBy(['newsletter' => (int)$data['newsletter_id']])
: null;
if (!$template) {
$template = new NewsletterTemplateEntity();
$this->entityManager->persist($template);
}
if (isset($data['newsletter_id'])) {
$template->setNewsletter($this->entityManager->getReference(NewsletterEntity::class, (int)$data['newsletter_id']));
}
if (isset($data['name'])) {
$template->setName($data['name']);
}
if (isset($data['thumbnail'])) {
$template->setThumbnail($data['thumbnail']);
}
if (isset($data['body'])) {
$template->setBody(json_decode($data['body'], true));
}
if (isset($data['categories'])) {
$template->setCategories($data['categories']);
}
$this->entityManager->flush();
return $template;
}
}