@@ -92,36 +92,42 @@ private function resolveByLinkUrl(string $uri): string
9292
9393 private function resolveByWebUrl (string $ uri ): string
9494 {
95- $ matches = [];
95+ $ storeMatch = null ;
96+ $ highestScore = 0 ;
9697
9798 /** @var Store $store */
9899 foreach ($ this ->storeRepository ->getList () as $ store ) {
99100 if ($ store ->getId () && str_starts_with ($ uri , $ store ->getBaseUrl (UrlInterface::URL_TYPE_WEB ))) {
100101 try {
101- $ website = $ store ->getWebsite ();
102- if ($ website ->getIsDefault ()) {
103- if ((int )$ website ->getDefaultGroup ()->getDefaultStoreId () === (int )$ store ->getId ()) {
104- // If it's the default store from the default group of the default website
105- return $ store ->getCode ();
106- }
107- if (!isset ($ matches [0 ]) && $ store ->isDefault ()) {
108- // If it's the default store from any group of the default website
109- $ matches [0 ] = $ store ->getCode ();
110- } elseif (!isset ($ matches [1 ])) {
111- // If it's any store from the default website
112- $ matches [1 ] = $ store ->getCode ();
113- }
114- } elseif (!isset ($ matches [2 ]) && $ store ->isDefault ()) {
115- // If nothing match, any default store has the priority
116- $ matches [2 ] = $ store ->getCode ();
117- } elseif (!isset ($ matches [3 ])) {
118- // If nothing match, we use the first store we found
119- $ matches [3 ] = $ store ->getCode ();
102+ $ score = $ this ->calculatePreferenceScore ($ store );
103+ $ storeMatch ??= $ store ->getCode ();
104+ if ($ highestScore < $ score ) {
105+ $ highestScore = $ score ;
106+ $ storeMatch = $ store ->getCode ();
120107 }
121108 } catch (NoSuchEntityException ) {}
122109 }
123110 }
124111
125- return $ matches [0 ] ?? $ matches [1 ] ?? $ matches [2 ] ?? $ matches [3 ] ?? '' ;
112+ return $ storeMatch ?? '' ;
113+ }
114+
115+ /**
116+ * @throws NoSuchEntityException
117+ */
118+ private function calculatePreferenceScore (Store $ store ): int
119+ {
120+ $ score = 0 ;
121+ $ website = $ store ->getWebsite ();
122+ if ($ website ->getIsDefault ()) {
123+ // Bonus point for the stores which are part of one of the groups from the default website.
124+ $ score = in_array ($ store ->getGroupId (), $ website ->getGroupIds () ? 2 : 1 ;
125+ }
126+ // Extra point for the stores which are part of the default group of its website.
127+ $ score += (int )$ website ->getDefaultGroup ()->getDefaultStoreId () === (int )$ store ->getId () ? 1 : 0
128+ // Extra point is the store is the default one of its group.
129+ $ score += $ store ->isDefault () ? 1 : 0 ;
130+
131+ return $ score ;
126132 }
127133}
0 commit comments