Skip to content

Commit

Permalink
MDL-72885 core: New weblib function get_html_lang_attribute_value()
Browse files Browse the repository at this point in the history
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
  • Loading branch information
junpataleta committed May 27, 2022
1 parent 3bdd840 commit 92e0804
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
26 changes: 26 additions & 0 deletions lib/tests/weblib_test.php
Expand Up @@ -941,4 +941,30 @@ public function test_print_password_policy() {

$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));
}
}
18 changes: 18 additions & 0 deletions lib/weblib.php
Expand Up @@ -2206,6 +2206,24 @@ function highlightfast($needle, $haystack) {
return str_replace('<span class="highlight"></span>', '', 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.
*
Expand Down

0 comments on commit 92e0804

Please sign in to comment.