FIX: Language parser matches with dashes or underscores (#31381)

Our language parser now incorrectly matches underscored locales:

```
[1] pry(main)> HttpLanguageParser.parse("zh-CN")
=> "zh_CN"
[2] pry(main)> HttpLanguageParser.parse("zh_CN")
=> "en_GB"
```

This commit makes sure the input can be agnostic of `-` or `_`
This commit is contained in:
Natalie Tay
2025-02-19 11:55:14 +08:00
committed by GitHub
parent b47e429b26
commit 143a824449
2 changed files with 21 additions and 1 deletions

View File

@ -6,7 +6,7 @@ module HttpLanguageParser
# headers use hyphens. # headers use hyphens.
require "http_accept_language" unless defined?(HttpAcceptLanguage) require "http_accept_language" unless defined?(HttpAcceptLanguage)
available_locales = I18n.available_locales.map { |locale| locale.to_s.tr("_", "-") } available_locales = I18n.available_locales.map { |locale| locale.to_s.tr("_", "-") }
parser = HttpAcceptLanguage::Parser.new(header) parser = HttpAcceptLanguage::Parser.new(header&.tr("_", "-"))
matched = parser.language_region_compatible_from(available_locales)&.tr("-", "_") matched = parser.language_region_compatible_from(available_locales)&.tr("-", "_")
matched || SiteSetting.default_locale matched || SiteSetting.default_locale
end end

View File

@ -0,0 +1,20 @@
# frozen_string_literal: true
describe HttpLanguageParser do
it "returns the default locale when no language is matched" do
expect(HttpLanguageParser.parse("")).to eq(SiteSetting.default_locale)
end
it "returns the matched locale when a language is matched" do
expect(HttpLanguageParser.parse("en")).to eq("en")
end
it "returns the matched locale when a language and region are matched" do
expect(HttpLanguageParser.parse("en-US")).to eq("en")
end
it "returns the matched locale regardless of dash or underscore usage" do
expect(HttpLanguageParser.parse("zh-CN")).to eq("zh_CN")
expect(HttpLanguageParser.parse("zh_CN")).to eq("zh_CN")
end
end