StoreCookie.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Store\Model\Plugin;
  7. use Magento\Store\Api\StoreCookieManagerInterface;
  8. use Magento\Store\Model\StoreManagerInterface;
  9. use Magento\Store\Api\StoreRepositoryInterface;
  10. use Magento\Store\Model\StoreIsInactiveException;
  11. use Magento\Framework\Exception\NoSuchEntityException;
  12. use \InvalidArgumentException;
  13. /**
  14. * Class StoreCookie
  15. */
  16. class StoreCookie
  17. {
  18. /**
  19. * @var \Magento\Store\Model\StoreManagerInterface
  20. */
  21. protected $storeManager;
  22. /**
  23. * @var StoreCookieManagerInterface
  24. */
  25. protected $storeCookieManager;
  26. /**
  27. * @var StoreRepositoryInterface
  28. */
  29. protected $storeRepository;
  30. /**
  31. * @param StoreManagerInterface $storeManager
  32. * @param StoreCookieManagerInterface $storeCookieManager
  33. * @param StoreRepositoryInterface $storeRepository
  34. */
  35. public function __construct(
  36. StoreManagerInterface $storeManager,
  37. StoreCookieManagerInterface $storeCookieManager,
  38. StoreRepositoryInterface $storeRepository
  39. ) {
  40. $this->storeManager = $storeManager;
  41. $this->storeCookieManager = $storeCookieManager;
  42. $this->storeRepository = $storeRepository;
  43. }
  44. /**
  45. * Delete cookie "store" if the store (a value in the cookie) does not exist or is inactive
  46. *
  47. * @param \Magento\Framework\App\FrontController $subject
  48. * @param \Magento\Framework\App\RequestInterface $request
  49. * @return void
  50. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  51. */
  52. public function beforeDispatch(
  53. \Magento\Framework\App\FrontController $subject,
  54. \Magento\Framework\App\RequestInterface $request
  55. ) {
  56. $storeCodeFromCookie = $this->storeCookieManager->getStoreCodeFromCookie();
  57. if ($storeCodeFromCookie) {
  58. try {
  59. $this->storeRepository->getActiveStoreByCode($storeCodeFromCookie);
  60. } catch (StoreIsInactiveException $e) {
  61. $this->storeCookieManager->deleteStoreCookie($this->storeManager->getDefaultStoreView());
  62. } catch (NoSuchEntityException $e) {
  63. $this->storeCookieManager->deleteStoreCookie($this->storeManager->getDefaultStoreView());
  64. } catch (InvalidArgumentException $e) {
  65. $this->storeCookieManager->deleteStoreCookie($this->storeManager->getDefaultStoreView());
  66. }
  67. }
  68. }
  69. }