Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
SwitchAction.php
Go to the documentation of this file.
1 <?php
9 
11 use Magento\Framework\App\Action\Context as ActionContext;
12 use Magento\Framework\App\Http\Context as HttpContext;
21 
27 class SwitchAction extends Action
28 {
33 
38  protected $httpContext;
39 
43  protected $storeRepository;
44 
49  protected $storeManager;
50 
54  private $storeSwitcher;
55 
66  public function __construct(
67  ActionContext $context,
69  HttpContext $httpContext,
72  StoreSwitcherInterface $storeSwitcher = null
73  ) {
74  parent::__construct($context);
75  $this->storeCookieManager = $storeCookieManager;
76  $this->httpContext = $httpContext;
77  $this->storeRepository = $storeRepository;
78  $this->storeManager = $storeManager;
79  $this->messageManager = $context->getMessageManager();
80  $this->storeSwitcher = $storeSwitcher ?: ObjectManager::getInstance()->get(StoreSwitcherInterface::class);
81  }
82 
89  public function execute()
90  {
91  $targetStoreCode = $this->_request->getParam(
93  $this->storeCookieManager->getStoreCodeFromCookie()
94  );
95  $fromStoreCode = $this->_request->getParam('___from_store');
96 
97  $requestedUrlToRedirect = $this->_redirect->getRedirectUrl();
98  $redirectUrl = $requestedUrlToRedirect;
99 
100  $error = null;
101  try {
102  $fromStore = $this->storeRepository->get($fromStoreCode);
103  $targetStore = $this->storeRepository->getActiveStoreByCode($targetStoreCode);
104  } catch (StoreIsInactiveException $e) {
105  $error = __('Requested store is inactive');
106  } catch (NoSuchEntityException $e) {
107  $error = __("The store that was requested wasn't found. Verify the store and try again.");
108  }
109  if ($error !== null) {
110  $this->messageManager->addErrorMessage($error);
111  } else {
112  $redirectUrl = $this->storeSwitcher->switch($fromStore, $targetStore, $requestedUrlToRedirect);
113  }
114 
115  $this->getResponse()->setRedirect($redirectUrl);
116  }
117 }
_redirect($path, $arguments=[])
Definition: Action.php:167
__()
Definition: __.php:13
__construct(ActionContext $context, StoreCookieManagerInterface $storeCookieManager, HttpContext $httpContext, StoreRepositoryInterface $storeRepository, StoreManagerInterface $storeManager, StoreSwitcherInterface $storeSwitcher=null)