|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Noon\HideDefaultStoreCode\Observer; |
| 4 | + |
| 5 | +class RedirectWithoutStoreCode implements \Magento\Framework\Event\ObserverInterface |
| 6 | +{ |
| 7 | + /** |
| 8 | + * @var \Magento\Framework\App\Response\RedirectInterface |
| 9 | + */ |
| 10 | + protected $redirect; |
| 11 | + |
| 12 | + /** |
| 13 | + * @var \Magento\Framework\App\ActionFlag |
| 14 | + */ |
| 15 | + protected $actionFlag; |
| 16 | + |
| 17 | + /** |
| 18 | + * @var \Magento\Store\Model\StoreManagerInterface |
| 19 | + */ |
| 20 | + protected $storeManager; |
| 21 | + |
| 22 | + /** |
| 23 | + * @var \Noon\HideDefaultStoreCode\Helper\Data |
| 24 | + */ |
| 25 | + protected $helper; |
| 26 | + |
| 27 | + /** |
| 28 | + * @var \Magento\Framework\UrlInterface |
| 29 | + */ |
| 30 | + protected $url; |
| 31 | + |
| 32 | + /** |
| 33 | + * |
| 34 | + * @param \Magento\Framework\App\Response\RedirectInterface $redirect |
| 35 | + * @param \Magento\Framework\App\ActionFlag $actionFlag |
| 36 | + * @param \Magento\Store\Model\StoreManagerInterface $storeManager |
| 37 | + * @param \Noon\HideDefaultStoreCode\Helper\Data $helper |
| 38 | + * @param \Magento\Framework\UrlInterface $url |
| 39 | + */ |
| 40 | + public function __construct( |
| 41 | + \Magento\Framework\App\Response\RedirectInterface $redirect, |
| 42 | + \Magento\Framework\App\ActionFlag $actionFlag, |
| 43 | + \Magento\Store\Model\StoreManagerInterface $storeManager, |
| 44 | + \Noon\HideDefaultStoreCode\Helper\Data $helper, |
| 45 | + \Magento\Framework\UrlInterface $url |
| 46 | + ) { |
| 47 | + $this->redirect = $redirect; |
| 48 | + $this->actionFlag = $actionFlag; |
| 49 | + $this->storeManager = $storeManager; |
| 50 | + $this->helper = $helper; |
| 51 | + $this->url = $url; |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * |
| 56 | + * @param \Magento\Framework\Event\Observer $observer |
| 57 | + * @return void |
| 58 | + */ |
| 59 | + public function execute(\Magento\Framework\Event\Observer $observer) |
| 60 | + { |
| 61 | + $websiteId = $this->storeManager->getStore()->getWebsiteId(); |
| 62 | + $defaultStore = $this->storeManager->getWebsite($websiteId)->getDefaultStore(); |
| 63 | + |
| 64 | + if (!is_null($defaultStore)) { |
| 65 | + $url = $this->url->getCurrentUrl(); |
| 66 | + $pos = strpos($url, $this->storeManager->getStore()->getBaseUrl() . $defaultStore->getCode()); |
| 67 | + |
| 68 | + if ($this->helper->isHideDefaultStoreCode() && $pos !== false) { |
| 69 | + $controller = $observer->getData('controller_action'); |
| 70 | + $url = str_replace('/' . $defaultStore->getCode() . '/', '/', $url); |
| 71 | + $this->actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true); |
| 72 | + $this->redirect->redirect($controller->getResponse(), $url); |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments