From a655a6f3ae60b12488217831bbf0ba71dd71b6dd Mon Sep 17 00:00:00 2001 From: Dario Garcia Date: Sun, 15 Nov 2026 13:31:14 -0300 Subject: [PATCH] feat(console): add bin/camelia-orm with seed and make commands 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. --- CHANGELOG.md | 14 ++ README.md | 48 +++++ bin/camelia-orm | 44 +++++ composer.json | 3 + src/Console/Application.php | 131 +++++++++++++ src/Console/Command.php | 37 ++++ src/Console/Command/DoctorCommand.php | 72 +++++++ src/Console/Command/MakeCommand.php | 120 ++++++++++++ src/Console/Command/MakeModelCommand.php | 116 ++++++++++++ src/Console/Command/MakeSeederCommand.php | 96 ++++++++++ src/Console/Command/SeedCommand.php | 110 +++++++++++ src/Console/Input.php | 152 +++++++++++++++ src/Console/Output.php | 85 +++++++++ tests/Unit/Console/ApplicationTest.php | 171 +++++++++++++++++ tests/Unit/Console/MakeCommandsTest.php | 218 ++++++++++++++++++++++ tests/Unit/Console/SeedCommandTest.php | 159 ++++++++++++++++ 16 files changed, 1576 insertions(+) create mode 100644 bin/camelia-orm create mode 100644 src/Console/Application.php create mode 100644 src/Console/Command.php create mode 100644 src/Console/Command/DoctorCommand.php create mode 100644 src/Console/Command/MakeCommand.php create mode 100644 src/Console/Command/MakeModelCommand.php create mode 100644 src/Console/Command/MakeSeederCommand.php create mode 100644 src/Console/Command/SeedCommand.php create mode 100644 src/Console/Input.php create mode 100644 src/Console/Output.php create mode 100644 tests/Unit/Console/ApplicationTest.php create mode 100644 tests/Unit/Console/MakeCommandsTest.php create mode 100644 tests/Unit/Console/SeedCommandTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 32471ef..9b9eeb8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 [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 ### Added diff --git a/README.md b/README.md index 4af62ed..931c749 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,54 @@ $orm->transaction(function (Orm $orm) { 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 Every read and write throws on failure. Silent degradation to `[]` is deliberately absent: it hides diff --git a/bin/camelia-orm b/bin/camelia-orm new file mode 100644 index 0000000..f2d9522 --- /dev/null +++ b/bin/camelia-orm @@ -0,0 +1,44 @@ +#!/usr/bin/env php + 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))); diff --git a/composer.json b/composer.json index d308561..587f029 100644 --- a/composer.json +++ b/composer.json @@ -34,6 +34,9 @@ "Camelia\\Orm\\Tests\\": "tests/" } }, + "bin": [ + "bin/camelia-orm" + ], "scripts": { "test": "phpunit --configuration phpunit.xml.dist", "test:integration": "phpunit --configuration phpunit.integration.xml.dist", diff --git a/src/Console/Application.php b/src/Console/Application.php new file mode 100644 index 0000000..26a0e8e --- /dev/null +++ b/src/Console/Application.php @@ -0,0 +1,131 @@ + */ + 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 + */ + public function commands(): array + { + return $this->commands; + } + + /** + * @param list $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 . ' [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; + } +} diff --git a/src/Console/Command.php b/src/Console/Command.php new file mode 100644 index 0000000..45a606e --- /dev/null +++ b/src/Console/Command.php @@ -0,0 +1,37 @@ + --help`. + */ + public function usage(): string; + + /** + * @param list $arguments everything after the command name + * @param array $options parsed --flags, keyed without the dashes + */ + public function execute(array $arguments, array $options, Output $output): int; +} diff --git a/src/Console/Command/DoctorCommand.php b/src/Console/Command/DoctorCommand.php new file mode 100644 index 0000000..4091000 --- /dev/null +++ b/src/Console/Command/DoctorCommand.php @@ -0,0 +1,72 @@ + $arguments + * @param array $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; + } +} diff --git a/src/Console/Command/MakeCommand.php b/src/Console/Command/MakeCommand.php new file mode 100644 index 0000000..99dc469 --- /dev/null +++ b/src/Console/Command/MakeCommand.php @@ -0,0 +1,120 @@ + $arguments + * @param array $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 $options + */ + abstract protected function template(string $name, array $options): string; + + /** + * @param array $options + */ + protected function namespaceOf(array $options): string + { + return $this->text($options['namespace'] ?? '') ?? $this->defaultNamespace(); + } + + /** + * @param array $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; + } +} diff --git a/src/Console/Command/MakeModelCommand.php b/src/Console/Command/MakeModelCommand.php new file mode 100644 index 0000000..128906b --- /dev/null +++ b/src/Console/Command/MakeModelCommand.php @@ -0,0 +1,116 @@ + --table= [--namespace=] [--dir=] [--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 $arguments + * @param array $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 --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 $options + */ + protected function template(string $name, array $options): string + { + $table = $this->text($options['table'] ?? '') ?? ''; + $namespace = $this->namespaceOf($options); + + return << camel_case_property. + } + + PHP; + } +} diff --git a/src/Console/Command/MakeSeederCommand.php b/src/Console/Command/MakeSeederCommand.php new file mode 100644 index 0000000..068eb15 --- /dev/null +++ b/src/Console/Command/MakeSeederCommand.php @@ -0,0 +1,96 @@ + [--namespace=] [--dir=] [--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 '; + } + + 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 $options + */ + protected function template(string $name, array $options): string + { + $namespace = $this->namespaceOf($options); + $key = strtolower(preg_replace('/Seeder$/', '', $name) ?? $name); + + return <<seedOnce(\$orm->repository(MyModel::class), ['code' => 'x'], ['label' => 'X']); + } + } + + PHP; + } +} diff --git a/src/Console/Command/SeedCommand.php b/src/Console/Command/SeedCommand.php new file mode 100644 index 0000000..991b399 --- /dev/null +++ b/src/Console/Command/SeedCommand.php @@ -0,0 +1,110 @@ + $arguments + * @param array $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; + } +} diff --git a/src/Console/Input.php b/src/Console/Input.php new file mode 100644 index 0000000..c58d989 --- /dev/null +++ b/src/Console/Input.php @@ -0,0 +1,152 @@ + */ + public array $arguments = [], + /** @var array */ + public array $options = [], + ) {} + + /** + * @param list $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 + */ + 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 !== '', + )); + } +} diff --git a/src/Console/Output.php b/src/Console/Output.php new file mode 100644 index 0000000..028d7e0 --- /dev/null +++ b/src/Console/Output.php @@ -0,0 +1,85 @@ +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; + } +} diff --git a/tests/Unit/Console/ApplicationTest.php b/tests/Unit/Console/ApplicationTest.php new file mode 100644 index 0000000..5231c6f --- /dev/null +++ b/tests/Unit/Console/ApplicationTest.php @@ -0,0 +1,171 @@ +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; + } + }; + } +} diff --git a/tests/Unit/Console/MakeCommandsTest.php b/tests/Unit/Console/MakeCommandsTest.php new file mode 100644 index 0000000..0326690 --- /dev/null +++ b/tests/Unit/Console/MakeCommandsTest.php @@ -0,0 +1,218 @@ +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=
', $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)); + } +} diff --git a/tests/Unit/Console/SeedCommandTest.php b/tests/Unit/Console/SeedCommandTest.php new file mode 100644 index 0000000..b44a457 --- /dev/null +++ b/tests/Unit/Console/SeedCommandTest.php @@ -0,0 +1,159 @@ +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 $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 $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); + } +}