Skip to content

Commit ea344fb

Browse files
Copilotswissspidy
andcommitted
Add --hook parameter to shell command and tests
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
1 parent 0b57f1b commit ea344fb

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

‎features/shell.feature‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,29 @@ Feature: WordPress REPL
7777
"""
7878
history: -1: invalid option
7979
"""
80+
81+
Scenario: Shell with hook parameter
82+
Given a WP install
83+
And a session file:
84+
"""
85+
did_action('init');
86+
"""
87+
88+
When I run `wp shell --basic --hook=init < session`
89+
Then STDOUT should contain:
90+
"""
91+
int(1)
92+
"""
93+
94+
Scenario: Shell with hook parameter on already-fired hook
95+
Given a WP install
96+
And a session file:
97+
"""
98+
did_action('plugins_loaded');
99+
"""
100+
101+
When I run `wp shell --basic --hook=plugins_loaded < session`
102+
Then STDOUT should contain:
103+
"""
104+
int(1)
105+
"""

‎src/Shell_Command.php‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,55 @@ class Shell_Command extends WP_CLI_Command {
1919
* : Force the use of WP-CLI's built-in PHP REPL, even if the Boris or
2020
* PsySH PHP REPLs are available.
2121
*
22+
* [--hook=<hook>]
23+
* : Attach the shell to a specific WordPress action or filter hook.
24+
* ---
25+
* default: ''
26+
* ---
27+
*
2228
* ## EXAMPLES
2329
*
2430
* # Call get_bloginfo() to get the name of the site.
2531
* $ wp shell
2632
* wp> get_bloginfo( 'name' );
2733
* => string(6) "WP-CLI"
34+
*
35+
* # Start a shell after the 'init' action has fired.
36+
* $ wp shell --hook=init
2837
*/
2938
public function __invoke( $_, $assoc_args ) {
39+
$hook = Utils\get_flag_value( $assoc_args, 'hook', '' );
40+
41+
if ( $hook ) {
42+
// Attach shell execution to the specified hook.
43+
add_action(
44+
$hook,
45+
function () use ( $assoc_args ) {
46+
$this->start_shell( $assoc_args );
47+
}
48+
);
49+
50+
// Trigger WordPress lifecycle to reach the hook.
51+
if ( ! did_action( $hook ) ) {
52+
// Hook hasn't fired yet, so we need to let WordPress run.
53+
// The hook will be called during the normal WordPress lifecycle.
54+
return;
55+
} else {
56+
// Hook already fired, start the shell immediately.
57+
$this->start_shell( $assoc_args );
58+
}
59+
} else {
60+
// No hook specified, start immediately.
61+
$this->start_shell( $assoc_args );
62+
}
63+
}
64+
65+
/**
66+
* Start the shell REPL.
67+
*
68+
* @param array<string,bool|string> $assoc_args Associative arguments.
69+
*/
70+
private function start_shell( $assoc_args ) {
3071
$class = WP_CLI\Shell\REPL::class;
3172

3273
$implementations = array(

0 commit comments

Comments
 (0)