From 92e080465e07f3f1f9b25792c58cd0785fd36aff Mon Sep 17 00:00:00 2001 From: Jun Pataleta Date: Fri, 27 May 2022 14:24:29 +0800 Subject: [PATCH] MDL-72885 core: New weblib function get_html_lang_attribute_value() Converts a language code to hyphen-separated format in accordance to the BCP47 syntax appropriate for the HTML lang attribute. See https://datatracker.ietf.org/doc/html/rfc5646#section-2.1 https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang --- lib/tests/weblib_test.php | 26 ++++++++++++++++++++++++++ lib/weblib.php | 18 ++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/lib/tests/weblib_test.php b/lib/tests/weblib_test.php index 8fa7d6a9924..a6c6aa9b3c3 100644 --- a/lib/tests/weblib_test.php +++ b/lib/tests/weblib_test.php @@ -941,4 +941,30 @@ EXPECTED; $this->assertNotEquals($policydisabled, print_password_policy()); } + + /** + * Data provider for the testing get_html_lang_attribute_value(). + * + * @return string[][] + */ + public function get_html_lang_attribute_value_provider() { + return [ + 'Empty lang code' => [' ', 'unknown'], + 'English' => ['en', 'en'], + 'English, US' => ['en_us', 'en-us'], + ]; + } + + /** + * Test for get_html_lang_attribute_value(). + * + * @covers ::get_html_lang_attribute_value() + * @dataProvider get_html_lang_attribute_value_provider + * @param string $langcode The language code to convert. + * @param string $expected The expected converted value. + * @return void + */ + public function test_get_html_lang_attribute_value(string $langcode, string $expected): void { + $this->assertEquals($expected, get_html_lang_attribute_value($langcode)); + } } diff --git a/lib/weblib.php b/lib/weblib.php index 7b142723eed..ed2b73f163f 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -2206,6 +2206,24 @@ function highlightfast($needle, $haystack) { return str_replace('', '', join('', $parts)); } +/** + * Converts a language code to hyphen-separated format in accordance to the + * {@link https://datatracker.ietf.org/doc/html/rfc5646#section-2.1 BCP47 syntax}. + * + * For additional information, check out + * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang MDN web docs - lang}. + * + * @param string $langcode The language code to convert. + * @return string + */ +function get_html_lang_attribute_value(string $langcode): string { + if (empty(trim($langcode))) { + // If the language code passed is an empty string, return 'unknown'. + return 'unknown'; + } + return str_replace('_', '-', $langcode); +} + /** * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes. *