StoreSwitcher.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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;
  8. use Magento\Store\Api\Data\StoreInterface;
  9. use Magento\Store\Model\StoreSwitcher\CannotSwitchStoreException;
  10. /**
  11. * Handles store switching procedure and detects url for final redirect after store switching.
  12. */
  13. class StoreSwitcher implements StoreSwitcherInterface
  14. {
  15. /**
  16. * @var StoreSwitcherInterface[]
  17. */
  18. private $storeSwitchers;
  19. /**
  20. * @param StoreSwitcherInterface[] $storeSwitchers
  21. * @throws \Exception
  22. */
  23. public function __construct(array $storeSwitchers)
  24. {
  25. foreach ($storeSwitchers as $switcherName => $switcherInstance) {
  26. if (!$switcherInstance instanceof StoreSwitcherInterface) {
  27. throw new \InvalidArgumentException(
  28. "Store switcher '{$switcherName}' is expected to implement interface "
  29. . StoreSwitcherInterface::class
  30. );
  31. }
  32. }
  33. $this->storeSwitchers = $storeSwitchers;
  34. }
  35. /**
  36. * @param StoreInterface $fromStore store where we came from
  37. * @param StoreInterface $targetStore store where to go to
  38. * @param string $redirectUrl original url requested for redirect after switching
  39. * @return string url to be redirected after switching
  40. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  41. * @throws CannotSwitchStoreException
  42. */
  43. public function switch(StoreInterface $fromStore, StoreInterface $targetStore, string $redirectUrl): string
  44. {
  45. $targetUrl = $redirectUrl;
  46. foreach ($this->storeSwitchers as $storeSwitcher) {
  47. $targetUrl = $storeSwitcher->switch($fromStore, $targetStore, $targetUrl);
  48. }
  49. return $targetUrl;
  50. }
  51. }