Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
SynchronizePersistentOnLoginObserver.php
Go to the documentation of this file.
1 <?php
7 
9 
11 
16 {
23 
29  protected $_persistentData = null;
30 
36  protected $_sessionFactory;
37 
43  protected $_customerSession;
44 
53  public function __construct(
54  \Magento\Persistent\Helper\Data $persistentData,
55  \Magento\Persistent\Helper\Session $persistentSession,
56  \Magento\Customer\Model\Session $customerSession,
57  \Magento\Persistent\Model\SessionFactory $sessionFactory
58  ) {
59  $this->_persistentData = $persistentData;
60  $this->_persistentSession = $persistentSession;
61  $this->_customerSession = $customerSession;
62  $this->_sessionFactory = $sessionFactory;
63  }
64 
70  public function execute(Observer $observer)
71  {
73  $customer = $observer->getEvent()->getCustomer();
74  // Check if customer is valid (remove persistent cookie for invalid customer)
75  if (!$customer || !$customer->getId() || !$this->_persistentSession->isRememberMeChecked()) {
76  $this->_sessionFactory->create()->removePersistentCookie();
77  return;
78  }
79 
80  $persistentLifeTime = $this->_persistentData->getLifeTime();
81  // Delete persistent session, if persistent could not be applied
82  if ($this->_persistentData->isEnabled() && $persistentLifeTime <= 0) {
83  // Remove current customer persistent session
84  $this->_sessionFactory->create()->deleteByCustomerId($customer->getId());
85  return;
86  }
87 
89  $sessionModel = $this->_persistentSession->getSession();
90 
91  // Check if session is wrong or not exists, so create new session
92  if (!$sessionModel->getId() || $sessionModel->getCustomerId() != $customer->getId()) {
94  $sessionModel = $this->_sessionFactory->create();
95  $sessionModel->setLoadExpired()->loadByCustomerId($customer->getId());
96  if (!$sessionModel->getId()) {
98  $sessionModel = $this->_sessionFactory->create();
99  $sessionModel->setCustomerId($customer->getId())->save();
100  }
101  $this->_persistentSession->setSession($sessionModel);
102  }
103 
104  // Set new cookie
105  if ($sessionModel->getId()) {
106  $sessionModel->setPersistentCookie(
107  $persistentLifeTime,
108  $this->_customerSession->getCookiePath()
109  );
110  }
111  }
112 }
$customer
Definition: customers.php:11
$persistentSession
Definition: persistent.php:11
__construct(\Magento\Persistent\Helper\Data $persistentData, \Magento\Persistent\Helper\Session $persistentSession, \Magento\Customer\Model\Session $customerSession, \Magento\Persistent\Model\SessionFactory $sessionFactory)