Framework/src/commands/create_command.php

84 lines
2.7 KiB
PHP
Raw Normal View History

2025-12-14 23:10:01 +00:00
<?php
declare(strict_types=1);
use Phred\Console\Command;
use Symfony\Component\Console\Input\InputInterface as Input;
use Symfony\Component\Console\Output\OutputInterface as Output;
return new class extends Command {
protected string $command = 'create:command';
protected string $description = 'Scaffold a new user CLI command under console/commands.';
protected array $options = [
'name' => [
'mode' => 'argument',
'required' => true,
'description' => 'Command name (e.g., hello:world)',
],
'--force' => [
'mode' => 'flag',
'description' => 'Overwrite if the target file already exists.',
],
];
public function handle(Input $input, Output $output): int
{
$name = (string) ($input->getArgument('name') ?? '');
$force = (bool) $input->getOption('force');
$name = trim($name);
if ($name === '') {
$output->writeln('<error>Command name is required.</error>');
return 1;
}
// Derive PascalCase filename from name, splitting on non-alphanumeric boundaries and colons/underscores/dashes
$parts = preg_split('/[^a-zA-Z0-9]+/', $name) ?: [];
$classStem = '';
foreach ($parts as $p) {
if ($p === '') { continue; }
$classStem .= ucfirst(strtolower($p));
}
if ($classStem === '') {
$output->writeln('<error>Unable to derive a valid filename from the provided name.</error>');
return 1;
}
$root = getcwd();
$dir = $root . '/console/commands';
$file = $dir . '/' . $classStem . '.php';
if (!is_dir($dir)) {
@mkdir($dir, 0777, true);
}
if (file_exists($file) && !$force) {
$output->writeln('<error>Command already exists:</error> console/commands/' . basename($file));
$output->writeln('Use <comment>--force</comment> to overwrite.');
return 1;
}
$template = <<<'PHP'
<?php
use Phred\Console\Command;
use Symfony\Component\Console\Input\InputInterface as Input;
use Symfony\Component\Console\Output\OutputInterface as Output;
return new class extends Command {
protected string $command = '__COMMAND__';
protected string $description = 'Describe your command';
public function handle(Input $i, Output $o): int
{
$o->writeln('Command __COMMAND__ executed.');
return 0;
}
};
PHP;
$contents = str_replace('__COMMAND__', $name, $template);
@file_put_contents($file, rtrim($contents) . "\n");
$output->writeln('<info>created</info> console/commands/' . basename($file));
return 0;
}
};