refactor: console improvements — auto-discovery, centralized bootstrap, per-command help
- ConsoleApplication.discoverCommands() scans lib/Console/Commands/ automatically; adding a new command no longer requires editing bin/console - Command base class provides bootstrapApp(), bootstrapModuleApp(), requireBinScript() and projectRoot() helpers — eliminates fragile 4-level relative require_once paths - Per-command --help support via optional usage() method on Command - Docker-compose scheduler updated to use bin/console scheduler:run - Old bin scripts now emit deprecation hint to stderr when called directly Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
26
bin/console
26
bin/console
@@ -9,35 +9,17 @@ declare(strict_types=1);
|
||||
* Usage:
|
||||
* php bin/console <command> [arguments] [options]
|
||||
* php bin/console list
|
||||
* php bin/console <command> --help
|
||||
*
|
||||
* Examples:
|
||||
* php bin/console module:sync
|
||||
* php bin/console module:deactivate addressbook --confirm
|
||||
* php bin/console scheduler:run
|
||||
* php bin/console doctor
|
||||
* Commands are auto-discovered from lib/Console/Commands/.
|
||||
* To add a new command, create a class extending Command in that directory.
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../vendor/autoload.php';
|
||||
|
||||
use MintyPHP\Console\ConsoleApplication;
|
||||
use MintyPHP\Console\Commands\DoctorCommand;
|
||||
use MintyPHP\Console\Commands\Module\AssetsSyncCommand;
|
||||
use MintyPHP\Console\Commands\Module\BuildCommand;
|
||||
use MintyPHP\Console\Commands\Module\DeactivateCommand;
|
||||
use MintyPHP\Console\Commands\Module\MigrateCommand;
|
||||
use MintyPHP\Console\Commands\Module\PermissionsSyncCommand;
|
||||
use MintyPHP\Console\Commands\Module\RuntimeSyncCommand;
|
||||
use MintyPHP\Console\Commands\Scheduler\RunCommand;
|
||||
|
||||
$app = new ConsoleApplication();
|
||||
|
||||
$app->register(new RuntimeSyncCommand());
|
||||
$app->register(new MigrateCommand());
|
||||
$app->register(new PermissionsSyncCommand());
|
||||
$app->register(new BuildCommand());
|
||||
$app->register(new AssetsSyncCommand());
|
||||
$app->register(new DeactivateCommand());
|
||||
$app->register(new RunCommand());
|
||||
$app->register(new DoctorCommand());
|
||||
$app->discoverCommands(__DIR__ . '/../lib/Console/Commands');
|
||||
|
||||
exit($app->run($argv));
|
||||
|
||||
@@ -56,5 +56,6 @@ function moduleAssetsSyncRun(): int
|
||||
}
|
||||
|
||||
if (PHP_SAPI === 'cli' && realpath((string) ($_SERVER['SCRIPT_FILENAME'] ?? '')) === __FILE__) {
|
||||
fwrite(STDERR, "Hint: prefer `php bin/console module:assets-sync` instead.\n");
|
||||
exit(moduleAssetsSyncRun());
|
||||
}
|
||||
|
||||
@@ -63,5 +63,6 @@ function moduleBuildRun(): int
|
||||
}
|
||||
|
||||
if (PHP_SAPI === 'cli' && realpath((string) ($_SERVER['SCRIPT_FILENAME'] ?? '')) === __FILE__) {
|
||||
fwrite(STDERR, "Hint: prefer `php bin/console module:build` instead.\n");
|
||||
exit(moduleBuildRun());
|
||||
}
|
||||
|
||||
@@ -85,5 +85,6 @@ function moduleDeactivateRun(): int
|
||||
}
|
||||
|
||||
if (PHP_SAPI === 'cli' && realpath((string) ($_SERVER['SCRIPT_FILENAME'] ?? '')) === __FILE__) {
|
||||
fwrite(STDERR, "Hint: prefer `php bin/console module:deactivate` instead.\n");
|
||||
exit(moduleDeactivateRun());
|
||||
}
|
||||
|
||||
@@ -246,5 +246,6 @@ function moduleMigrateSplitSqlStatements(string $sql): array
|
||||
}
|
||||
|
||||
if (PHP_SAPI === 'cli' && realpath((string) ($_SERVER['SCRIPT_FILENAME'] ?? '')) === __FILE__) {
|
||||
fwrite(STDERR, "Hint: prefer `php bin/console module:migrate` instead.\n");
|
||||
exit(moduleMigrateRun());
|
||||
}
|
||||
|
||||
@@ -50,5 +50,6 @@ function modulePermissionsSyncRun(): int
|
||||
}
|
||||
|
||||
if (PHP_SAPI === 'cli' && realpath((string) ($_SERVER['SCRIPT_FILENAME'] ?? '')) === __FILE__) {
|
||||
fwrite(STDERR, "Hint: prefer `php bin/console module:permissions-sync` instead.\n");
|
||||
exit(modulePermissionsSyncRun());
|
||||
}
|
||||
|
||||
@@ -72,5 +72,6 @@ function moduleRuntimeSyncRun(): int
|
||||
}
|
||||
|
||||
if (PHP_SAPI === 'cli' && realpath((string) ($_SERVER['SCRIPT_FILENAME'] ?? '')) === __FILE__) {
|
||||
fwrite(STDERR, "Hint: prefer `php bin/console module:sync` instead.\n");
|
||||
exit(moduleRuntimeSyncRun());
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ use MintyPHP\Service\Scheduler\SchedulerServicesFactory;
|
||||
|
||||
require_once __DIR__ . '/cli-bootstrap.php';
|
||||
|
||||
fwrite(STDERR, "Hint: prefer `php bin/console scheduler:run` instead.\n");
|
||||
$exitCode = 0;
|
||||
$startedAt = microtime(true);
|
||||
try {
|
||||
|
||||
@@ -44,7 +44,7 @@ services:
|
||||
depends_on:
|
||||
- db
|
||||
- memcached
|
||||
command: sh -lc "while true; do php -d display_errors=0 bin/scheduler-run.php || true; sleep 60; done"
|
||||
command: sh -lc "while true; do php -d display_errors=0 bin/console scheduler:run || true; sleep 60; done"
|
||||
restart: unless-stopped
|
||||
|
||||
db:
|
||||
|
||||
@@ -34,7 +34,7 @@ services:
|
||||
depends_on:
|
||||
- db
|
||||
- memcached
|
||||
command: sh -lc "while true; do php -d display_errors=0 bin/scheduler-run.php || true; sleep 60; done"
|
||||
command: sh -lc "while true; do php -d display_errors=0 bin/console scheduler:run || true; sleep 60; done"
|
||||
restart: unless-stopped
|
||||
|
||||
db:
|
||||
|
||||
@@ -6,7 +6,8 @@ namespace MintyPHP\Console;
|
||||
* Base class for CLI commands.
|
||||
*
|
||||
* Subclasses define a name (e.g. 'module:sync') and implement execute().
|
||||
* Arguments and options are passed as a simple parsed array.
|
||||
* Bootstrap helpers provide a stable way to initialize the app without
|
||||
* fragile relative paths.
|
||||
*/
|
||||
abstract class Command
|
||||
{
|
||||
@@ -14,10 +15,57 @@ abstract class Command
|
||||
|
||||
abstract public function description(): string;
|
||||
|
||||
/**
|
||||
* Optional usage text shown when --help is passed for this command.
|
||||
* Override in subclasses that accept arguments or options.
|
||||
*/
|
||||
public function usage(): string
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $args Positional arguments (after the command name)
|
||||
* @param array<string, string|bool> $options Parsed --key=value and --flag options
|
||||
* @return int Exit code (0 = success)
|
||||
*/
|
||||
abstract public function execute(array $args, array $options): int;
|
||||
|
||||
// ─── Bootstrap helpers ──────────────────────────────────────────
|
||||
|
||||
protected function projectRoot(): string
|
||||
{
|
||||
return dirname(__DIR__, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap the app for non-module CLI commands.
|
||||
* Wraps bin/cli-bootstrap.php with stable path resolution.
|
||||
*/
|
||||
protected function bootstrapApp(string $channel = 'cli', ?string $path = null): void
|
||||
{
|
||||
require_once $this->projectRoot() . '/bin/cli-bootstrap.php';
|
||||
|
||||
cliBootstrapApp($channel, $path ?? 'bin/console ' . $this->name());
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap the app for module CLI commands.
|
||||
* Loads the module CLI infrastructure (error policy, locking, app container).
|
||||
*/
|
||||
protected function bootstrapModuleApp(): void
|
||||
{
|
||||
require_once $this->projectRoot() . '/bin/module-cli-bootstrap.php';
|
||||
|
||||
moduleCliBootstrapApp();
|
||||
}
|
||||
|
||||
/**
|
||||
* Require a bin script by name (e.g. 'module-migrate.php').
|
||||
* Resolves the path from projectRoot — no fragile relative paths.
|
||||
*/
|
||||
protected function requireBinScript(string $filename): void
|
||||
{
|
||||
require_once $this->projectRoot() . '/bin/' . $filename;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,11 +18,9 @@ final class DoctorCommand extends Command
|
||||
|
||||
public function execute(array $args, array $options): int
|
||||
{
|
||||
// doctor.php is self-contained — include and let it run
|
||||
$scriptPath = __DIR__ . '/../../../bin/doctor.php';
|
||||
|
||||
// Capture the exit code by running as a subprocess to avoid
|
||||
// the script's own exit() call terminating our process.
|
||||
// doctor.php calls exit() internally — run as subprocess
|
||||
// to avoid terminating the console process.
|
||||
$scriptPath = $this->projectRoot() . '/bin/doctor.php';
|
||||
$command = PHP_BINARY . ' ' . escapeshellarg($scriptPath);
|
||||
passthru($command, $exitCode);
|
||||
|
||||
|
||||
@@ -18,8 +18,8 @@ final class AssetsSyncCommand extends Command
|
||||
|
||||
public function execute(array $args, array $options): int
|
||||
{
|
||||
require_once __DIR__ . '/../../../../bin/module-cli-bootstrap.php';
|
||||
require_once __DIR__ . '/../../../../bin/module-assets-sync.php';
|
||||
$this->requireBinScript('module-cli-bootstrap.php');
|
||||
$this->requireBinScript('module-assets-sync.php');
|
||||
|
||||
return moduleAssetsSyncRun();
|
||||
}
|
||||
|
||||
@@ -18,8 +18,8 @@ final class BuildCommand extends Command
|
||||
|
||||
public function execute(array $args, array $options): int
|
||||
{
|
||||
require_once __DIR__ . '/../../../../bin/module-cli-bootstrap.php';
|
||||
require_once __DIR__ . '/../../../../bin/module-build.php';
|
||||
$this->requireBinScript('module-cli-bootstrap.php');
|
||||
$this->requireBinScript('module-build.php');
|
||||
|
||||
return moduleBuildRun();
|
||||
}
|
||||
|
||||
@@ -13,14 +13,27 @@ final class DeactivateCommand extends Command
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Run a module\'s deactivation handler (--confirm or --dry-run)';
|
||||
return 'Run a module\'s deactivation handler';
|
||||
}
|
||||
|
||||
public function usage(): string
|
||||
{
|
||||
return <<<'USAGE'
|
||||
Usage: php bin/console module:deactivate <module-id> [options]
|
||||
|
||||
Options:
|
||||
--confirm Execute the deactivation handler
|
||||
--dry-run Validate the handler without executing
|
||||
|
||||
The module does not need to be in the enabled list.
|
||||
USAGE;
|
||||
}
|
||||
|
||||
public function execute(array $args, array $options): int
|
||||
{
|
||||
$moduleId = $args[0] ?? '';
|
||||
if ($moduleId === '') {
|
||||
fwrite(STDERR, "Usage: php bin/console module:deactivate <module-id> --confirm|--dry-run\n");
|
||||
fwrite(STDERR, $this->usage() . "\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -34,7 +47,7 @@ final class DeactivateCommand extends Command
|
||||
$argv[] = '--dry-run';
|
||||
}
|
||||
|
||||
require_once __DIR__ . '/../../../../bin/module-deactivate.php';
|
||||
$this->requireBinScript('module-deactivate.php');
|
||||
|
||||
return moduleDeactivateRun();
|
||||
}
|
||||
|
||||
@@ -18,8 +18,8 @@ final class MigrateCommand extends Command
|
||||
|
||||
public function execute(array $args, array $options): int
|
||||
{
|
||||
require_once __DIR__ . '/../../../../bin/module-cli-bootstrap.php';
|
||||
require_once __DIR__ . '/../../../../bin/module-migrate.php';
|
||||
$this->requireBinScript('module-cli-bootstrap.php');
|
||||
$this->requireBinScript('module-migrate.php');
|
||||
|
||||
return moduleMigrateRun();
|
||||
}
|
||||
|
||||
@@ -18,8 +18,8 @@ final class PermissionsSyncCommand extends Command
|
||||
|
||||
public function execute(array $args, array $options): int
|
||||
{
|
||||
require_once __DIR__ . '/../../../../bin/module-cli-bootstrap.php';
|
||||
require_once __DIR__ . '/../../../../bin/module-permissions-sync.php';
|
||||
$this->requireBinScript('module-cli-bootstrap.php');
|
||||
$this->requireBinScript('module-permissions-sync.php');
|
||||
|
||||
return modulePermissionsSyncRun();
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ final class RuntimeSyncCommand extends Command
|
||||
|
||||
public function execute(array $args, array $options): int
|
||||
{
|
||||
require_once __DIR__ . '/../../../../bin/module-runtime-sync.php';
|
||||
$this->requireBinScript('module-runtime-sync.php');
|
||||
|
||||
return moduleRuntimeSyncRun();
|
||||
}
|
||||
|
||||
@@ -21,12 +21,11 @@ final class RunCommand extends Command
|
||||
|
||||
public function execute(array $args, array $options): int
|
||||
{
|
||||
require_once __DIR__ . '/../../../../bin/cli-bootstrap.php';
|
||||
$this->bootstrapApp('scheduler');
|
||||
|
||||
$exitCode = 0;
|
||||
$startedAt = microtime(true);
|
||||
try {
|
||||
cliBootstrapApp('scheduler', 'bin/console scheduler:run');
|
||||
$factory = app(SchedulerServicesFactory::class);
|
||||
$result = $factory->createSchedulerRunService()->runDueJobs();
|
||||
if (!($result['ok'] ?? false)) {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
namespace MintyPHP\Console;
|
||||
|
||||
/**
|
||||
* Minimal CLI command dispatcher.
|
||||
* Minimal CLI command dispatcher with auto-discovery.
|
||||
*
|
||||
* Parses argv into command name, positional args, and --options,
|
||||
* then dispatches to the matching registered Command instance.
|
||||
@@ -18,6 +18,63 @@ final class ConsoleApplication
|
||||
$this->commands[$command->name()] = $command;
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-discover and register all Command subclasses in a directory.
|
||||
*
|
||||
* Scans PHP files recursively, extracts the FQCN from namespace + class name,
|
||||
* and registers any concrete Command subclass found.
|
||||
*/
|
||||
public function discoverCommands(string $directory): void
|
||||
{
|
||||
if (!is_dir($directory)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS),
|
||||
\RecursiveIteratorIterator::LEAVES_ONLY
|
||||
);
|
||||
|
||||
foreach ($iterator as $file) {
|
||||
if ($file->getExtension() !== 'php') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$content = file_get_contents($file->getPathname());
|
||||
if ($content === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Extract namespace and class name from file
|
||||
$namespace = '';
|
||||
if (preg_match('/^namespace\s+(.+?);/m', $content, $nsMatch)) {
|
||||
$namespace = $nsMatch[1];
|
||||
}
|
||||
|
||||
$className = '';
|
||||
if (preg_match('/^(?:final\s+|abstract\s+)?class\s+(\w+)/m', $content, $classMatch)) {
|
||||
$className = $classMatch[1];
|
||||
}
|
||||
|
||||
if ($className === '' || $namespace === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$fqcn = $namespace . '\\' . $className;
|
||||
|
||||
if (!class_exists($fqcn)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$reflection = new \ReflectionClass($fqcn);
|
||||
if ($reflection->isAbstract() || !$reflection->isSubclassOf(Command::class)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->register($reflection->newInstance());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $argv Raw CLI arguments (including script name at [0])
|
||||
*/
|
||||
@@ -38,6 +95,18 @@ final class ConsoleApplication
|
||||
|
||||
[$args, $options] = self::parseArgv(array_slice($argv, 2));
|
||||
|
||||
// Per-command --help
|
||||
if ($options['help'] ?? false) {
|
||||
$command = $this->commands[$commandName];
|
||||
$usage = $command->usage();
|
||||
if ($usage !== '') {
|
||||
fwrite(STDOUT, $usage . "\n");
|
||||
} else {
|
||||
fwrite(STDOUT, sprintf("%s — %s\n", $command->name(), $command->description()));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
return $this->commands[$commandName]->execute($args, $options);
|
||||
}
|
||||
|
||||
|
||||
@@ -81,6 +81,65 @@ final class ConsoleApplicationTest extends TestCase
|
||||
self::assertSame([], $command->lastArgs);
|
||||
self::assertSame(['module' => 'addressbook'], $command->lastOptions);
|
||||
}
|
||||
|
||||
public function testHelpOptionShowsUsageAndReturnsZero(): void
|
||||
{
|
||||
$command = new CommandWithUsage();
|
||||
$app = new ConsoleApplication();
|
||||
$app->register($command);
|
||||
|
||||
$exitCode = $app->run(['bin/console', 'test:usage', '--help']);
|
||||
|
||||
self::assertSame(0, $exitCode);
|
||||
self::assertFalse($command->wasExecuted, 'Command should not execute when --help is passed');
|
||||
}
|
||||
|
||||
public function testHelpOnCommandWithoutUsageShowsNameAndDescription(): void
|
||||
{
|
||||
$command = new DummyCommand();
|
||||
$app = new ConsoleApplication();
|
||||
$app->register($command);
|
||||
|
||||
$exitCode = $app->run(['bin/console', 'test:dummy', '--help']);
|
||||
|
||||
self::assertSame(0, $exitCode);
|
||||
self::assertSame([], $command->lastArgs, 'Command should not execute when --help is passed');
|
||||
}
|
||||
|
||||
public function testAutoDiscoverFindsCommandsInDirectory(): void
|
||||
{
|
||||
$app = new ConsoleApplication();
|
||||
$commandsDir = dirname(__DIR__, 2) . '/lib/Console/Commands';
|
||||
$app->discoverCommands($commandsDir);
|
||||
|
||||
// Should find at least the 8 commands we have
|
||||
$exitCode = $app->run(['bin/console', 'module:sync', '--help']);
|
||||
self::assertSame(0, $exitCode);
|
||||
|
||||
$exitCode = $app->run(['bin/console', 'scheduler:run', '--help']);
|
||||
self::assertSame(0, $exitCode);
|
||||
|
||||
$exitCode = $app->run(['bin/console', 'doctor', '--help']);
|
||||
self::assertSame(0, $exitCode);
|
||||
}
|
||||
|
||||
public function testAutoDiscoverIgnoresNonexistentDirectory(): void
|
||||
{
|
||||
$app = new ConsoleApplication();
|
||||
$app->discoverCommands(sys_get_temp_dir() . '/nonexistent-console-' . uniqid());
|
||||
|
||||
// Should not throw, just have no commands
|
||||
$exitCode = $app->run(['bin/console', 'anything']);
|
||||
self::assertSame(1, $exitCode);
|
||||
}
|
||||
|
||||
public function testProjectRootResolvesCorrectly(): void
|
||||
{
|
||||
$command = new ProjectRootTestCommand();
|
||||
$expectedRoot = realpath(dirname(__DIR__, 2));
|
||||
|
||||
self::assertSame($expectedRoot, realpath($command->getProjectRoot()));
|
||||
}
|
||||
}
|
||||
|
||||
final class DummyCommand extends Command
|
||||
@@ -123,3 +182,52 @@ final class FailingCommand extends Command
|
||||
return 42;
|
||||
}
|
||||
}
|
||||
|
||||
final class CommandWithUsage extends Command
|
||||
{
|
||||
public bool $wasExecuted = false;
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'test:usage';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Has custom usage text';
|
||||
}
|
||||
|
||||
public function usage(): string
|
||||
{
|
||||
return "Usage: php bin/console test:usage <arg>\n\nA test command with usage.";
|
||||
}
|
||||
|
||||
public function execute(array $args, array $options): int
|
||||
{
|
||||
$this->wasExecuted = true;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
final class ProjectRootTestCommand extends Command
|
||||
{
|
||||
public function name(): string
|
||||
{
|
||||
return 'test:root';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Tests project root';
|
||||
}
|
||||
|
||||
public function getProjectRoot(): string
|
||||
{
|
||||
return $this->projectRoot();
|
||||
}
|
||||
|
||||
public function execute(array $args, array $options): int
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user