Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
80.00% covered (warning)
80.00%
8 / 10
100.00% covered (success)
100.00%
1 / 1
CRAP
n/a
0 / 0
Automattic\Jetpack\Extensions\Shared\determine_iso_639_locale
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * Shared locale helper for extensions that load assets from widgets.wp.com.
4 *
5 * Used by CDN-based loaders (Image Studio, AI Sidebar) that need to map the
6 * current user's WordPress locale to the ISO 639 language code used by the
7 * widgets.wp.com translation files at languages/{code}-v1.js.
8 *
9 * @package automattic/jetpack
10 */
11
12namespace Automattic\Jetpack\Extensions\Shared;
13
14if ( ! defined( 'ABSPATH' ) ) {
15    exit( 0 );
16}
17
18/**
19 * Determine the ISO 639 locale code for the current user.
20 *
21 * Normalizes the WordPress user locale to match widgets.wp.com translation
22 * file naming. Preserves region for a small set of locales where the region
23 * is meaningful (pt_br, zh_tw, zh_cn); strips the region for all others;
24 * falls back to 'en' when the locale is empty.
25 *
26 * @return string The ISO 639 language code, defaulting to 'en'.
27 */
28function determine_iso_639_locale(): string {
29    $language = get_user_locale();
30    $language = strtolower( $language );
31
32    if ( in_array( $language, array( 'pt_br', 'pt-br', 'zh_tw', 'zh-tw', 'zh_cn', 'zh-cn' ), true ) ) {
33        $language = str_replace( '_', '-', $language );
34    } else {
35        $language = preg_replace( '/([-_].*)$/i', '', $language );
36    }
37
38    if ( empty( $language ) ) {
39        return 'en';
40    }
41
42    return $language;
43}