Skip to content

Commit e64be5e

Browse files
authored
feat: Add isAvailable() method to AbstractCommand (#10228)
* feat: Add `isAvailable()` method to AbstractCommand * Add docs and changelog * cs-fix * fix some english and references * apply suggestions * Add period * apply suggestions * Added more tests * Revert PHPStorm's auto styled code
1 parent 17e9fc3 commit e64be5e

10 files changed

Lines changed: 226 additions & 10 deletions

File tree

‎system/CLI/AbstractCommand.php‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
use CodeIgniter\CLI\Attributes\Command;
1717
use CodeIgniter\CLI\Exceptions\ArgumentCountMismatchException;
18+
use CodeIgniter\CLI\Exceptions\CommandNotAvailableException;
1819
use CodeIgniter\CLI\Exceptions\InvalidArgumentDefinitionException;
1920
use CodeIgniter\CLI\Exceptions\InvalidOptionDefinitionException;
2021
use CodeIgniter\CLI\Exceptions\OptionValueMismatchException;
@@ -390,31 +391,37 @@ public function setInteractive(bool $interactive): static
390391
*
391392
* The lifecycle is:
392393
*
393-
* 1. `initialize()` and `interact()` are handed the raw parsed input by reference, in that order.
394+
* 1. Run `isAvailable()` to check if the command can be run in the current environment.
395+
* 2. `initialize()` and `interact()` are handed the raw parsed input by reference, in that order.
394396
* Both can mutate the tokens before the framework interprets them against the declared definitions.
395397
* Note: the per-run interactive state is captured from `$options` before `initialize()` runs, so
396398
* mutating `--no-interaction` from within `initialize()` will not affect this invocation. Use
397399
* `setInteractive()` instead.
398-
* 2. The post-hook input is snapshotted into `$unboundArguments` and `$unboundOptions` so the unbound
400+
* 3. The post-hook input is snapshotted into `$unboundArguments` and `$unboundOptions` so the unbound
399401
* accessors can report the tokens carried into binding (as opposed to what defaults resolved to).
400402
* Any mutations performed in `initialize()` or `interact()` are therefore reflected in the snapshot.
401-
* 3. `bind()` maps the raw tokens onto the declared arguments and options, applying defaults and
403+
* 4. `bind()` maps the raw tokens onto the declared arguments and options, applying defaults and
402404
* coercing flag/negation values.
403-
* 4. `validate()` rejects the bound result if it violates any of the declarations — missing required
405+
* 5. `validate()` rejects the bound result if it violates any of the declarations — missing required
404406
* argument, unknown option, value/flag mismatches, and so on.
405-
* 5. The bound-and-validated values are snapshotted into `$validatedArguments` / `$validatedOptions`
407+
* 6. The bound-and-validated values are snapshotted into `$validatedArguments` / `$validatedOptions`
406408
* and then passed to `execute()`, whose integer return is the command's exit code.
407409
*
408410
* @param list<string> $arguments Parsed arguments from command line.
409411
* @param array<string, list<string|null>|string|null> $options Parsed options from command line.
410412
*
411413
* @throws ArgumentCountMismatchException
414+
* @throws CommandNotAvailableException
412415
* @throws LogicException
413416
* @throws OptionValueMismatchException
414417
* @throws UnknownOptionException
415418
*/
416419
final public function run(array $arguments, array $options): int
417420
{
421+
if (! $this->isAvailable()) {
422+
throw new CommandNotAvailableException(lang('Commands.notAvailable', [$this->name]));
423+
}
424+
418425
// Reset per-run interactive state from the current options.
419426
$this->runtimeInteractive = $this->hasUnboundOption('no-interaction', $options) ? false : null;
420427

@@ -449,6 +456,14 @@ protected function configure(): void
449456
{
450457
}
451458

459+
/**
460+
* Checks whether this command is available to execute in the current environment.
461+
*/
462+
protected function isAvailable(): bool
463+
{
464+
return true;
465+
}
466+
452467
/**
453468
* Initializes a command before the arguments and options are bound to their definitions.
454469
*
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter\CLI\Exceptions;
15+
16+
use CodeIgniter\Exceptions\RuntimeException;
17+
18+
/**
19+
* Exception thrown when a command is found but is not currently available for execution.
20+
*/
21+
final class CommandNotAvailableException extends RuntimeException
22+
{
23+
}

‎system/Language/en/Commands.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
'noArgumentsExpected' => 'No arguments expected for "{0}" command. Received: "{1}".',
4848
'nonArrayArgumentWithArrayDefault' => 'Argument "{0}" does not accept an array default value.',
4949
'nonArrayOptionWithArrayValue' => 'Option "--{0}" does not accept an array value.',
50+
'notAvailable' => 'Command "{0}" is not available in the current environment.',
5051
'optionClashesWithExistingNegation' => 'Option "--{0}" clashes with the negation of negatable option "--{1}".',
5152
'optionNoValueAndNoDefault' => 'Option "--{0}" does not accept a value and cannot have a default value.',
5253
'optionNotAcceptingValue' => 'Option "--{0}" does not accept a value.',
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace Tests\Support\Commands\Modern;
15+
16+
use CodeIgniter\CLI\AbstractCommand;
17+
use CodeIgniter\CLI\Attributes\Command;
18+
19+
#[Command(name: 'test:unavailable', description: 'Fixture command to test runtime availability checks.', group: 'Tests')]
20+
final class UnavailableFixtureCommand extends AbstractCommand
21+
{
22+
public static bool $initializeCalled = false;
23+
public static bool $interactCalled = false;
24+
public static bool $executeCalled = false;
25+
public static bool $available = true;
26+
27+
public static function reset(): void
28+
{
29+
self::$initializeCalled = false;
30+
self::$interactCalled = false;
31+
self::$executeCalled = false;
32+
self::$available = true;
33+
}
34+
35+
protected function isAvailable(): bool
36+
{
37+
return self::$available;
38+
}
39+
40+
protected function initialize(array &$arguments, array &$options): void
41+
{
42+
self::$initializeCalled = true;
43+
}
44+
45+
protected function interact(array &$arguments, array &$options): void
46+
{
47+
self::$interactCalled = true;
48+
}
49+
50+
protected function execute(array $arguments, array $options): int
51+
{
52+
self::$executeCalled = true;
53+
54+
return EXIT_SUCCESS;
55+
}
56+
}

‎tests/system/CLI/AbstractCommandTest.php‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
use CodeIgniter\CLI\Attributes\Command;
1717
use CodeIgniter\CLI\Exceptions\ArgumentCountMismatchException;
18+
use CodeIgniter\CLI\Exceptions\CommandNotAvailableException;
1819
use CodeIgniter\CLI\Exceptions\InvalidArgumentDefinitionException;
1920
use CodeIgniter\CLI\Exceptions\InvalidOptionDefinitionException;
2021
use CodeIgniter\CLI\Exceptions\OptionValueMismatchException;
@@ -40,6 +41,7 @@
4041
use Tests\Support\Commands\Modern\InteractiveStateProbeCommand;
4142
use Tests\Support\Commands\Modern\ParentCallsInteractFixtureCommand;
4243
use Tests\Support\Commands\Modern\TestFixtureCommand;
44+
use Tests\Support\Commands\Modern\UnavailableFixtureCommand;
4345
use Throwable;
4446

4547
/**
@@ -60,6 +62,7 @@ protected function resetAll(): void
6062
CLI::reset();
6163

6264
InteractiveStateProbeCommand::reset();
65+
UnavailableFixtureCommand::reset();
6366
}
6467

6568
private function getUndecoratedBuffer(): string
@@ -930,6 +933,48 @@ public function testCallPreservesCallerFlagWhenForcingNonInteractive(): void
930933
$this->assertFalse(InteractiveStateProbeCommand::$observedInteractive);
931934
}
932935

936+
public function testRunThrowsWhenCommandIsUnavailable(): void
937+
{
938+
$command = new UnavailableFixtureCommand(new Commands());
939+
940+
UnavailableFixtureCommand::$available = false;
941+
942+
$this->expectException(CommandNotAvailableException::class);
943+
$this->expectExceptionMessage('Command "test:unavailable" is not available in the current environment.');
944+
945+
$command->run([], []);
946+
}
947+
948+
public function testRunExecutesWhenCommandIsAvailable(): void
949+
{
950+
$command = new UnavailableFixtureCommand(new Commands());
951+
952+
UnavailableFixtureCommand::$available = true;
953+
954+
$exitCode = $command->run([], []);
955+
956+
$this->assertSame(EXIT_SUCCESS, $exitCode);
957+
$this->assertTrue(UnavailableFixtureCommand::$initializeCalled);
958+
$this->assertTrue(UnavailableFixtureCommand::$interactCalled);
959+
$this->assertTrue(UnavailableFixtureCommand::$executeCalled);
960+
}
961+
962+
public function testRunChecksAvailabilityBeforeInitializeInteractAndExecute(): void
963+
{
964+
$command = new UnavailableFixtureCommand(new Commands());
965+
966+
UnavailableFixtureCommand::$available = false;
967+
968+
try {
969+
$command->run([], []);
970+
$this->fail('Expected CommandNotAvailableException was not thrown.');
971+
} catch (CommandNotAvailableException) {
972+
$this->assertFalse(UnavailableFixtureCommand::$initializeCalled);
973+
$this->assertFalse(UnavailableFixtureCommand::$interactCalled);
974+
$this->assertFalse(UnavailableFixtureCommand::$executeCalled);
975+
}
976+
}
977+
933978
/**
934979
* @param array<string, list<string|null>|string|null> $options
935980
*/

‎tests/system/Commands/HelpCommandTest.php‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,29 @@ public function testDescribeSpecificCommand(): void
126126
);
127127
}
128128

129+
public function testDescribeUnavailableCommand(): void
130+
{
131+
command('help test:unavailable');
132+
133+
$this->assertSame(
134+
<<<'EOT'
135+
136+
Usage:
137+
test:unavailable [options]
138+
139+
Description:
140+
Fixture command to test runtime availability checks.
141+
142+
Options:
143+
-h, --help Display help for the given command.
144+
--no-header Do not display the banner when running the command.
145+
-N, --no-interaction Do not ask any interactive questions.
146+
147+
EOT,
148+
$this->getUndecoratedBuffer(),
149+
);
150+
}
151+
129152
public function testDescribeLegacyCommandUsesLegacyShowHelp(): void
130153
{
131154
// `app:info` is a legacy BaseCommand fixture. Help must take the

‎tests/system/Commands/ListCommandsTest.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,14 @@ public function testRunCommandWithSimpleOption(): void
5858
$this->assertStringNotContainsString('Clears the current system caches.', $this->getStreamFilterBuffer());
5959
}
6060

61+
public function testUnavailableCommandIsStillListed(): void
62+
{
63+
command('list');
64+
65+
$this->assertStringContainsString('test:unavailable', $this->getStreamFilterBuffer());
66+
$this->assertStringContainsString('Fixture command to test runtime availability checks.', $this->getStreamFilterBuffer());
67+
}
68+
6169
public function testDuplicateCommandNameListedOnceInSimpleOutput(): void
6270
{
6371
$list = new ListCommands($this->mockRunnerWithDuplicate());

‎user_guide_src/source/changelogs/v4.8.0.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ Commands
183183
========
184184

185185
- Added a new attribute-based command style built on :php:class:`AbstractCommand <CodeIgniter\\CLI\\AbstractCommand>` and the ``#[Command]`` attribute,
186-
with ``configure()`` / ``initialize()`` / ``interact()`` / ``execute()`` hooks and typed ``Argument`` / ``Option`` definitions.
186+
with ``configure()`` / ``isAvailable()`` / ``initialize()`` / ``interact()`` / ``execute()`` hooks and typed ``Argument`` / ``Option`` definitions.
187187
The legacy ``BaseCommand`` style continues to work. See :doc:`../cli/cli_modern_commands`.
188188
- Every modern command now ships with a ``--no-interaction`` / ``-N`` flag that skips the ``interact()`` hook, plus public
189189
``isInteractive()`` / ``setInteractive()`` methods on ``AbstractCommand``. ``isInteractive()`` also auto-detects piped or

‎user_guide_src/source/cli/cli_modern_commands.rst‎

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,19 +68,21 @@ this order:
6868
extra usage examples. A default ``--help``/ ``-h`` flag, ``--no-header``
6969
flag, and ``--no-interaction``/ ``-N`` flag are added automatically
7070
afterwards.
71-
2. ``initialize(array &$arguments, array &$options): void`` receives the raw
71+
2. ``isAvailable(): bool`` is called to check whether the command should execute
72+
(see :ref:`restricting-execution`).
73+
3. ``initialize(array &$arguments, array &$options): void`` receives the raw
7274
arguments and options by reference. Useful when your command needs to
7375
massage input — for instance, to unfold an alias argument into the canonical
7476
form before anything else runs.
75-
3. ``interact(array &$arguments, array &$options): void`` also receives the
77+
4. ``interact(array &$arguments, array &$options): void`` also receives the
7678
raw arguments and options by reference. This is where you prompt the user
7779
for missing input, set values conditionally, or abort early. This hook is
7880
skipped when the command is non-interactive (see :ref:`non-interactive-mode`).
79-
4. **Bind & validate.** The framework maps the raw input to the definitions
81+
5. **Bind & validate.** The framework maps the raw input to the definitions
8082
you declared in ``configure()``, applies defaults, and rejects input that
8183
violates the definitions (missing required argument, unknown option, array
8284
option passed without a value, and so on).
83-
5. ``execute(array $arguments, array $options): int`` receives the bound and
85+
6. ``execute(array $arguments, array $options): int`` receives the bound and
8486
validated arguments and options, and returns an exit code.
8587

8688
You only have to implement ``execute()``; the other hooks are optional.
@@ -223,6 +225,26 @@ parameter of ``call()``:
223225
child ``$options`` so the sub-command resolves its own state. Note: TTY
224226
detection can still downgrade the sub-command if STDIN is not a TTY.
225227

228+
.. _restricting-execution:
229+
230+
*****************************
231+
Restricting Command Execution
232+
*****************************
233+
234+
Sometimes a command should not run in a specific runtime context. For example,
235+
development-only commands may need to be blocked in the ``production`` environment.
236+
237+
You can override ``isAvailable()`` to decide at runtime whether the command may execute.
238+
By default, this method returns ``true``.
239+
240+
.. literalinclude:: cli_modern_commands/013.php
241+
242+
The availability check runs before ``initialize()``, ``interact()``, argument and
243+
option binding, validation, and ``execute()``. If the command is not available,
244+
a ``CommandNotAvailableException`` is thrown immediately.
245+
246+
.. note:: This method prevents execution of the command, but does not remove it from help output or command discovery.
247+
226248
******************
227249
Inside execute()
228250
******************
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
namespace App\Commands;
4+
5+
use CodeIgniter\CLI\AbstractCommand;
6+
use CodeIgniter\CLI\Attributes\Command;
7+
8+
#[Command(name: 'dev:only', description: 'A dev only command', group: 'Dev')]
9+
class DevOnly extends AbstractCommand
10+
{
11+
protected function isAvailable(): bool
12+
{
13+
// Only allow this command in the development environment
14+
return ENVIRONMENT === 'development';
15+
}
16+
17+
protected function execute(array $arguments, array $options): int
18+
{
19+
// ...
20+
21+
return EXIT_SUCCESS;
22+
}
23+
}

0 commit comments

Comments
 (0)