session = $session; $this->httpContext = $httpContext; $this->storeManager = $storeManager; $this->storeCookieManager = $storeCookieManager; } /** * Set store and currency to http context. * * @param AbstractAction $subject * @param RequestInterface $request * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function beforeDispatch( AbstractAction $subject, RequestInterface $request ) { if ($this->isAlreadySet()) { //If required store related value were already set for //HTTP processors then just continuing as we were. return; } /** @var string|array|null $storeCode */ $storeCode = $request->getParam( \Magento\Store\Model\StoreManagerInterface::PARAM_NAME, $this->storeCookieManager->getStoreCodeFromCookie() ); if (is_array($storeCode)) { if (!isset($storeCode['_data']['code'])) { $this->processInvalidStoreRequested(); } $storeCode = $storeCode['_data']['code']; } if ($storeCode === '') { //Empty code - is an invalid code and it was given explicitly //(the value would be null if the code wasn't found). $this->processInvalidStoreRequested(); } try { $currentStore = $this->storeManager->getStore($storeCode); } catch (NoSuchEntityException $exception) { $this->processInvalidStoreRequested($exception); } $this->updateContext($currentStore); } /** * Take action in case of invalid store requested. * * @param \Throwable|null $previousException * @return void * @throws NotFoundException */ private function processInvalidStoreRequested( \Throwable $previousException = null ) { $store = $this->storeManager->getStore(); $this->updateContext($store); throw new NotFoundException( $previousException ? __($previousException->getMessage()) : __('Invalid store requested.'), $previousException ); } /** * Update context accordingly to the store found. * * @param StoreInterface $store * @return void */ private function updateContext(StoreInterface $store) { $this->httpContext->setValue( StoreManagerInterface::CONTEXT_STORE, $store->getCode(), $this->storeManager->getDefaultStoreView()->getCode() ); /** @var StoreInterface $defaultStore */ $defaultStore = $this->storeManager->getWebsite()->getDefaultStore(); $this->httpContext->setValue( HttpContext::CONTEXT_CURRENCY, $this->session->getCurrencyCode() ?: $store->getDefaultCurrencyCode(), $defaultStore->getDefaultCurrencyCode() ); } /** * Check if there is a need to find the current store. * * @return bool */ private function isAlreadySet(): bool { $storeKey = StoreManagerInterface::CONTEXT_STORE; return $this->httpContext->getValue($storeKey) !== null; } }