Ensured NotFoundRedirectResolver replaces placeholders from the URL

This commit is contained in:
Alejandro Celaya
2021-10-03 16:45:13 +02:00
parent b0a8a03f0a
commit 994a28f31d
3 changed files with 72 additions and 22 deletions

View File

@@ -4,9 +4,11 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Core\Config;
use League\Uri\Exceptions\SyntaxError;
use League\Uri\Uri;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
use Psr\Log\LoggerInterface;
use Shlinkio\Shlink\Core\ErrorHandler\Model\NotFoundType;
use Shlinkio\Shlink\Core\Util\RedirectResponseHelperInterface;
@@ -18,8 +20,10 @@ class NotFoundRedirectResolver implements NotFoundRedirectResolverInterface
private const DOMAIN_PLACEHOLDER = '{DOMAIN}';
private const ORIGINAL_PATH_PLACEHOLDER = '{ORIGINAL_PATH}';
public function __construct(private RedirectResponseHelperInterface $redirectResponseHelper)
{
public function __construct(
private RedirectResponseHelperInterface $redirectResponseHelper,
private LoggerInterface $logger,
) {
}
public function resolveRedirectResponse(
@@ -48,13 +52,23 @@ class NotFoundRedirectResolver implements NotFoundRedirectResolverInterface
{
$domain = $currentUri->getAuthority();
$path = $currentUri->getPath();
$redirectUri = Uri::createFromString($redirectUrl);
try {
$redirectUri = Uri::createFromString($redirectUrl);
} catch (SyntaxError $e) {
$this->logger->warning('It was not possible to parse "{url}" as a valid URL: {e}', [
'e' => $e,
'url' => $redirectUrl,
]);
return $redirectUrl;
}
$replacePlaceholderForPattern = static fn (string $pattern, string $replace, callable $modifier) =>
static fn (?string $value) =>
$value === null ? null : str_replace($modifier($pattern), $modifier($replace), $value);
$replacePlaceholders = static fn (callable $modifier) => compose(
static fn (?string $value) =>
$value === null ? null : str_replace(self::DOMAIN_PLACEHOLDER, $modifier($domain), $value),
static fn (?string $value) =>
$value === null ? null : str_replace(self::ORIGINAL_PATH_PLACEHOLDER, $modifier($path), $value),
$replacePlaceholderForPattern(self::DOMAIN_PLACEHOLDER, $domain, $modifier),
$replacePlaceholderForPattern(self::ORIGINAL_PATH_PLACEHOLDER, $path, $modifier),
);
$replacePlaceholdersInPath = $replacePlaceholders('\Functional\id');
$replacePlaceholdersInQuery = $replacePlaceholders('\urlencode');