From 202d0b86b3fe0ca480737a8ac6a0e585ee307ac5 Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Sun, 25 Feb 2024 17:13:54 +0100 Subject: [PATCH] Extract logic to match every type of redirect condition to its own private method --- .../RedirectRule/Entity/RedirectCondition.php | 40 +++++++++++++------ 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/module/Core/src/RedirectRule/Entity/RedirectCondition.php b/module/Core/src/RedirectRule/Entity/RedirectCondition.php index 72960d82..608acd06 100644 --- a/module/Core/src/RedirectRule/Entity/RedirectCondition.php +++ b/module/Core/src/RedirectRule/Entity/RedirectCondition.php @@ -25,22 +25,38 @@ class RedirectCondition extends AbstractEntity */ public function matchesRequest(ServerRequestInterface $request): bool { - if ($this->type === RedirectConditionType::QUERY_PARAM && $this->matchKey !== null) { - $query = $request->getQueryParams(); - $queryValue = $query[$this->matchKey] ?? null; - return $queryValue === $this->matchValue; + return match ($this->type) { + RedirectConditionType::QUERY_PARAM => $this->matchesQueryParam($request), + RedirectConditionType::LANGUAGE => $this->matchesLanguage($request), + default => false, + }; + } + + public function matchesQueryParam(ServerRequestInterface $request): bool + { + if ($this->matchKey !== null) { + return false; } - if ($this->type === RedirectConditionType::LANGUAGE && $request->hasHeader('Accept-Language')) { - $acceptedLanguages = explode(',', $request->getHeaderLine('Accept-Language')); - $normalizedLanguage = normalizeLocale($this->matchValue); + $query = $request->getQueryParams(); + $queryValue = $query[$this->matchKey] ?? null; - return some( - $acceptedLanguages, - static fn (string $lang) => normalizeLocale($lang) === $normalizedLanguage, - ); + return $queryValue === $this->matchValue; + } + + public function matchesLanguage(ServerRequestInterface $request): bool + { + $acceptLanguage = $request->getHeaderLine('Accept-Language'); + if ($acceptLanguage === '' || $acceptLanguage === '*') { + return false; } - return false; + $acceptedLanguages = explode(',', $acceptLanguage); + $normalizedLanguage = normalizeLocale($this->matchValue); + + return some( + $acceptedLanguages, + static fn (string $lang) => normalizeLocale($lang) === $normalizedLanguage, + ); } }