Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
lumnn committed Apr 6, 2022
0 parents commit 2a96cf3
Show file tree
Hide file tree
Showing 11 changed files with 696 additions and 0 deletions.
51 changes: 51 additions & 0 deletions Block/PreferencesForm.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace KingfisherDirect\MailchimpExtras\Block;

use Ebizmarts\MailChimp\Helper\Data;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\View\Element\Template;
use Magento\Store\Model\StoreManagerInterface;

class PreferencesForm extends Template
{
private Data $mailchimpData;

private StoreManagerInterface $storeManager;

public function __construct(
Context $context,
array $data = [],
Data $mailchimpData
) {
parent::__construct($context, $data);

$this->storeManager = $context->getStoreManager();
$this->mailchimpData = $mailchimpData;
}

public function getStoreId(): int
{
return $this->storeManager->getStore()->getId();
}

public function getInterest(): array
{
return $this->mailchimpData->getInterest($this->getStoreId());
}

public function getMergeFields(): array
{
$api = $this->mailchimpData->getApi($this->getStoreId());
$listId = $this->mailchimpData->getDefaultList();
/** @var \Mailchimp_ListsMergeFields **/
$mergeApi = $api->lists->mergeFields;

$mergeFields = $mergeApi->getAll($listId, "merge_fields")["merge_fields"];
usort($mergeFields, function ($a, $b) {
return $a['display_order'] - $b['display_order'];
});

return $mergeFields;
}
}
83 changes: 83 additions & 0 deletions Controller/Preferences/AddInterest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

namespace KingfisherDirect\MailchimpExtras\Controller\Preferences;

use Ebizmarts\MailChimp\Helper\Data;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Action\Action;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManagerInterface;

class AddInterest extends Action
{
private Data $mailchimpData;

private Context $context;

private StoreManagerInterface $storeManager;

public function __construct(
Context $context,
Data $mailchimpData,
StoreManagerInterface $storeManager
) {
parent::__construct($context);

$this->context = $context;
$this->mailchimpData = $mailchimpData;
$this->storeManager = $storeManager;
}

public function execute()
{
$params = $this->getRequest()->getParams();
$member = $params['memberId'] ?? null;
$interest = $params['interestId'] ?? null;

$storeId = $this->storeManager->getStore()->getId();

$api = $this->mailchimpData->getApi($storeId);
$listId = $this->mailchimpData->getDefaultList();

if (!$member || !$interest) {
$this->messageManager->addWarning(__("This link is incorrect. You can subscribe from this page"));

return $this->_redirect("newsletter/preferences");
}

/** @var \Mailchimp_ListsMembers **/
$members = $api->lists->members;
$search = $members->getAll($listId, null, null, 1, null, null, null, null, null, null, null, $member);
$member = count($search['members']) === 1 ? $search['members'][0] : null;

if (!$member) {
$this->messageManager->addWarning(__("Subscriber information was not found. You can subscribe from this page"));

return $this->_redirect("newsletter/preferences");
}

$interests = $member['interests'];

if (!isset($interests[$interest])) {
$this->messageManager->addWarning(__("Failed to update interests. You can do it from this page"));

return $this->_redirect("newsletter/preferences", ["memberId" => $member["unique_email_id"]]);
}

$interests[$interest] = true;

try {
$update = $members->update($listId, $member['id'], null, null, null, $interests);
} catch (\Exception $e) {
$this->messageManager->addError(__("Something went wrong while saving your information."));

return $this->_redirect("newsletter/preferences", ["memberId" => $member["unique_email_id"]]);
}

$this->messageManager->addSuccess(__("Your preference was updated. You can add more interests on this page"));

return $this->_redirect("newsletter/preferences", ["memberId" => $member["unique_email_id"]]);
}
}
173 changes: 173 additions & 0 deletions Controller/Preferences/Index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
<?php

namespace KingfisherDirect\MailchimpExtras\Controller\Preferences;

use Ebizmarts\MailChimp\Helper\Data;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Action\Action;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface;
use function var_dump;

class Index extends Action
{
private PageFactory $pageFactory;

private Data $mailchimpData;

private Context $context;

private StoreManagerInterface $storeManager;

private Validator $formKeyValidator;

private LoggerInterface $logger;

public function __construct(
Context $context,
PageFactory $pageFactory,
Data $mailchimpData,
StoreManagerInterface $storeManager,
Validator $formKeyValidator,
LoggerInterface $logger
) {
parent::__construct($context);

$this->context = $context;
$this->pageFactory = $pageFactory;
$this->mailchimpData = $mailchimpData;
$this->storeManager = $storeManager;
$this->formKeyValidator = $formKeyValidator;
$this->logger = $logger;
}

public function execute()
{
$params = $this->getRequest()->getParams();
$member = $params['memberId'] ?? null;

$storeId = $this->getStoreId();

$api = $this->mailchimpData->getApi($storeId);
$listId = $this->mailchimpData->getDefaultList();

/** @var \Mailchimp_ListsMembers **/
$members = $api->lists->members;

if ($member) {
$search = $members->getAll($listId, null, null, 1, null, null, null, null, null, null, null, $member);

$member = count($search['members']) === 1 ? $search['members'][0] : null;
}

if (!$member) {
$this->messageManager->addWarning(__("We were not able to find your details, but you can subscribe from this page."));

return $this->_redirect("newsletter/subscribe");
}

$resultPage = $this->pageFactory->create();
$block = $resultPage->getLayout()->getBlock('newsletter.preferences_form');

if ($block) {
$block->setMember($member);
}

if (!$this->getRequest()->isPost()) {
return $resultPage;
}

if (!$this->formKeyValidator->validate($this->getRequest())) {
$this->messageManager->addWarning(__("Invalid form security key. Please try again"));

return $resultPage;
}


$errors = [];

$post = $this->getRequest()->getParam("member", []);

$post['interest'] = $post['interest'] ?? [];

if (is_array($post['interest'])) {
$interests = $member['interests'] ?? $this->getInterests();

foreach ($interests as $interest => $isInterested) {
$interests[$interest] = in_array($interest, $post['interest']);
}
}

if (!$member && (!$post['email'] || !filter_var($post['email'], FILTER_VALIDATE_EMAIL))) {
$errors['email'] = [__("Please enter valid email address")];
}

$postMergeFields = is_array($post['data']) ? $post['data'] : null;

foreach ($this->getMergeFields() as $mergeField) {
$tag = $mergeField["tag"];

if ($mergeField['public'] === false) {
if (array_key_exists($tag, $postMergeFields)) {
unset($postMergeFields[$tag]);
}

continue;
}

if ($mergeField['required'] === false) {
continue;
}

if (empty($postMergeFields[$tag])) {
$errors["data[${tag}]"] = [__("This field is required")];
}
}

if (empty($errors)) {
try {
$saved = $member
? $members->update($listId, $member['id'], null, "subscribed", $postMergeFields, $interests)
: $members->add($listId, "subscribed", $post['email'], null, $postMergeFields, $interests);

$this->messageManager->addSuccess(__("Your preferences were successfully saved!"));

return $this->_redirect("newsletter/preferences", ["memberId" => $saved["unique_email_id"]]);
} catch (\Exception $e) {
$this->messageManager->addError(__("Something went wrong while saving your information."));
$this->logger->error($e->getMessage());
}
} else {
$this->messageManager->addError(__("Please correct errors in form and try again"));
}

$block->setPostData($post);
$block->setErrors($errors);

return $resultPage;
}

private function getStoreId(): int
{
return $this->storeManager->getStore()->getId();
}

private function getInterests(): array
{
return $this->mailchimpData->getInterest($this->getStoreId());
}

private function getMergeFields(): array
{
$api = $this->mailchimpData->getApi($this->getStoreId());
$listId = $this->mailchimpData->getDefaultList();
/** @var \Mailchimp_ListsMergeFields **/
$mergeApi = $api->lists->mergeFields;

$mergeFields = $mergeApi->getAll($listId, "merge_fields")["merge_fields"];

return $mergeFields;
}
}
Loading

0 comments on commit 2a96cf3

Please sign in to comment.