feat(console): add bin/camelia-orm with seed and make commands
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:
dgarcia committed 2026-11-15 13:31:14 -03:00
1 parent 2acf2cc099
commit a655a6f3ae
16 files changed
+1576

No files matched your search

+14
View File
@@ -4,6 +4,20 @@ All notable changes to this project are documented here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project adheres to [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project adheres to
[Semantic Versioning](https://semver.org/spec/v2.0.0.html). [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
- `Camelia\Orm\Seeding`: `Seeder` contract, `AbstractSeeder` with an idempotent `seedOnce()`, and
`SeederRunner`, which runs an ordered batch inside one transaction and reports per-seeder counts.
A failing seeder rolls the whole batch back.
- `Camelia\Orm\Console`: a small CLI core (`Application`, `Command`, `Input`, `Output`) with no
external dependency, plus `bin/camelia-orm` exposing `seed`, `doctor`, `make:model` and
`make:seeder`. Commands return exit codes instead of calling `exit()`, and every command can be
driven from a test through a stream-backed `Output`.
- `ConfigurationException::unknownSeeder()`.
- `docs/SEEDING.md`.
## [1.0.0] - 2026-11-15 ## [1.0.0] - 2026-11-15
### Added ### Added
+48
View File
@@ -110,6 +110,54 @@ $orm->transaction(function (Orm $orm) {
Nested calls use savepoints and the original exception is rethrown. Nested calls use savepoints and the original exception is rethrown.
## Seeders
A seeder fills reference or bootstrap data and must be safe to run twice. The runner executes the
batch inside one transaction, so a failure writes nothing.
```php
final class PermissionsSeeder extends AbstractSeeder
{
public function name(): string
{
return 'permissions';
}
public function run(Orm $orm): void
{
$repository = $orm->repository(PermissionModel::class);
foreach (Permission::cases() as $permission) {
$this->seedOnce($repository, ['code' => $permission->value], [
'module' => $permission->module(),
'action' => $permission->action(),
]);
}
}
}
$report = (new SeederRunner($orm))->addMany([new PermissionsSeeder()])->run();
```
Full guide in [`docs/SEEDING.md`](docs/SEEDING.md).
## Command line
`bin/camelia-orm` ships the commands that need no knowledge of your code; the scaffolding commands
write into the current directory, so run it from your project root.
```bash
vendor/bin/camelia-orm # list commands
vendor/bin/camelia-orm doctor # check the connection from CAMELIA_DB_*
vendor/bin/camelia-orm make:model Invoice --table=invoices --dir=src/Models
vendor/bin/camelia-orm make:seeder RolesSeeder --dir=database/seeders
vendor/bin/camelia-orm seed --list
vendor/bin/camelia-orm seed --only=permissions,roles
```
`seed` runs whatever `SeederRunner` is wired to the command; the binary ships an empty runner, so an
application registers its own seeders by composing `SeedCommand` into its own `Application`.
## Errors ## Errors
Every read and write throws on failure. Silent degradation to `[]` is deliberately absent: it hides Every read and write throws on failure. Silent degradation to `[]` is deliberately absent: it hides
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env php
<?php
declare(strict_types=1);
/**
* camelia/orm command line.
*
* Ships the commands that need no knowledge of the consumer's code (seed, doctor). Scaffolding
* commands write into the current working directory, so run this from the project root.
*/
use Camelia\Orm\Console\Application;
use Camelia\Orm\Console\Command\DoctorCommand;
use Camelia\Orm\Console\Command\MakeModelCommand;
use Camelia\Orm\Console\Command\MakeSeederCommand;
use Camelia\Orm\Console\Command\SeedCommand;
use Camelia\Orm\Console\Output;
use Camelia\Orm\Orm;
use Camelia\Orm\Seeding\SeederRunner;
$autoload = __DIR__ . '/../vendor/autoload.php';
if (!is_file($autoload)) {
fwrite(STDERR, "Run composer install first.\n");
exit(1);
}
require $autoload;
// The consumer's own autoloader is loaded when the binary is invoked from their project, so their
// seeders and models resolve. Composer already registers it by way of vendor/bin.
$ormFactory = static fn(): Orm => Orm::fromEnv();
$application = (new Application('camelia-orm', '1.0.0'))->add(
new SeedCommand($ormFactory, static fn(Orm $orm): SeederRunner => new SeederRunner($orm)),
new DoctorCommand($ormFactory),
new MakeModelCommand(),
new MakeSeederCommand(),
);
$decorated = stream_isatty(STDOUT) && getenv('NO_COLOR') === false;
exit($application->run($_SERVER['argv'] ?? [], Output::toStream(STDOUT, $decorated)));
+3
View File
@@ -34,6 +34,9 @@
"Camelia\\Orm\\Tests\\": "tests/" "Camelia\\Orm\\Tests\\": "tests/"
} }
}, },
"bin": [
"bin/camelia-orm"
],
"scripts": { "scripts": {
"test": "phpunit --configuration phpunit.xml.dist", "test": "phpunit --configuration phpunit.xml.dist",
"test:integration": "phpunit --configuration phpunit.integration.xml.dist", "test:integration": "phpunit --configuration phpunit.integration.xml.dist",
+131
View File
@@ -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;
}
}
+37
View File
@@ -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;
}
+72
View File
@@ -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;
}
}
+120
View File
@@ -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;
}
}
+116
View File
@@ -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;
}
}
+96
View File
@@ -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;
}
}
+110
View File
@@ -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;
}
}
+152
View File
@@ -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 !== '',
));
}
}
+85
View File
@@ -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;
}
}
+171
View File
@@ -0,0 +1,171 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit\Console;
use Camelia\Orm\Console\Application;
use Camelia\Orm\Console\Command;
use Camelia\Orm\Console\Input;
use Camelia\Orm\Console\Output;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class ApplicationTest extends TestCase
{
private string $printed = '';
private function console(): Output
{
return new Output(function (string $text): void {
$this->printed .= $text;
});
}
#[Test]
public function it_lists_registered_commands_with_their_description(): void
{
$application = new Application()->add($this->command('seed', 'Runs the seeders.'));
$exit = $application->run([], $this->console());
self::assertSame(Application::SUCCESS, $exit);
self::assertStringContainsString('seed', $this->printed);
self::assertStringContainsString('Runs the seeders.', $this->printed);
}
#[Test]
public function it_dispatches_to_the_named_command(): void
{
$application = new Application()->add($this->command('seed', 'desc'));
$exit = $application->run(['bin', 'seed'], $this->console());
self::assertSame(Application::SUCCESS, $exit);
self::assertStringContainsString('executed:seed', $this->printed);
}
#[Test]
public function it_passes_positional_arguments(): void
{
$application = new Application()->add($this->command('make:model', 'desc'));
$application->run(['bin', 'make:model', 'Invoice'], $this->console());
self::assertStringContainsString('args:Invoice', $this->printed);
}
#[Test]
public function it_passes_long_options_with_and_without_values(): void
{
$application = new Application()->add($this->command('seed', 'desc'));
$application->run(['bin', 'seed', '--only=roles', '--list'], $this->console());
self::assertStringContainsString('only=roles', $this->printed);
self::assertStringContainsString('list=1', $this->printed);
}
#[Test]
public function an_unknown_command_fails_with_a_non_zero_code(): void
{
$application = new Application()->add($this->command('seed', 'desc'));
$exit = $application->run(['bin', 'nope'], $this->console());
self::assertSame(Application::INVALID_USAGE, $exit);
self::assertStringContainsString('Unknown command "nope".', $this->printed);
}
#[Test]
public function help_prints_the_usage_of_one_command(): void
{
$application = new Application()->add($this->command('seed', 'desc'));
$application->run(['bin', 'help', 'seed'], $this->console());
self::assertStringContainsString('Usage: seed [--x]', $this->printed);
}
#[Test]
public function dash_dash_help_prints_the_usage_instead_of_running(): void
{
$application = new Application()->add($this->command('seed', 'desc'));
$application->run(['bin', 'seed', '--help'], $this->console());
self::assertStringContainsString('Usage: seed [--x]', $this->printed);
self::assertStringNotContainsString('executed:seed', $this->printed);
}
#[Test]
public function dash_dash_version_prints_the_version(): void
{
$application = new Application('camelia-orm', '9.9.9');
$application->run(['bin', '--version'], $this->console());
self::assertStringContainsString('camelia-orm 9.9.9', $this->printed);
}
#[Test]
public function input_splits_options_from_arguments(): void
{
$input = Input::fromArgv(['bin', 'seed', 'extra', '--only=a,b', '--list']);
self::assertSame('seed', $input->command);
self::assertSame(['extra'], $input->arguments);
self::assertSame('a,b', $input->option('only'));
self::assertTrue($input->hasOption('list'));
self::assertSame('', $input->option('list'));
}
#[Test]
public function input_splits_a_comma_separated_list_option(): void
{
$input = Input::fromArgv(['bin', 'seed', '--only=roles, admin-user ,']);
self::assertSame(['roles', 'admin-user'], $input->listOption('only'));
self::assertSame([], $input->listOption('missing'));
}
private function command(string $name, string $description): Command
{
return new class($name, $description) implements Command {
public function __construct(
private readonly string $label,
private readonly string $text,
) {}
public function name(): string
{
return $this->label;
}
public function description(): string
{
return $this->text;
}
public function usage(): string
{
return 'Usage: ' . $this->label . ' [--x]';
}
public function execute(array $arguments, array $options, Output $output): int
{
$output->writeln('executed:' . $this->label);
if ($arguments !== []) {
$output->writeln('args:' . implode(',', $arguments));
}
foreach ($options as $key => $value) {
$output->writeln($key . '=' . ($value === true ? '1' : $value));
}
return Application::SUCCESS;
}
};
}
}
+218
View File
@@ -0,0 +1,218 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit\Console;
use Camelia\Orm\Console\Application;
use Camelia\Orm\Console\Command\MakeModelCommand;
use Camelia\Orm\Console\Command\MakeSeederCommand;
use Camelia\Orm\Console\Output;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class MakeCommandsTest extends TestCase
{
private string $directory = '';
private string $printed = '';
protected function setUp(): void
{
$this->directory =
sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'camelia_' . bin2hex(random_bytes(6));
}
protected function tearDown(): void
{
if ($this->directory === '' || !is_dir($this->directory)) {
return;
}
$files = glob($this->directory . DIRECTORY_SEPARATOR . '*');
foreach ($files === false ? [] : $files as $file) {
if (is_file($file)) {
unlink($file);
}
}
rmdir($this->directory);
}
private function console(): Output
{
return new Output(function (string $text): void {
$this->printed .= $text;
});
}
#[Test]
public function make_model_writes_a_model_with_the_orm_attributes(): void
{
$exit = new MakeModelCommand()->execute(
['Invoice'],
['table' => 'invoices', 'dir' => $this->directory, 'namespace' => 'App\\Models'],
$this->console(),
);
self::assertSame(Application::SUCCESS, $exit);
$contents = (string) file_get_contents(
$this->directory . DIRECTORY_SEPARATOR . 'Invoice.php',
);
self::assertStringContainsString('namespace App\\Models;', $contents);
self::assertStringContainsString("#[TableName('invoices')]", $contents);
self::assertStringContainsString('final class Invoice extends Model', $contents);
self::assertStringContainsString('#[PrimaryKey, AutoIncrement]', $contents);
}
#[Test]
public function make_model_generates_valid_php(): void
{
new MakeModelCommand()->execute(
['Invoice'],
['table' => 'invoices', 'dir' => $this->directory],
$this->console(),
);
self::assertSame(
'No syntax errors detected in '
. str_replace(
['\\', '/'],
'/',
$this->directory . DIRECTORY_SEPARATOR . 'Invoice.php',
),
$this->lint('Invoice.php'),
);
}
#[Test]
public function make_model_requires_a_table(): void
{
$exit = new MakeModelCommand()->execute(['Invoice'], [], $this->console());
self::assertSame(Application::INVALID_USAGE, $exit);
self::assertStringContainsString('--table=<table>', $this->printed);
}
#[Test]
public function make_model_requires_a_pascal_case_name(): void
{
$exit = new MakeModelCommand()->execute(
['invoice'],
['table' => 'invoices', 'dir' => $this->directory],
$this->console(),
);
self::assertSame(Application::INVALID_USAGE, $exit);
self::assertStringContainsString('PascalCase', $this->printed);
}
#[Test]
public function make_model_refuses_to_overwrite_without_force(): void
{
new MakeModelCommand()->execute(
['Invoice'],
['table' => 'invoices', 'dir' => $this->directory],
$this->console(),
);
$exit = new MakeModelCommand()->execute(
['Invoice'],
['table' => 'other', 'dir' => $this->directory],
$this->console(),
);
self::assertSame(Application::FAILURE, $exit);
self::assertStringContainsString(
"#[TableName('invoices')]",
(string) file_get_contents($this->directory . DIRECTORY_SEPARATOR . 'Invoice.php'),
);
}
#[Test]
public function make_model_overwrites_when_forced(): void
{
new MakeModelCommand()->execute(
['Invoice'],
['table' => 'invoices', 'dir' => $this->directory],
$this->console(),
);
new MakeModelCommand()->execute(
['Invoice'],
['table' => 'other', 'dir' => $this->directory, 'force' => true],
$this->console(),
);
self::assertStringContainsString(
"#[TableName('other')]",
(string) file_get_contents($this->directory . DIRECTORY_SEPARATOR . 'Invoice.php'),
);
}
#[Test]
public function make_seeder_writes_a_seeder_extending_abstract_seeder(): void
{
$exit = new MakeSeederCommand()->execute(
['RolesSeeder'],
['dir' => $this->directory, 'namespace' => 'App\\Seeders'],
$this->console(),
);
self::assertSame(Application::SUCCESS, $exit);
$contents = (string) file_get_contents(
$this->directory . DIRECTORY_SEPARATOR . 'RolesSeeder.php',
);
self::assertStringContainsString('namespace App\\Seeders;', $contents);
self::assertStringContainsString(
'final class RolesSeeder extends AbstractSeeder',
$contents,
);
self::assertStringContainsString("return 'roles';", $contents);
self::assertStringContainsString('public function run(Orm $orm): void', $contents);
}
#[Test]
public function make_seeder_generates_valid_php(): void
{
new MakeSeederCommand()->execute(
['RolesSeeder'],
['dir' => $this->directory],
$this->console(),
);
self::assertSame(
'No syntax errors detected in '
. str_replace(
['\\', '/'],
'/',
$this->directory . DIRECTORY_SEPARATOR . 'RolesSeeder.php',
),
$this->lint('RolesSeeder.php'),
);
}
/**
* `php -l` prints its verdict on the first line; the path separator differs per platform.
*/
private function lint(string $file): string
{
$output = [];
exec(
escapeshellarg(PHP_BINARY)
. ' -l '
. escapeshellarg($this->directory . DIRECTORY_SEPARATOR . $file)
. ' 2>&1',
$output,
);
$first = $output[0] ?? '';
return trim(str_replace(['\\', '/'], '/', $first));
}
}
+159
View File
@@ -0,0 +1,159 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit\Console;
use Camelia\Orm\Console\Application;
use Camelia\Orm\Console\Command\SeedCommand;
use Camelia\Orm\Console\Output;
use Camelia\Orm\Orm;
use Camelia\Orm\Seeding\AbstractSeeder;
use Camelia\Orm\Seeding\SeederRunner;
use Camelia\Orm\Tests\Support\FakeConnection;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class SeedCommandTest extends TestCase
{
private string $printed = '';
private function console(): Output
{
return new Output(function (string $text): void {
$this->printed .= $text;
});
}
private function orm(): Orm
{
return Orm::fromConnection(new FakeConnection());
}
private function command(): SeedCommand
{
return new SeedCommand(
$this->orm(...),
static fn(Orm $orm): SeederRunner => new SeederRunner($orm),
);
}
#[Test]
public function list_prints_registered_seeder_names(): void
{
$command = new SeedCommand(
$this->orm(...),
static fn(Orm $orm): SeederRunner => new SeederRunner($orm)->addMany([
new class extends AbstractSeeder {
public function name(): string
{
return 'permissions';
}
public function run(Orm $orm): void {}
},
new class extends AbstractSeeder {
public function name(): string
{
return 'roles';
}
public function run(Orm $orm): void {}
},
]),
);
$exit = $command->execute([], ['list' => true], $this->console());
self::assertSame(Application::SUCCESS, $exit);
self::assertStringContainsString('permissions', $this->printed);
self::assertStringContainsString('roles', $this->printed);
}
#[Test]
public function it_reports_no_seeders_registered(): void
{
$exit = $this->command()->execute([], [], $this->console());
self::assertSame(Application::SUCCESS, $exit);
self::assertStringContainsString('No seeders registered.', $this->printed);
}
#[Test]
public function it_runs_only_the_seeders_named_in_only(): void
{
$ran = new \ArrayObject();
$command = new SeedCommand($this->orm(...), static function (Orm $orm) use (
$ran,
): SeederRunner {
$a = new class($ran) extends AbstractSeeder {
/** @param \ArrayObject<int, string> $ran */
public function __construct(
private readonly \ArrayObject $ran,
) {}
public function name(): string
{
return 'permissions';
}
public function run(Orm $orm): void
{
$this->ran->append('permissions');
}
};
$b = new class($ran) extends AbstractSeeder {
/** @param \ArrayObject<int, string> $ran */
public function __construct(
private readonly \ArrayObject $ran,
) {}
public function name(): string
{
return 'roles';
}
public function run(Orm $orm): void
{
$this->ran->append('roles');
}
};
return new SeederRunner($orm)->addMany([$a, $b]);
});
$exit = $command->execute([], ['only' => 'roles'], $this->console());
self::assertSame(Application::SUCCESS, $exit);
self::assertSame(['roles'], $ran->getArrayCopy());
self::assertStringContainsString('roles: 0 inserted, 0 skipped', $this->printed);
}
#[Test]
public function it_reports_a_seeder_failure_without_a_stack_trace(): void
{
$command = new SeedCommand(
$this->orm(...),
static fn(Orm $orm): SeederRunner => new SeederRunner($orm)->add(new class extends
AbstractSeeder {
public function name(): string
{
return 'boom';
}
public function run(Orm $orm): void
{
throw new \RuntimeException('table missing');
}
}),
);
$exit = $command->execute([], [], $this->console());
self::assertSame(Application::FAILURE, $exit);
self::assertStringContainsString('Seeding failed, nothing was written', $this->printed);
self::assertStringContainsString('table missing', $this->printed);
}
}