Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
EmulateCustomerObserver.php
Go to the documentation of this file.
1 <?php
7 
9 
14 {
20  protected $_customerSession;
21 
28 
34  protected $_persistentData;
35 
42 
46  protected $addressRepository;
47 
57  public function __construct(
58  \Magento\Persistent\Helper\Session $persistentSession,
59  \Magento\Persistent\Helper\Data $persistentData,
60  \Magento\Customer\Model\Session $customerSession,
61  \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
62  \Magento\Customer\Api\AddressRepositoryInterface $addressRepository
63  ) {
64  $this->_persistentSession = $persistentSession;
65  $this->_persistentData = $persistentData;
66  $this->_customerSession = $customerSession;
67  $this->customerRepository = $customerRepository;
68  $this->addressRepository = $addressRepository;
69  }
70 
79  public function execute(\Magento\Framework\Event\Observer $observer)
80  {
81  if (!$this->_persistentData->canProcess($observer) || !$this->_persistentData->isShoppingCartPersist()) {
82  return $this;
83  }
84 
85  if ($this->_persistentSession->isPersistent() && !$this->_customerSession->isLoggedIn()) {
87  $customer = $this->customerRepository->getById($this->_persistentSession->getSession()->getCustomerId());
88  if ($defaultShipping = $customer->getDefaultShipping()) {
90  $address = $this->addressRepository->getById($defaultShipping);
91  if ($address) {
92  $this->_customerSession->setDefaultTaxShippingAddress(
93  [
94  'country_id' => $address->getCountryId(),
95  'region_id' => $address->getRegion()
96  ? $address->getRegionId()
97  : null,
98  'postcode' => $address->getPostcode(),
99  ]
100  );
101  }
102  }
103 
104  if ($defaultBilling = $customer->getDefaultBilling()) {
105  $address = $this->addressRepository->getById($defaultBilling);
106  if ($address) {
107  $this->_customerSession->setDefaultTaxBillingAddress([
108  'country_id' => $address->getCountryId(),
109  'region_id' => $address->getRegion() ? $address->getRegionId() : null,
110  'postcode' => $address->getPostcode(),
111  ]);
112  }
113  }
114  $this->_customerSession
115  ->setCustomerId($customer->getId())
116  ->setCustomerGroupId($customer->getGroupId())
117  ->setIsCustomerEmulated(true);
118  }
119  return $this;
120  }
121 }
__construct(\Magento\Persistent\Helper\Session $persistentSession, \Magento\Persistent\Helper\Data $persistentData, \Magento\Customer\Model\Session $customerSession, \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository, \Magento\Customer\Api\AddressRepositoryInterface $addressRepository)
$customer
Definition: customers.php:11
$address
Definition: customer.php:38
$persistentSession
Definition: persistent.php:11