Skip to content

Commit 81e5e72

Browse files
Copilotswissspidy
andcommitted
Add validation and error handling for hook parameter
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
1 parent bb60d94 commit 81e5e72

2 files changed

Lines changed: 22 additions & 18 deletions

File tree

‎features/shell.feature‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ Feature: WordPress REPL
9191
int(1)
9292
"""
9393
94-
Scenario: Shell with hook parameter on already-fired hook
94+
Scenario: Shell with hook parameter using plugins_loaded hook
9595
Given a WP install
9696
And a session file:
9797
"""
@@ -103,3 +103,13 @@ Feature: WordPress REPL
103103
"""
104104
int(1)
105105
"""
106+
107+
Scenario: Shell with hook parameter for hook that hasn't fired
108+
Given a WP install
109+
110+
When I try `wp shell --basic --hook=shutdown < /dev/null`
111+
Then STDERR should contain:
112+
"""
113+
Error: The 'shutdown' hook has not fired yet
114+
"""
115+
And the return code should be 1

‎src/Shell_Command.php‎

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -39,29 +39,23 @@ public function __invoke( $_, $assoc_args ) {
3939
$hook = Utils\get_flag_value( $assoc_args, 'hook', '' );
4040

4141
if ( $hook ) {
42+
// Validate hook parameter.
43+
if ( ! is_string( $hook ) || '' === trim( $hook ) ) {
44+
WP_CLI::error( 'The --hook parameter must be a non-empty string.' );
45+
}
46+
4247
// Check if the hook has already fired.
4348
if ( did_action( $hook ) ) {
4449
// Hook already fired, start the shell immediately.
4550
$this->start_shell( $assoc_args );
4651
} else {
47-
// Hook hasn't fired yet. We need to attach a callback and let WordPress continue.
48-
// Since shell is interactive and blocks execution, we'll attach the callback
49-
// and let it start when the hook fires naturally.
50-
$shell_started = false;
51-
add_action(
52-
$hook,
53-
function () use ( $assoc_args, &$shell_started ) {
54-
if ( ! $shell_started ) {
55-
$shell_started = true;
56-
$this->start_shell( $assoc_args );
57-
}
58-
},
59-
10
52+
// Hook hasn't fired yet.
53+
WP_CLI::error(
54+
sprintf(
55+
"The '%s' hook has not fired yet. The shell command runs after WordPress is loaded, so only hooks that have already been triggered can be used. Common hooks that are available include: init, plugins_loaded, wp_loaded, admin_init.",
56+
$hook
57+
)
6058
);
61-
// Note: The shell will start when the hook fires during WordPress lifecycle.
62-
// Since commands typically run after WordPress is loaded, most common hooks
63-
// will have already fired. For hooks that haven't fired yet, the shell will
64-
// start when they do fire.
6559
}
6660
} else {
6761
// No hook specified, start immediately.

0 commit comments

Comments
 (0)