diff --git a/bin/console b/bin/console index e9957ea..214b62a 100755 --- a/bin/console +++ b/bin/console @@ -9,35 +9,17 @@ declare(strict_types=1); * Usage: * php bin/console [arguments] [options] * php bin/console list + * php bin/console --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)); diff --git a/bin/module-assets-sync.php b/bin/module-assets-sync.php index 1df425c..250e0da 100644 --- a/bin/module-assets-sync.php +++ b/bin/module-assets-sync.php @@ -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()); } diff --git a/bin/module-build.php b/bin/module-build.php index e84011f..000e3e2 100644 --- a/bin/module-build.php +++ b/bin/module-build.php @@ -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()); } diff --git a/bin/module-deactivate.php b/bin/module-deactivate.php index 6a4c731..46f7254 100644 --- a/bin/module-deactivate.php +++ b/bin/module-deactivate.php @@ -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()); } diff --git a/bin/module-migrate.php b/bin/module-migrate.php index c487a12..a98e131 100644 --- a/bin/module-migrate.php +++ b/bin/module-migrate.php @@ -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()); } diff --git a/bin/module-permissions-sync.php b/bin/module-permissions-sync.php index 32dbf81..e6d48cc 100644 --- a/bin/module-permissions-sync.php +++ b/bin/module-permissions-sync.php @@ -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()); } diff --git a/bin/module-runtime-sync.php b/bin/module-runtime-sync.php index 076e853..a4fd709 100755 --- a/bin/module-runtime-sync.php +++ b/bin/module-runtime-sync.php @@ -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()); } diff --git a/bin/scheduler-run.php b/bin/scheduler-run.php index a6ffcf8..684b083 100755 --- a/bin/scheduler-run.php +++ b/bin/scheduler-run.php @@ -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 { diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 0a35ae4..8bb6611 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -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: diff --git a/docker-compose.yml b/docker-compose.yml index a2cfe89..cbf6e70 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -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: diff --git a/lib/Console/Command.php b/lib/Console/Command.php index 7394285..6155981 100644 --- a/lib/Console/Command.php +++ b/lib/Console/Command.php @@ -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 $args Positional arguments (after the command name) * @param array $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; + } } diff --git a/lib/Console/Commands/DoctorCommand.php b/lib/Console/Commands/DoctorCommand.php index 23fc611..d6e9aff 100644 --- a/lib/Console/Commands/DoctorCommand.php +++ b/lib/Console/Commands/DoctorCommand.php @@ -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); diff --git a/lib/Console/Commands/Module/AssetsSyncCommand.php b/lib/Console/Commands/Module/AssetsSyncCommand.php index d71a521..1eed9cf 100644 --- a/lib/Console/Commands/Module/AssetsSyncCommand.php +++ b/lib/Console/Commands/Module/AssetsSyncCommand.php @@ -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(); } diff --git a/lib/Console/Commands/Module/BuildCommand.php b/lib/Console/Commands/Module/BuildCommand.php index e93293a..763302e 100644 --- a/lib/Console/Commands/Module/BuildCommand.php +++ b/lib/Console/Commands/Module/BuildCommand.php @@ -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(); } diff --git a/lib/Console/Commands/Module/DeactivateCommand.php b/lib/Console/Commands/Module/DeactivateCommand.php index 5ee8579..e96f563 100644 --- a/lib/Console/Commands/Module/DeactivateCommand.php +++ b/lib/Console/Commands/Module/DeactivateCommand.php @@ -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 [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 --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(); } diff --git a/lib/Console/Commands/Module/MigrateCommand.php b/lib/Console/Commands/Module/MigrateCommand.php index 1db646b..2e817f1 100644 --- a/lib/Console/Commands/Module/MigrateCommand.php +++ b/lib/Console/Commands/Module/MigrateCommand.php @@ -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(); } diff --git a/lib/Console/Commands/Module/PermissionsSyncCommand.php b/lib/Console/Commands/Module/PermissionsSyncCommand.php index f98f37d..e9cbde0 100644 --- a/lib/Console/Commands/Module/PermissionsSyncCommand.php +++ b/lib/Console/Commands/Module/PermissionsSyncCommand.php @@ -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(); } diff --git a/lib/Console/Commands/Module/RuntimeSyncCommand.php b/lib/Console/Commands/Module/RuntimeSyncCommand.php index 0d8ea5b..1f78e6d 100644 --- a/lib/Console/Commands/Module/RuntimeSyncCommand.php +++ b/lib/Console/Commands/Module/RuntimeSyncCommand.php @@ -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(); } diff --git a/lib/Console/Commands/Scheduler/RunCommand.php b/lib/Console/Commands/Scheduler/RunCommand.php index ad3a913..c97b5e5 100644 --- a/lib/Console/Commands/Scheduler/RunCommand.php +++ b/lib/Console/Commands/Scheduler/RunCommand.php @@ -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)) { diff --git a/lib/Console/ConsoleApplication.php b/lib/Console/ConsoleApplication.php index de0349e..50b18ce 100644 --- a/lib/Console/ConsoleApplication.php +++ b/lib/Console/ConsoleApplication.php @@ -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 $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); } diff --git a/tests/Console/ConsoleApplicationTest.php b/tests/Console/ConsoleApplicationTest.php index 568dac2..d19e783 100644 --- a/tests/Console/ConsoleApplicationTest.php +++ b/tests/Console/ConsoleApplicationTest.php @@ -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 \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; + } +}