Skip to content

Commit

Permalink
fix: Add pathHasSitePrefix to handle edge-cases
Browse files Browse the repository at this point in the history
  • Loading branch information
khalwat committed Sep 20, 2024
1 parent 737a4ae commit 72297b1
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 6 deletions.
8 changes: 5 additions & 3 deletions src/gql/resolvers/RetourResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,11 @@ public static function resolve(mixed $source, array $arguments, mixed $context,
$path = $redirect['redirectDestUrl'];
// Combine the URL and path together, merging them as appropriate
try {
$dest = UrlHelper::siteUrl('/', null, null, $siteId);
$dest = UrlHelper::mergeUrlWithPath($dest, $path);
$dest = parse_url($dest, PHP_URL_PATH);
if (!UrlHelper::pathHasSitePrefix($path)) {
$dest = UrlHelper::siteUrl('/', null, null, $siteId);
$dest = UrlHelper::mergeUrlWithPath($dest, $path);
$dest = parse_url($dest, PHP_URL_PATH);
}
} catch (Throwable $e) {
// That's ok
}
Expand Down
25 changes: 25 additions & 0 deletions src/helpers/UrlHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace nystudio107\retour\helpers;

use Craft;
use craft\errors\SiteNotFoundException;
use craft\helpers\UrlHelper as CraftUrlHelper;

Expand Down Expand Up @@ -74,6 +75,30 @@ public static function stripSitePathPrefix(string $path): string
return $path;
}

/**
* See if the path includes a site prefix for any site
*
* @param string $path
* @return bool
*/
public static function pathHasSitePrefix(string $path): bool
{
$sites = Craft::$app->getSites()->getAllSites();
foreach ($sites as $site) {
$sitePath = parse_url($site->baseUrl, PHP_URL_PATH);
if (!empty($sitePath)) {
// Normalizes a URI path by trimming leading/ trailing slashes and removing double slashes
$sitePath = '/' . preg_replace('/\/\/+/', '/', trim($sitePath, '/'));
}
// Strip the $sitePath from the incoming $path
if (str_starts_with($path, $sitePath)) {
return true;
}
}

return false;
}

/**
* Merge the $url and $path together, combining any overlapping path segments
*
Expand Down
8 changes: 5 additions & 3 deletions src/services/Redirects.php
Original file line number Diff line number Diff line change
Expand Up @@ -829,9 +829,11 @@ public function doRedirect(string $fullUrl, string $pathOnly, ?array $redirect):
if ($siteId !== null) {
$siteId = (int)$siteId;
}
$dest = UrlHelper::siteUrl('/', null, null, $siteId);
$dest = UrlHelper::mergeUrlWithPath($dest, $path);
$dest = parse_url($dest, PHP_URL_PATH);
if (!UrlHelper::pathHasSitePrefix($path)) {
$dest = UrlHelper::siteUrl('/', null, null, $siteId);
$dest = UrlHelper::mergeUrlWithPath($dest, $path);
$dest = parse_url($dest, PHP_URL_PATH);
}
} catch (\yii\base\Exception $e) {
}
break;
Expand Down

0 comments on commit 72297b1

Please sign in to comment.