I18N: Fix a PHP fatal when `get_locale()` is called before `$wpdb` is ready.

If WPDB needs to bail early, it loads the translations, which need to load the locale. Without WPDB, we can't get any database options, so can only rely on what's been loaded so far.

Fixes #29783.



git-svn-id: https://develop.svn.wordpress.org/trunk@38976 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Gary Pendergast 2016-10-27 03:42:09 +00:00
parent eb9e2b9207
commit dcc71eddcd
2 changed files with 44 additions and 1 deletions

View File

@ -28,7 +28,7 @@
* @return string The locale of the blog or from the {@see 'locale'} hook.
*/
function get_locale() {
global $locale, $wp_local_package;
global $locale, $wp_local_package, $wpdb;
if ( isset( $locale ) ) {
/**
@ -50,6 +50,15 @@ function get_locale() {
$locale = WPLANG;
}
// If $wpdb hasn't been initialised yet, we can only return what we have.
if ( ! $wpdb ) {
if ( ! $locale ) {
return 'en_US';
}
return $locale;
}
// If multisite, check options.
if ( is_multisite() ) {
// Don't check blog option when installing.

View File

@ -81,6 +81,40 @@ class Tests_L10n_GetLocale extends WP_UnitTestCase {
$this->assertSame( 'en_US', $found );
}
public function test_should_fall_back_on_locale_when_wpdb_is_unavailable() {
global $locale, $wpdb;
$old_locale = $locale;
$old_wpdb = $wpdb;
$locale = $expected = "Is this a locale? No. No it isn't.";
$wpdb = null;
$found = get_locale();
$locale = $old_locale;
$wpdb = $old_wpdb;
$this->assertSame( $expected, $found );
}
public function test_should_fall_back_on_es_US_when_locale_and_wpdb_are_unavailable() {
global $locale, $wpdb;
$old_locale = $locale;
$old_wpdb = $wpdb;
$locale = null;
$wpdb = null;
$found = get_locale();
$locale = $old_locale;
$wpdb = $old_wpdb;
$this->assertSame( 'en_US', $found );
}
public function test_should_respect_get_locale_filter() {
add_filter( 'locale', array( $this, 'filter_get_locale' ) );
$found = get_locale();