Skip to content

Commit

Permalink
Merge pull request #6 from outeredge/fix-news-after-subscriber
Browse files Browse the repository at this point in the history
Fix news update after subscribed
  • Loading branch information
davidwindell authored May 10, 2022
2 parents 9200dc8 + 2043f5d commit b516f3d
Showing 1 changed file with 15 additions and 26 deletions.
41 changes: 15 additions & 26 deletions Observer/UpdateNewsSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Model\SessionFactory;
use Magento\Customer\Api\CustomerRepositoryInterface;
use OuterEdge\Multiplenewsletter\Helper\Data;

Expand All @@ -15,21 +14,13 @@ class UpdateNewsSubscriber implements ObserverInterface
*/
protected $customerRepositoryInterface;

/**
* @var SessionFactory
*/
protected $sessionFactory;

/**
* @param CustomerRepositoryInterface $customerRepositoryInterface
* @param SessionFactory $sessionFactory
*/
public function __construct(
CustomerRepositoryInterface $customerRepositoryInterface,
SessionFactory $sessionFactory
CustomerRepositoryInterface $customerRepositoryInterface
) {
$this->customerRepositoryInterface = $customerRepositoryInterface;
$this->sessionFactory = $sessionFactory;
}

/**
Expand All @@ -38,25 +29,23 @@ public function __construct(
public function execute(Observer $observer) : void
{
$event = $observer->getEvent();
if ($event->getSubscriber()) {
$dataToSave = Data::CORE_NEWSLETTER_SUBSCRIBE;
} else {
$dataToSave = Data::CORE_NEWSLETTER_UNSUBSCRIBE;
}

try {
$customer = $this->customerRepositoryInterface->getById($this->getCustomerId());
$customer->setCustomAttribute('newsletter_options', $dataToSave);
if ($customerId = $event->getSubscriber()->getCustomerId()) {

$this->customerRepositoryInterface->save($customer);
if ($event->getSubscriber()) {
$dataToSave = Data::CORE_NEWSLETTER_SUBSCRIBE;
} else {
$dataToSave = Data::CORE_NEWSLETTER_UNSUBSCRIBE;
}

} catch (\Exception $e) {
throw new \Exception('Error saving multiple newsletter');
}
}
try {
$customer = $this->customerRepositoryInterface->getById($customerId);
$customer->setCustomAttribute('newsletter_options', $dataToSave);

private function getCustomerId()
{
return $this->sessionFactory->create()->getId();
$this->customerRepositoryInterface->save($customer);
} catch (\Exception $e) {
throw new \Exception('Error saving multiple newsletter');
}
}
}
}

0 comments on commit b516f3d

Please sign in to comment.