<?php
function maybe_change_user_language( $selected_lang, $user_lang, $site_lang ) {
if ( $selected_lang !== $site_lang ) {
$user_lang = $selected_lang;
}
return $user_lang;
}
// Tests - Scroll to the bottom for results.
function test_respect_user_language_preference( $expected, $site_lang, $user_lang, $selected_lang = 'English' ) {
$user_lang = maybe_change_user_language(
$selected_lang,
$user_lang,
$site_lang
);
echo 'Expected: ', $expected, PHP_EOL;
echo 'Actual: ', $user_lang, PHP_EOL;
return 'Result: ' . ( $expected === $user_lang ? 'Pass' : 'Fail' );
}
$tests = array(
'defaults with nothing selected' => array(
'expected' => 'English',
'site_lang' => 'English',
'user_lang' => 'English',
'selected_lang' => 'English',
),
'no existing preference and selects Spanish' => array(
'expected' => 'Spanish',
'site_lang' => 'English',
'user_lang' => 'English',
'selected_lang' => 'Spanish',
),
'already prefers Spanish and selects Spanish' => array(
'expected' => 'Spanish',
'site_lang' => 'English',
'user_lang' => 'Spanish',
'selected_lang' => 'Spanish',
),
'already prefers Spanish and selects nothing' => array(
'expected' => 'Spanish',
'site_language' => 'English',
'user_lang' => 'Spanish',
'selected_lang' => 'English',
),
);
foreach ( $tests as $test => $args ) {
$sep = str_pad( '', strlen( $test ), '=' );
echo $sep, PHP_EOL, $test, PHP_EOL, $sep, PHP_EOL;
echo test_respect_user_language_preference( ...array_values( $args ) ), PHP_EOL, PHP_EOL;
}
preferences:
27.74 ms | 405 KiB | 5 Q