feat(console): add bin/camelia-orm with seed and make commands
Tests / PHP 8.4 (push) Failing after 3m23s
Tests / PHP 8.4 (push) Failing after 3m23s
A command line for the library, kept deliberately small: no console component, no dependency added to the consumer's tree. - Application/Command/Input/Output: parsing, dispatch, exit codes and capturable output. Commands return an exit code instead of calling exit(), so every one is testable. - seed: runs the registered SeederRunner inside one transaction, with --list and --only=name[,name]. - doctor: one round-trip that fails loudly when the DSN is wrong. - make:model and make:seeder: live scaffolding into the consumer's code, sharing name validation, the overwrite guard and directory creation through MakeCommand. The binary ships an empty runner; an application composes SeedCommand into its own Application to register its seeders.
This commit is contained in:
1 parent
2acf2cc099
commit
a655a6f3ae
16 files changed
+1576
No files matched your search
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Console;
|
||||
|
||||
/**
|
||||
* Registers commands and dispatches one request to them.
|
||||
*
|
||||
* Deliberately small: `list`, `help`, then whatever the application registers. Live scaffolding
|
||||
* commands (make:model, make:seeder) live in the consumer, because only the consumer knows the
|
||||
* namespace and directory layout of its own code.
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
final class Application
|
||||
{
|
||||
public const SUCCESS = 0;
|
||||
|
||||
public const FAILURE = 1;
|
||||
|
||||
public const INVALID_USAGE = 2;
|
||||
|
||||
/** @var array<string, Command> */
|
||||
private array $commands = [];
|
||||
|
||||
public function __construct(
|
||||
private readonly string $name = 'camelia',
|
||||
private readonly string $version = '1.0.0',
|
||||
) {}
|
||||
|
||||
public function add(Command ...$commands): self
|
||||
{
|
||||
foreach ($commands as $command) {
|
||||
$this->commands[$command->name()] = $command;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, Command>
|
||||
*/
|
||||
public function commands(): array
|
||||
{
|
||||
return $this->commands;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $argv
|
||||
*/
|
||||
public function run(array $argv, Output $output): int
|
||||
{
|
||||
$input = Input::fromArgv($argv);
|
||||
|
||||
if ($input->hasOption('version')) {
|
||||
$output->writeln(sprintf('%s %s', $this->name, $this->version));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
if ($input->command === '' || $input->command === 'list') {
|
||||
$this->renderList($output);
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
if ($input->command === 'help') {
|
||||
return $this->renderHelp($input->argument(0), $output);
|
||||
}
|
||||
|
||||
$command = $this->commands[$input->command] ?? null;
|
||||
|
||||
if ($command === null) {
|
||||
$output->error(sprintf('Unknown command "%s".', $input->command));
|
||||
$output->muted('Run without arguments to see every command.');
|
||||
|
||||
return self::INVALID_USAGE;
|
||||
}
|
||||
|
||||
if ($input->hasOption('help')) {
|
||||
$output->writeln($command->usage());
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
return $command->execute($input->arguments, $input->options, $output);
|
||||
}
|
||||
|
||||
private function renderList(Output $output): void
|
||||
{
|
||||
$output->title(sprintf('%s %s', $this->name, $this->version));
|
||||
$output->writeln();
|
||||
$output->writeln('Usage: ' . $this->name . ' <command> [arguments] [--options]');
|
||||
$output->writeln();
|
||||
|
||||
$width = 0;
|
||||
|
||||
foreach (array_keys($this->commands) as $name) {
|
||||
$width = max($width, strlen($name));
|
||||
}
|
||||
|
||||
foreach ($this->commands as $name => $command) {
|
||||
$output->writeln(' ' . str_pad($name, $width + 2) . $command->description());
|
||||
}
|
||||
|
||||
$output->writeln();
|
||||
$output->muted(' list, help, --version');
|
||||
}
|
||||
|
||||
private function renderHelp(?string $name, Output $output): int
|
||||
{
|
||||
if ($name === null) {
|
||||
$this->renderList($output);
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$command = $this->commands[$name] ?? null;
|
||||
|
||||
if ($command === null) {
|
||||
$output->error(sprintf('Unknown command "%s".', $name));
|
||||
|
||||
return self::INVALID_USAGE;
|
||||
}
|
||||
|
||||
$output->writeln($command->usage());
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Console;
|
||||
|
||||
/**
|
||||
* One command of the CLI.
|
||||
*
|
||||
* The registry holds commands by name; parsing and dispatch live in Application. A command never
|
||||
* reads argv directly and never calls exit(): it returns an exit code.
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
interface Command
|
||||
{
|
||||
/**
|
||||
* The word you type: `seed`, `make:model`.
|
||||
*/
|
||||
public function name(): string;
|
||||
|
||||
/**
|
||||
* One line, shown in the command list.
|
||||
*/
|
||||
public function description(): string;
|
||||
|
||||
/**
|
||||
* Usage block printed by `<command> --help`.
|
||||
*/
|
||||
public function usage(): string;
|
||||
|
||||
/**
|
||||
* @param list<string> $arguments everything after the command name
|
||||
* @param array<string, string|true> $options parsed --flags, keyed without the dashes
|
||||
*/
|
||||
public function execute(array $arguments, array $options, Output $output): int;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Console\Command;
|
||||
|
||||
use Camelia\Orm\Console\Application;
|
||||
use Camelia\Orm\Console\Command;
|
||||
use Camelia\Orm\Console\Output;
|
||||
use Camelia\Orm\Orm;
|
||||
use Closure;
|
||||
|
||||
/**
|
||||
* Checks the connection and reports what the ORM sees.
|
||||
*
|
||||
* Useful as the first command after install: it fails loudly when the DSN is wrong, instead of
|
||||
* surfacing later as an empty result set.
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
final class DoctorCommand implements Command
|
||||
{
|
||||
/**
|
||||
* @param Closure(): Orm $orm
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly Closure $orm,
|
||||
) {}
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'doctor';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Checks the database connection and the ORM wiring.';
|
||||
}
|
||||
|
||||
public function usage(): string
|
||||
{
|
||||
return <<<'TXT'
|
||||
Usage: doctor
|
||||
|
||||
Runs one round-trip against the configured database and prints the driver and
|
||||
server version. Exits non-zero when the connection fails.
|
||||
TXT;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $arguments
|
||||
* @param array<string, string|true> $options
|
||||
*/
|
||||
public function execute(array $arguments, array $options, Output $output): int
|
||||
{
|
||||
try {
|
||||
$orm = ($this->orm)();
|
||||
$driver = $orm->connection()->driver();
|
||||
$version = $orm->connection()->scalar('SELECT VERSION()');
|
||||
} catch (\Throwable $exception) {
|
||||
$output->error('Connection failed: ' . $exception->getMessage());
|
||||
|
||||
return Application::FAILURE;
|
||||
}
|
||||
|
||||
$output->info('Connection OK');
|
||||
$output->writeln(' driver ' . $driver);
|
||||
$output->writeln(' server ' . (string) $version);
|
||||
|
||||
return Application::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Console\Command;
|
||||
|
||||
use Camelia\Orm\Console\Application;
|
||||
use Camelia\Orm\Console\Command;
|
||||
use Camelia\Orm\Console\Output;
|
||||
|
||||
/**
|
||||
* Live scaffolding shared by make:model and make:seeder: name validation, path resolution, the
|
||||
* overwrite guard and the directory creation. The concrete commands only supply the template.
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
abstract class MakeCommand implements Command
|
||||
{
|
||||
/**
|
||||
* @param list<string> $arguments
|
||||
* @param array<string, string|true> $options
|
||||
*/
|
||||
public function execute(array $arguments, array $options, Output $output): int
|
||||
{
|
||||
$name = $arguments[0] ?? null;
|
||||
|
||||
if ($name === null) {
|
||||
$output->error('Usage: ' . $this->signature());
|
||||
|
||||
return Application::INVALID_USAGE;
|
||||
}
|
||||
|
||||
if (preg_match('/^[A-Z][A-Za-z0-9]*$/', $name) !== 1) {
|
||||
$output->error(sprintf(
|
||||
'%s must be PascalCase, for example: %s',
|
||||
$this->kind(),
|
||||
$this->example(),
|
||||
));
|
||||
|
||||
return Application::INVALID_USAGE;
|
||||
}
|
||||
|
||||
$path = $this->directory($options) . DIRECTORY_SEPARATOR . $name . '.php';
|
||||
|
||||
if (is_file($path) && !isset($options['force'])) {
|
||||
$output->warn(sprintf('%s already exists. Use --force to overwrite.', $path));
|
||||
|
||||
return Application::FAILURE;
|
||||
}
|
||||
|
||||
$directory = dirname($path);
|
||||
|
||||
if (!is_dir($directory) && !mkdir($directory, 0o775, true) && !is_dir($directory)) {
|
||||
$output->error('Cannot create directory: ' . $directory);
|
||||
|
||||
return Application::FAILURE;
|
||||
}
|
||||
|
||||
file_put_contents($path, $this->template($name, $options));
|
||||
|
||||
$output->info('Created ' . $path);
|
||||
|
||||
return Application::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Short usage line shown when the name is missing.
|
||||
*/
|
||||
abstract protected function signature(): string;
|
||||
|
||||
/**
|
||||
* Noun used in the PascalCase error: "model", "seeder".
|
||||
*/
|
||||
abstract protected function kind(): string;
|
||||
|
||||
abstract protected function example(): string;
|
||||
|
||||
/**
|
||||
* Default namespace when --namespace is absent.
|
||||
*/
|
||||
abstract protected function defaultNamespace(): string;
|
||||
|
||||
/**
|
||||
* Default directory when --dir is absent.
|
||||
*/
|
||||
abstract protected function defaultDirectory(): string;
|
||||
|
||||
/**
|
||||
* @param array<string, string|true> $options
|
||||
*/
|
||||
abstract protected function template(string $name, array $options): string;
|
||||
|
||||
/**
|
||||
* @param array<string, string|true> $options
|
||||
*/
|
||||
protected function namespaceOf(array $options): string
|
||||
{
|
||||
return $this->text($options['namespace'] ?? '') ?? $this->defaultNamespace();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string|true> $options
|
||||
*/
|
||||
private function directory(array $options): string
|
||||
{
|
||||
return rtrim($this->text($options['dir'] ?? '') ?? $this->defaultDirectory(), '/\\');
|
||||
}
|
||||
|
||||
/**
|
||||
* An option value, or null when absent/empty. A bare flag counts as empty.
|
||||
*/
|
||||
protected function text(string|true $value): ?string
|
||||
{
|
||||
if ($value === true || $value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Console\Command;
|
||||
|
||||
use Camelia\Orm\Console\Application;
|
||||
use Camelia\Orm\Console\Output;
|
||||
|
||||
/**
|
||||
* Scaffolds a starter model into the consumer's code.
|
||||
*
|
||||
* Every field the template needs (table, namespace, directory) comes from options: the library
|
||||
* cannot infer which table a class maps to.
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
final class MakeModelCommand extends MakeCommand
|
||||
{
|
||||
public function name(): string
|
||||
{
|
||||
return 'make:model';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Scaffolds a model class.';
|
||||
}
|
||||
|
||||
public function usage(): string
|
||||
{
|
||||
return <<<'TXT'
|
||||
Usage: make:model <Name> --table=<table> [--namespace=<App\Models>] [--dir=<path>] [--force]
|
||||
|
||||
Generates a starter model with #[TableName], #[PrimaryKey] and #[AutoIncrement].
|
||||
|
||||
Options:
|
||||
--table=name table the model maps to (required)
|
||||
--namespace=App\Models namespace of the generated class
|
||||
--dir=src/Models directory to write into
|
||||
--force overwrite an existing file
|
||||
TXT;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $arguments
|
||||
* @param array<string, string|true> $options
|
||||
*/
|
||||
public function execute(array $arguments, array $options, Output $output): int
|
||||
{
|
||||
if ($this->text($options['table'] ?? '') === null) {
|
||||
$output->error('Usage: ' . $this->signature());
|
||||
|
||||
return Application::INVALID_USAGE;
|
||||
}
|
||||
|
||||
return parent::execute($arguments, $options, $output);
|
||||
}
|
||||
|
||||
protected function signature(): string
|
||||
{
|
||||
return 'make:model <Name> --table=<table>';
|
||||
}
|
||||
|
||||
protected function kind(): string
|
||||
{
|
||||
return 'The model name';
|
||||
}
|
||||
|
||||
protected function example(): string
|
||||
{
|
||||
return 'Invoice';
|
||||
}
|
||||
|
||||
protected function defaultNamespace(): string
|
||||
{
|
||||
return 'App\\Models';
|
||||
}
|
||||
|
||||
protected function defaultDirectory(): string
|
||||
{
|
||||
return 'src/Models';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string|true> $options
|
||||
*/
|
||||
protected function template(string $name, array $options): string
|
||||
{
|
||||
$table = $this->text($options['table'] ?? '') ?? '';
|
||||
$namespace = $this->namespaceOf($options);
|
||||
|
||||
return <<<PHP
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace {$namespace};
|
||||
|
||||
use Camelia\\Orm\\Attribute\\AutoIncrement;
|
||||
use Camelia\\Orm\\Attribute\\PrimaryKey;
|
||||
use Camelia\\Orm\\Attribute\\TableName;
|
||||
use Camelia\\Orm\\Model;
|
||||
|
||||
#[TableName('{$table}')]
|
||||
final class {$name} extends Model
|
||||
{
|
||||
#[PrimaryKey, AutoIncrement]
|
||||
public ?int \$id = null;
|
||||
|
||||
// Public typed properties become columns: camelCaseProperty -> camel_case_property.
|
||||
}
|
||||
|
||||
PHP;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Console\Command;
|
||||
|
||||
/**
|
||||
* Scaffolds a Seeder class into the consumer's code.
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
final class MakeSeederCommand extends MakeCommand
|
||||
{
|
||||
public function name(): string
|
||||
{
|
||||
return 'make:seeder';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Scaffolds a Seeder class.';
|
||||
}
|
||||
|
||||
public function usage(): string
|
||||
{
|
||||
return <<<'TXT'
|
||||
Usage: make:seeder <Name> [--namespace=<App\Seeders>] [--dir=<path>] [--force]
|
||||
|
||||
Generates a Seeder that extends AbstractSeeder and implements name() and run().
|
||||
|
||||
Options:
|
||||
--namespace=App\Seeders namespace of the generated class
|
||||
--dir=database/seeders directory to write into
|
||||
--force overwrite an existing file
|
||||
TXT;
|
||||
}
|
||||
|
||||
protected function signature(): string
|
||||
{
|
||||
return 'make:seeder <Name>';
|
||||
}
|
||||
|
||||
protected function kind(): string
|
||||
{
|
||||
return 'The seeder name';
|
||||
}
|
||||
|
||||
protected function example(): string
|
||||
{
|
||||
return 'RolesSeeder';
|
||||
}
|
||||
|
||||
protected function defaultNamespace(): string
|
||||
{
|
||||
return 'App\\Seeders';
|
||||
}
|
||||
|
||||
protected function defaultDirectory(): string
|
||||
{
|
||||
return 'database/seeders';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string|true> $options
|
||||
*/
|
||||
protected function template(string $name, array $options): string
|
||||
{
|
||||
$namespace = $this->namespaceOf($options);
|
||||
$key = strtolower(preg_replace('/Seeder$/', '', $name) ?? $name);
|
||||
|
||||
return <<<PHP
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace {$namespace};
|
||||
|
||||
use Camelia\\Orm\\Orm;
|
||||
use Camelia\\Orm\\Seeding\\AbstractSeeder;
|
||||
|
||||
final class {$name} extends AbstractSeeder
|
||||
{
|
||||
public function name(): string
|
||||
{
|
||||
return '{$key}';
|
||||
}
|
||||
|
||||
public function run(Orm \$orm): void
|
||||
{
|
||||
// \$this->seedOnce(\$orm->repository(MyModel::class), ['code' => 'x'], ['label' => 'X']);
|
||||
}
|
||||
}
|
||||
|
||||
PHP;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Console\Command;
|
||||
|
||||
use Camelia\Orm\Console\Application;
|
||||
use Camelia\Orm\Console\Command;
|
||||
use Camelia\Orm\Console\Output;
|
||||
use Camelia\Orm\Orm;
|
||||
use Camelia\Orm\Seeding\SeederRunner;
|
||||
use Closure;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Runs the registered seeders.
|
||||
*
|
||||
* The application passes a Closure that builds the Orm lazily, so `--help` does not need a
|
||||
* database connection.
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
final class SeedCommand implements Command
|
||||
{
|
||||
/**
|
||||
* @param Closure(): Orm $orm
|
||||
* @param Closure(Orm): SeederRunner $runner
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly Closure $orm,
|
||||
private readonly Closure $runner,
|
||||
) {}
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'seed';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Runs the registered seeders inside one transaction.';
|
||||
}
|
||||
|
||||
public function usage(): string
|
||||
{
|
||||
return <<<'TXT'
|
||||
Usage: seed [--only=name[,name]] [--list]
|
||||
|
||||
Fills reference and bootstrap data: permissions, roles, the first administrator.
|
||||
Every seeder is idempotent, so running the command twice is safe.
|
||||
|
||||
Options:
|
||||
--only=a,b run just these seeders, in the order given
|
||||
--list print the registered seeder names and exit
|
||||
TXT;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $arguments
|
||||
* @param array<string, string|true> $options
|
||||
*/
|
||||
public function execute(array $arguments, array $options, Output $output): int
|
||||
{
|
||||
$orm = ($this->orm)();
|
||||
$runner = ($this->runner)($orm);
|
||||
|
||||
if (isset($options['list'])) {
|
||||
foreach ($runner->names() as $name) {
|
||||
$output->writeln($name);
|
||||
}
|
||||
|
||||
return Application::SUCCESS;
|
||||
}
|
||||
|
||||
$only = array_values(array_filter(
|
||||
array_map('trim', explode(',', $this->text($options['only'] ?? ''))),
|
||||
static fn(string $part): bool => $part !== '',
|
||||
));
|
||||
|
||||
try {
|
||||
$results = $runner->run($only);
|
||||
} catch (Throwable $exception) {
|
||||
$output->error('Seeding failed, nothing was written: ' . $exception->getMessage());
|
||||
|
||||
return Application::FAILURE;
|
||||
}
|
||||
|
||||
if ($results === []) {
|
||||
$output->warn('No seeders registered.');
|
||||
|
||||
return Application::SUCCESS;
|
||||
}
|
||||
|
||||
foreach ($results as $result) {
|
||||
$result->isNoOp()
|
||||
? $output->muted(' ' . $result->summary())
|
||||
: $output->info(' ' . $result->summary());
|
||||
}
|
||||
|
||||
$output->writeln();
|
||||
$output->info('Done.');
|
||||
|
||||
return Application::SUCCESS;
|
||||
}
|
||||
|
||||
private function text(string|true $value): string
|
||||
{
|
||||
return $value === true ? '' : $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Console;
|
||||
|
||||
use SensitiveParameter;
|
||||
|
||||
/**
|
||||
* Parses the argument vector into a command name, positional arguments and --options.
|
||||
*
|
||||
* Hand-rolled on purpose: a library that ships a CLI should not drag a console component into every
|
||||
* consumer's dependency tree.
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
final readonly class Input
|
||||
{
|
||||
/**
|
||||
* The long-option sigil.
|
||||
*/
|
||||
private const SIGIL = '--';
|
||||
|
||||
public function __construct(
|
||||
public string $command,
|
||||
/** @var list<string> */
|
||||
public array $arguments = [],
|
||||
/** @var array<string, string|true> */
|
||||
public array $options = [],
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param list<string> $argv the raw vector, including the script name
|
||||
*/
|
||||
public static function fromArgv(#[SensitiveParameter] array $argv): self
|
||||
{
|
||||
array_shift($argv);
|
||||
|
||||
$command = '';
|
||||
$arguments = [];
|
||||
$options = [];
|
||||
$optionsOnly = false;
|
||||
|
||||
foreach ($argv as $token) {
|
||||
// Everything after `--` is a positional argument, even if it starts with a dash.
|
||||
if ($optionsOnly) {
|
||||
if ($command === '') {
|
||||
$command = $token;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$arguments[] = $token;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (self::isSeparator($token)) {
|
||||
$optionsOnly = true;
|
||||
|
||||
continue;
|
||||
}
|
||||
if (str_starts_with($token, self::SIGIL)) {
|
||||
[$name, $value] = self::splitOption(substr($token, 2));
|
||||
$options[$name] = $value;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($command === '') {
|
||||
$command = $token;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$arguments[] = $token;
|
||||
}
|
||||
|
||||
return new self($command, $arguments, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: string, 1: string|true}
|
||||
*/
|
||||
private static function splitOption(#[SensitiveParameter] string $token): array
|
||||
{
|
||||
$position = strpos($token, '=');
|
||||
|
||||
if ($position === false) {
|
||||
return [$token, true];
|
||||
}
|
||||
|
||||
return [substr($token, 0, $position), substr($token, $position + 1)];
|
||||
}
|
||||
|
||||
/**
|
||||
* `--` alone, the "everything after this is positional" marker.
|
||||
*/
|
||||
private static function isSeparator(#[SensitiveParameter] string $token): bool
|
||||
{
|
||||
if ($token === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$chars = str_split($token);
|
||||
|
||||
return count($chars) === 2 && implode('', $chars) === self::SIGIL;
|
||||
}
|
||||
|
||||
public function hasOption(string $name): bool
|
||||
{
|
||||
return isset($this->options[$name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* A flag without a value (`--force`) counts as present.
|
||||
*/
|
||||
public function option(string $name, ?string $default = null): ?string
|
||||
{
|
||||
$value = $this->options[$name] ?? null;
|
||||
|
||||
if ($value === null) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return $value === true ? '' : $value;
|
||||
}
|
||||
|
||||
public function argument(int $index, ?string $default = null): ?string
|
||||
{
|
||||
return $this->arguments[$index] ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a comma-separated option: `--only=roles,admin-user` → ['roles', 'admin-user'].
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function listOption(string $name): array
|
||||
{
|
||||
$raw = $this->option($name);
|
||||
|
||||
if ($raw === null || $raw === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(array_filter(
|
||||
array_map('trim', explode(',', $raw)),
|
||||
static fn(string $part): bool => $part !== '',
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Console;
|
||||
|
||||
/**
|
||||
* Everything a command is allowed to print.
|
||||
*
|
||||
* Commands never call echo: tests capture a stream-backed Output and assert on the text, and the
|
||||
* Application decides the colors.
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
final class Output
|
||||
{
|
||||
/**
|
||||
* @param \Closure(string): void $writer
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly \Closure $writer,
|
||||
private readonly bool $decorated = false,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param resource $stream
|
||||
*/
|
||||
public static function toStream(mixed $stream, bool $decorated = false): self
|
||||
{
|
||||
if (!is_resource($stream)) {
|
||||
throw new \InvalidArgumentException(
|
||||
'Output::toStream() expects an open stream resource.',
|
||||
);
|
||||
}
|
||||
|
||||
return new self(static function (string $line) use ($stream): void {
|
||||
fwrite($stream, $line);
|
||||
}, $decorated);
|
||||
}
|
||||
|
||||
public function writeln(string $line = ''): void
|
||||
{
|
||||
($this->writer)($line . PHP_EOL);
|
||||
}
|
||||
|
||||
public function write(string $text): void
|
||||
{
|
||||
($this->writer)($text);
|
||||
}
|
||||
|
||||
public function info(string $line): void
|
||||
{
|
||||
$this->writeln($this->paint($line, '32'));
|
||||
}
|
||||
|
||||
public function warn(string $line): void
|
||||
{
|
||||
$this->writeln($this->paint($line, '33'));
|
||||
}
|
||||
|
||||
public function error(string $line): void
|
||||
{
|
||||
$this->writeln($this->paint($line, '31'));
|
||||
}
|
||||
|
||||
public function muted(string $line): void
|
||||
{
|
||||
$this->writeln($this->paint($line, '90'));
|
||||
}
|
||||
|
||||
public function title(string $line): void
|
||||
{
|
||||
$this->writeln($this->paint($line, '1;36'));
|
||||
}
|
||||
|
||||
public function isDecorated(): bool
|
||||
{
|
||||
return $this->decorated;
|
||||
}
|
||||
|
||||
private function paint(string $text, string $code): string
|
||||
{
|
||||
return $this->decorated ? "\033[" . $code . 'm' . $text . "\033[0m" : $text;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user