From 4984081ef6a976396d709f576195906de4ac0bac Mon Sep 17 00:00:00 2001 From: Tonya Mork Date: Tue, 10 Oct 2023 12:50:19 +0000 Subject: [PATCH] Options, Meta APIs: Check setting group exists before search in unregister_setting(). Checks if the given `$option_group` exists before searching for the `$option_name`. Sets the `$pos` to `false`, as `array_search()` returns `false` if the option name (needle) does not exist. This changeset fixes 2 different PHP Warning|Notice scenarios: 1. When the global `$new_allowed_options` is `null`, fixes raising `Trying to access array offset on value of type null` PHP Notice (PHP 7.4) | Warning (on PHP 8). 2. When the global `$new_allowed_options` is an `array` and the setting group key does not exist, fixes raising "Undefined index: unknown_setting_group" PHP Notice (PHP 7) | Warning (on PHP 8). For both scenarios, the `array_search()` is skipped and the `$pos` is set to a default of `false`, i.e. which is the value returned when `array_search()` is unsuccessful. Props xknown, hellofromTonya, nicolefurlan, oglekler, SergeyBiryukov, shailu25. Fixes #57674. git-svn-id: https://develop.svn.wordpress.org/trunk@56817 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/option.php | 5 ++++- tests/phpunit/tests/option/registration.php | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/option.php b/src/wp-includes/option.php index c8136950307a3..4df0b81458b68 100644 --- a/src/wp-includes/option.php +++ b/src/wp-includes/option.php @@ -2903,7 +2903,10 @@ function unregister_setting( $option_group, $option_name, $deprecated = '' ) { $option_group = 'reading'; } - $pos = array_search( $option_name, (array) $new_allowed_options[ $option_group ], true ); + $pos = false; + if ( isset( $new_allowed_options[ $option_group ] ) ) { + $pos = array_search( $option_name, (array) $new_allowed_options[ $option_group ], true ); + } if ( false !== $pos ) { unset( $new_allowed_options[ $option_group ][ $pos ] ); diff --git a/tests/phpunit/tests/option/registration.php b/tests/phpunit/tests/option/registration.php index 04991e4a33832..9b0e418c91c57 100644 --- a/tests/phpunit/tests/option/registration.php +++ b/tests/phpunit/tests/option/registration.php @@ -149,4 +149,18 @@ public function test_unregister_setting_removes_default() { $this->assertFalse( has_filter( 'default_option_test_default', 'filter_default_option' ) ); } + + /** + * The test passes if a Notice | Warning | Error is not raised. Thus. the absence of a Notice | Warning | Error + * is an indicator the fix in the ticket resolves the issue. + * + * @ticket 57674 + * + * @covers ::unregister_setting + */ + public function test_unregister_invalid_setting_does_not_raise_php_notice_warning_or_error() { + $setting = uniqid(); + unregister_setting( $setting, $setting ); + $this->assertFalse( has_filter( 'default_option_' . $setting, 'filter_default_option' ) ); + } }