@@ -59,6 +59,11 @@ class Url
5959 */
6060 protected $ storeId ;
6161
62+ /**
63+ * @var mixed
64+ */
65+ protected $ originalStore ;
66+
6267 /**
6368 * Initialize dependencies.
6469 *
@@ -188,19 +193,16 @@ public function getCanonicalUrl(\Magento\Framework\Model\AbstractModel $object)
188193
189194 $ storeChanged = false ;
190195 if ($ useOtherStore ) {
191- $ origStore = $ this ->_url ->getScope ();
192- if ($ newStore ->getId () != $ origStore ->getId ()) {
193- $ this ->_url ->setScope ($ newStore );
194- $ this ->setStoreId ($ newStore ->getId ());
196+ if ($ newStore ->getId () != $ this ->_url ->getScope ()->getId ()) {
197+ $ this ->startStoreEmulation ($ newStore );
195198 $ storeChanged = true ;
196199 }
197200 }
198201
199202 $ url = $ this ->getUrl ($ object , $ object ->getControllerName ());
200203
201204 if ($ storeChanged ) {
202- $ this ->_url ->setScope ($ origStore );
203- $ this ->setStoreId ($ origStore ->getId ());
205+ $ this ->stopStoreEmulation ();
204206 }
205207
206208 return $ url ;
@@ -366,7 +368,7 @@ public function getMediaUrl($file)
366368 return $ this ->_storeManager ->getStore ()
367369 ->getBaseUrl (\Magento \Framework \UrlInterface::URL_TYPE_MEDIA ) . $ file ;
368370 }
369-
371+
370372 /**
371373 * @return int|null
372374 */
@@ -385,6 +387,37 @@ public function setStoreId($storeId)
385387 return $ this ;
386388 }
387389
390+ /**
391+ * Start blog URL store emulation
392+ * @param $store
393+ * @throws \Exception
394+ */
395+ public function startStoreEmulation ($ store )
396+ {
397+ if (null !== $ this ->originalStore ) {
398+ throw new \Exception ('Cannot start Blog URL store emulation, emulation already started. ' );
399+ }
400+
401+ $ this ->originalStore = $ this ->_url ->getScope ();
402+ $ this ->setStoreId ($ store ->getId ());
403+ $ this ->_url ->setScope ($ store );
404+ }
405+
406+ /**
407+ * Stop blog URL store emulation
408+ */
409+ public function stopStoreEmulation ()
410+ {
411+ if ($ this ->originalStore ) {
412+ $ this ->setStoreId ($ this ->originalStore ->getId ());
413+ $ this ->_url ->setScope ($ this ->originalStore );
414+ } else {
415+ $ this ->setStoreId (null );
416+ $ this ->_url ->setScope (null );
417+ }
418+ $ this ->originalStore = null ;
419+ }
420+
388421 /**
389422 * Retrieve blog permalink config value
390423 * @param string $key
0 commit comments