Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
RewriteUrl.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
14 
19 {
23  private $urlFinder;
24 
28  private $requestFactory;
29 
34  public function __construct(
35  UrlFinderInterface $urlFinder,
36  \Magento\Framework\HTTP\PhpEnvironment\RequestFactory $requestFactory
37  ) {
38  $this->urlFinder = $urlFinder;
39  $this->requestFactory = $requestFactory;
40  }
41 
48  public function switch(StoreInterface $fromStore, StoreInterface $targetStore, string $redirectUrl): string
49  {
50  $targetUrl = $redirectUrl;
52  $request = $this->requestFactory->create(['uri' => $targetUrl]);
53 
54  $urlPath = ltrim($request->getPathInfo(), '/');
55 
56  if ($targetStore->isUseStoreInUrl()) {
57  // Remove store code in redirect url for correct rewrite search
58  $storeCode = preg_quote($targetStore->getCode() . '/', '/');
59  $pattern = "@^($storeCode)@";
60  $urlPath = preg_replace($pattern, '', $urlPath);
61  }
62 
63  $oldStoreId = $fromStore->getId();
64  $oldRewrite = $this->urlFinder->findOneByData([
65  UrlRewrite::REQUEST_PATH => $urlPath,
66  UrlRewrite::STORE_ID => $oldStoreId,
67  ]);
68  if ($oldRewrite) {
69  // look for url rewrite match on the target store
70  $currentRewrite = $this->urlFinder->findOneByData([
71  UrlRewrite::REQUEST_PATH => $urlPath,
72  UrlRewrite::STORE_ID => $targetStore->getId(),
73  ]);
74  if (null === $currentRewrite) {
76  $targetUrl = $targetStore->getBaseUrl();
77  }
78  }
79 
80  return $targetUrl;
81  }
82 }
$pattern
Definition: website.php:22
$storeCode
Definition: indexer.php:15
__construct(UrlFinderInterface $urlFinder, \Magento\Framework\HTTP\PhpEnvironment\RequestFactory $requestFactory)
Definition: RewriteUrl.php:34