From 7e5a18cd7c3c6908cde396e638ec082e48db8a89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Richard=20Dobro=C5=88?= Date: Sun, 3 Mar 2024 20:47:09 +0100 Subject: [PATCH] Add locale detection guide --- docs/locale_detection.md | 49 ++++++++++++++++++++++++++++++++++++++++ website/sidebars.js | 1 + 2 files changed, 50 insertions(+) create mode 100644 docs/locale_detection.md diff --git a/docs/locale_detection.md b/docs/locale_detection.md new file mode 100644 index 0000000..2b9c973 --- /dev/null +++ b/docs/locale_detection.md @@ -0,0 +1,49 @@ +--- +id: locale_detection +title: Locale detection +sidebar_label: Locale detection +--- + +# How to detect the user's locale from the browser? + +## Installation +To implement locale detection in your PHP project, you can use the `HTTP2` library. You can install it via Composer: + +```shell +composer require pear/http2 +``` + +# Usage +After installing the `HTTP2 library`, you can utilize it in your PHP code to detect the user's locale. Here's a basic example: + +```php + 'en_US', + 'en-UK' => 'en_UK', + 'de' => 'de_DE', + 'de-AT' => 'de_AT', + 'cs' => 'cs_CZ', + 'sk' => 'sk_SK', +]; + +// Detect the user's language +$clientLanguage = $http->negotiateLanguage($supportedLanguages, $fallbackLanguage = 'en'); + +// Get the locale for the detected language +$locale = $supportedLanguages[$clientLanguage]; + +// Set the detected locale +\fbt\FbtConfig::set('locale', $locale); +``` + +# Explanation + +## HTTP Accept-Language Header +The `negotiateLanguage()` method works by parsing the HTTP `Accept-Language` header sent by the user's browser. This header contains information about the user's preferred languages in order of priority. The method then matches these languages against the provided list and returns the best match. + +## Fallback Locale +In case the user's preferred language is not available or cannot be determined, it's essential to have a fallback locale. This ensures that your application always defaults to a suitable language/locale even when the detection process fails. diff --git a/website/sidebars.js b/website/sidebars.js index c1a5b0a..ea6d3fa 100644 --- a/website/sidebars.js +++ b/website/sidebars.js @@ -12,6 +12,7 @@ module.exports = { docs: { "Getting started": [ "getting_started", + "locale_detection", "best_practices" ], API: [