ManageStoreCookie.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\Store\Model\StoreSwitcher;
  8. use Magento\Store\Model\StoreSwitcherInterface;
  9. use Magento\Store\Api\Data\StoreInterface;
  10. use Magento\Framework\App\Http\Context as HttpContext;
  11. use Magento\Store\Api\StoreCookieManagerInterface;
  12. use Magento\Store\Model\StoreManagerInterface;
  13. use Magento\Store\Model\Store;
  14. /**
  15. * Manage store cookie depending on what store view customer is.
  16. */
  17. class ManageStoreCookie implements StoreSwitcherInterface
  18. {
  19. /**
  20. * @var StoreCookieManagerInterface
  21. */
  22. private $storeCookieManager;
  23. /**
  24. * @var HttpContext
  25. */
  26. private $httpContext;
  27. /**
  28. * @var StoreManagerInterface
  29. */
  30. private $storeManager;
  31. /**
  32. * @param StoreCookieManagerInterface $storeCookieManager
  33. * @param HttpContext $httpContext
  34. * @param StoreManagerInterface $storeManager
  35. */
  36. public function __construct(
  37. StoreCookieManagerInterface $storeCookieManager,
  38. HttpContext $httpContext,
  39. StoreManagerInterface $storeManager
  40. ) {
  41. $this->storeCookieManager = $storeCookieManager;
  42. $this->httpContext = $httpContext;
  43. $this->storeManager = $storeManager;
  44. }
  45. /**
  46. * @param StoreInterface $fromStore store where we came from
  47. * @param StoreInterface $targetStore store where to go to
  48. * @param string $redirectUrl original url requested for redirect after switching
  49. * @return string redirect url
  50. */
  51. public function switch(StoreInterface $fromStore, StoreInterface $targetStore, string $redirectUrl): string
  52. {
  53. $defaultStoreView = $this->storeManager->getDefaultStoreView();
  54. if ($defaultStoreView !== null) {
  55. if ($defaultStoreView->getId() === $targetStore->getId()) {
  56. $this->storeCookieManager->deleteStoreCookie($targetStore);
  57. } else {
  58. $this->httpContext->setValue(Store::ENTITY, $targetStore->getCode(), $defaultStoreView->getCode());
  59. $this->storeCookieManager->setStoreCookie($targetStore);
  60. }
  61. }
  62. return $redirectUrl;
  63. }
  64. }