A quick wp-cli command gotcha.
Command flags
wp-cli allows for very flexible and powerful commands to be put in place and its cookbook does a good job of going over the possibilities offered to package developers.
But I’ll admit I’ve skimmed the cookbook to jump into the code to the point that I’ve missed the “--no-option
cast” completely.
An example
In the code I’m working on the user can tell the command it should not ask any question and go straight through the default installation, to do so the user should use the --no-install
flag:
wp wpb-scaffold plugin-tests --no-interactive
To support the option I’ve updated the command registration like this:
<?php
use tad\WPCLI\Commands\Scaffold;
if ( ! class_exists( 'WP_CLI' ) ) {
return;
}
require_once 'vendor/autoload.php';
WP_CLI::add_command( 'wpb-scaffold', new Scaffold(), array(
'shortdesc' => 'Scaffolds wp-browser based tests for a plugin or theme',
'synopsis' => array(
array(
'type' => 'positional',
'name' => 'subcommand',
'optional' => false,
'multiple' => false,
),
array(
'type' => 'positional',
'name' => 'slug',
'optional' => true,
'multiple' => false,
),
array(
'type' => 'flag',
'name' => 'dry-run',
'optional' => true,
),
array(
'type' => 'flag',
'name' => 'no-install',
'optional' => true,
),
// [more options]...
)
) );
But when running the Behat tests I kept seeing an error about the --no-install
flag:
$ wp wpb-scaffold plugin-tests --no-install --dir="features/_data/temp" \
--description="Just a plugin" --name="Luca Tumedei" --email="luca@theaveragedev.com"
Error: Parameter errors:
unknown --install parameter
cwd: /var/folders/wy/b6dl58111nb62cr51c2_4xd00000gn/T/wp-cli-test-run-57fbcd772f2400.17409293/
exit status: 1
What seemed weird was the fact that the error is referring to the install parameter
.
Smarter than me
When I took my time to read the command cookbook I’ve found out that when an argument is registered as a flag
its value will be cast to false
if the user uses the flag prefixing it with --no-
.
I’ve modified the flag registration to use the install
name in place of the no-install
one and everything started working as intended.
<?php
use tad\WPCLI\Commands\Scaffold;
if ( ! class_exists( 'WP_CLI' ) ) {
return;
}
require_once 'vendor/autoload.php';
WP_CLI::add_command( 'wpb-scaffold', new Scaffold(), array(
'shortdesc' => 'Scaffolds wp-browser based tests for a plugin or theme',
'synopsis' => array(
array(
'type' => 'positional',
'name' => 'subcommand',
'optional' => false,
'multiple' => false,
),
array(
'type' => 'positional',
'name' => 'slug',
'optional' => true,
'multiple' => false,
),
array(
'type' => 'flag',
'name' => 'dry-run',
'optional' => true,
),
array(
'type' => 'flag',
'name' => 'install',
'optional' => true,
),
// [more options]...
)
) );
In the command picking up that flag is easy easy as an empty
check:
$shouldNotInstall = empty($assocArgs['install']);