Make WordPress Core

Opened 4 months ago

#61647 new enhancement

Catch ArgumentCountError in apply_filters, and prompt developers to check accepted_args

Reported by: gqqnbig's profile gqqnbig Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 6.6
Component: General Keywords:
Focuses: Cc:

Description

diff --git a/src/wp-includes/class-wp-hook.php b/src/wp-includes/class-wp-hook.php
index d95691d..f91f986 100644
--- a/src/wp-includes/class-wp-hook.php
+++ b/src/wp-includes/class-wp-hook.php
@@ -317,13 +317,17 @@ final class WP_Hook implements Iterator, ArrayAccess {
 					$args[0] = $value;
 				}
 
-				// Avoid the array_slice() if possible.
-				if ( 0 === $the_['accepted_args'] ) {
-					$value = call_user_func( $the_['function'] );
-				} elseif ( $the_['accepted_args'] >= $num_args ) {
-					$value = call_user_func_array( $the_['function'], $args );
-				} else {
-					$value = call_user_func_array( $the_['function'], array_slice( $args, 0, $the_['accepted_args'] ) );
+				try {
+					// Avoid the array_slice() if possible.
+					if (0 === $the_['accepted_args']) {
+						$value = call_user_func($the_['function']);
+					} elseif ($the_['accepted_args'] >= $num_args) {
+						$value = call_user_func_array($the_['function'], $args);
+					} else {
+						$value = call_user_func_array($the_['function'], array_slice($args, 0, $the_['accepted_args']));
+					}
+				} catch (ArgumentCountError $e) {
+					throw new ArgumentCountError($e->getMessage() . ". Did you set a correct accepted_args in add_action() or add_filter()?");
 				}
 			}
 		} while ( false !== next( $this->iterations[ $nesting_level ] ) );

I would like to propose this change. Add try-catch block around call_user_func_array in apply_filters(), so that (beginner) developers are hinted that they might forget to change accepted_args.

As a beginner WordPress developer, I encounter ArgumentCountError when I write the following code. I wasn't aware of the optional argument $accepted_args. My pull request thus gives a hint.

<?php
add_action('update_option', 'option_changed');


function option_changed($option_name, $old_value, $new_value) {
        ...
}

Change History (0)

Note: See TracTickets for help on using tickets.