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:
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user