Compare commits

..
15 Commits
Author SHA1 Message Date
dgarcia 318b5b9da2 fix(criteria): compare backed enums by their scalar value
Using an enum as a criteria value reached PDO as an object and failed with
"Object of class X could not be converted to string". Filtering by a state
column - the most natural thing to do with an enum-mapped property - was
impossible.

CriteriaCompiler now unwraps \BackedEnum both for a plain value and inside an
an IN list.

Covered by CriteriaCompilerEnumTest.
2026-11-15 14:37:54 -03:00
dgarcia 316cbdc2cd build: remove Gitea Actions workflows 2026-11-15 14:24:01 -03:00
dgarcia 1478b8f7f7 fix(typecaster): send booleans to the driver as 1/0
Tests / PHP 8.4 (push) Failing after 5m57s
PDO with ATTR_EMULATE_PREPARES = false sends a native PHP bool as an empty
string. MariaDB rejects it on a TINYINT column with "Incorrect integer
value: ''", so every boolean column was unwritable through the ORM:
inserting a model with a bool property always failed.

toDatabaseValue() now maps bool to 1/0. Other scalars, enums, dates and
BigDecimal keep their existing handling.

Covered by TypeCasterDatabaseValueTest.
2026-11-15 14:21:40 -03:00
dgarcia 227325e4b4 fix(repository): persist guarded columns passed to create()
Tests / PHP 8.4 (push) Failing after 5m9s
create() built the model through hydrate(), which skips #[Guarded]
properties on purpose: that is the right behaviour for an HTTP payload,
where a client must not set password_hash or a token. But create() is
called from trusted server code - a service, a seeder - and the guarded
value was silently dropped, so an account was inserted with an empty
password hash. The write succeeded and nothing failed loudly.

create() now re-applies guarded values after hydration, so every column
the caller passes is persisted. hydrate() keeps rejecting them, which is
what protects mass assignment.

Covered by CreateWithGuardedTest: one case for create() persisting the
hash, one asserting hydrate() still ignores it.
2026-11-15 13:37:39 -03:00
dgarcia 4faad2c46e fix(repository): hydrate enum columns instead of failing on read
Tests / PHP 8.4 (push) Failing after 4m31s
Repository::castDatabaseValue() called TypeCaster::cast() with the enum's
class name as the "type", so any row of a model declaring #[Enum] threw
"Cannot assign string to property X of type Y" the moment it was read.
Writes worked, which is why this survived 1.0.0: the select path is only
exercised on read.

castDatabaseValue() now delegates to TypeCaster::castEnum() when the
property declares one, and keeps the null passthrough. Covered by
EnumHydrationTest with a scalar value and a null.
2026-11-15 13:35:27 -03:00
dgarcia a655a6f3ae 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.
2026-11-15 13:31:14 -03:00
dgarcia 2acf2cc099 feat(seeding): add the seeder concept with an idempotent runner
A seeder fills reference or bootstrap data - the permission catalogue, the
built-in roles, the first administrator. It is not a migration: it never
touches the schema, it runs on demand, and it must be safe to run twice.

- Seeder: the contract (name + run).
- AbstractSeeder: seedOnce() inserts only when the criteria match nothing and
  records inserted/skipped counts. It never overwrites a row a user edited.
- SeederRunner: runs an ordered batch inside one transaction, so a failing
  seeder leaves the database untouched. Supports running a named subset.
- SeederResult: per-seeder outcome for reporting.
- ConfigurationException::unknownSeeder() lists the registered names.

docs/SEEDING.md documents the contract and how to write one.
2026-11-15 13:30:54 -03:00
dgarcia 02703f40ab build: replace .githooks with husky
Tests / PHP 8.4 (push) Failing after 5m32s
2026-11-15 11:14:26 -03:00
dgarcia 46d3ba10f0 refactor: shrink pre-commit hook to the gate itself
Tests / PHP 8.4 (push) Failing after 6m20s
2026-11-15 11:11:44 -03:00
dgarcia 574b034d4c docs: explain how to enable the pre-commit hook
Tests / PHP 8.4 (push) Failing after 5m37s
2026-11-15 11:08:22 -03:00
dgarcia cbbc349df0 chore: run composer check on pre-commit 2026-11-15 11:07:39 -03:00
dgarcia 53130d7b4a ci: install node for actions/checkout in the php container
Tests / PHP 8.4 (push) Failing after 6m3s
2026-11-15 11:00:58 -03:00
dgarcia 0e756e45c7 refactor!: require PHP 8.4
Tests / PHP 8.4 (push) Failing after 5m34s
Drop support for PHP 8.3 and lower. The package now declares >=8.4, and CI runs
only on 8.4.

- composer.json: require php >=8.4.
- mago.toml: php-version = "8.4", matching the minimum supported version.
- phpstan.neon: phpVersion 80400.
- Upgrade phpstan/phpstan to ^2.3: 1.x cannot parse `new Foo()->bar()`, which the
  8.4 formatter now emits.
- Fix the type errors PHPStan 2 reports: class-string<static> variance,
  optional array offsets in fromEnvironment, list vs array for PdoConnection::$lru,
  ReflectionClass<Model> docblocks, Repository made covariant in T, and a redundant
  null comparison in validateRelationPath.
- CI: single PHP 8.4 job using the php:8.4-cli container instead of setup-php,
  which failed with a TLS handshake timeout on the runner.

BREAKING CHANGE: PHP 8.4 is now required.
2026-11-15 10:58:11 -03:00
dgarcia c15015d809 ci: use php container image instead of setup-php action
Tests / PHP 8.3 (push) Failing after 10m43s
Tests / PHP 8.4 (push) Failing after 11m18s
2026-11-15 10:38:44 -03:00
dgarcia 8040506736 chore: make export-ignore recursive and cover dev files
Tests / PHP 8.3 (push) Failing after 15s
Tests / PHP 8.4 (push) Failing after 10s
2026-11-15 10:24:50 -03:00
54 changed files with 2543 additions and 128 deletions

No files matched your search

+7 -2
View File
@@ -1,10 +1,10 @@
* text=auto eol=lf
# Files excluded from the distribution archive installed by Composer.
/tests export-ignore
# export-ignore is not recursive: a directory entry does not cover its children.
/tests/** export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
/.github export-ignore
/AGENTS.md export-ignore
/especificaciones-orm.md export-ignore
/mago.toml export-ignore
@@ -12,3 +12,8 @@
/phpstan.neon export-ignore
/phpunit.xml.dist export-ignore
/phpunit.integration.xml.dist export-ignore
/phpunit.coverage.xml.dist export-ignore
/node_modules/ export-ignore
/package.json export-ignore
/package-lock.json export-ignore
/.husky/** export-ignore
-34
View File
@@ -1,34 +0,0 @@
name: Tests
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
check:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
php: ['8.3', '8.4']
name: PHP ${{ matrix.php }}
steps:
- uses: actions/checkout@v4
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring, pdo, pdo_mysql, json
coverage: none
tools: composer:v2
- name: Install dependencies
run: composer update --prefer-dist --no-interaction --no-progress
- name: Run gate
run: composer check
+1
View File
@@ -4,3 +4,4 @@
.phpunit.result.cache
.mago.cache
coverage/
node_modules/
+1
View File
@@ -0,0 +1 @@
composer check
+6 -4
View File
@@ -26,8 +26,8 @@ Si tu memoria sugiere alguno de esos nombres, está obsoleta.
## Entorno local
- PHP: `C:\php8.4\php.exe` (8.4.19). La librería declara `>=8.2`, así que **no** uses sintaxis de
8.3/8.4 (y por eso `(new Foo())->bar()` conserva los paréntesis).
- PHP: `C:\php8.4\php.exe` (8.4.19). La librería declara `>=8.4`, así que toda la sintaxis de 8.4
está disponible y el formatter puede emitir `new Foo()->bar()`.
- `declare(strict_types=1)` en todo archivo.
- Sin `.env` ni base configurada. Los tests unitarios usan `FakeConnection`; la integración
requiere `CAMELIA_TEST_DSN` y se **salta** si falta.
@@ -44,8 +44,10 @@ Nunca mergees con uno en rojo. Orden obligatorio.
`mago.toml` configura formatter, linter y analyzer. Notas que ahorran tiempo:
- **`php-version = "8.2"` en `mago.toml` es obligatorio.** Si se sube a 8.4, `mago fmt` reescribe
`(new X())->m()` como `new X()->m()`, que rompe el soporte declarado de 8.2.
- **`php-version = "8.4"` en `mago.toml` debe coincidir con el mínimo declarado.** El paquete
promete `>=8.4`, así que `mago fmt` puede emitir `new X()->m()`. Si el soporte mínimo bajara,
`php-version` tendría que bajar con él: con 8.4 el formatter elimina los paréntesis de
`(new X())->m()`, sintaxis que no parsea en 8.3 ni inferiores.
- `mago analyze` excluye `tests/`: no carga el autoloader de Composer, así que reportaría
`PHPUnit\Framework\TestCase` como clase inexistente. PHPStan sí cubre los tests.
- `mago-baseline.toml` acepta los hallazgos de `mixed` inherentes a valores que vienen de PDO.
+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
[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
+60 -5
View File
@@ -3,12 +3,11 @@
[![Latest Stable Version](https://img.shields.io/packagist/v/camelia/orm.svg)](https://packagist.org/packages/camelia/orm)
[![Total Downloads](https://img.shields.io/packagist/dt/camelia/orm.svg)](https://packagist.org/packages/camelia/orm)
[![License](https://img.shields.io/packagist/l/camelia/orm.svg)](https://packagist.org/packages/camelia/orm)
[![Tests](https://git.dr2gsistemas.duckdns.org/dr2gsistemas/camelia-orm/actions/workflows/tests.yml/badge.svg)](https://git.dr2gsistemas.duckdns.org/dr2gsistemas/camelia-orm/actions)
Lightweight attribute-mapped Active Record ORM for MariaDB/MySQL over PDO.
- **Package:** `camelia/orm` · **Namespace:** `Camelia\Orm`
- **PHP** `>=8.3`, extensions `pdo_mysql` and `mbstring`
- **PHP** `>=8.4`, extensions `pdo_mysql` and `mbstring`
- **Runtime dependencies:** `psr/log` (PSR-3, optional usage). `brick/math` is a suggestion for
`BigDecimal` properties.
@@ -110,6 +109,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
@@ -134,18 +181,26 @@ composer check # runs the five gates above, in order
composer test:integration # requires CAMELIA_TEST_DSN
```
The same gate runs on every commit once the hook is enabled per clone:
```bash
git config core.hooksPath .githooks
```
Use `git commit --no-verify` to bypass it for a single commit.
Configuration:
| File | Purpose |
|---|---|
| `mago.toml` | formatter, linter, analyzer |
| `mago-baseline.toml` | accepted analyzer findings (values coming from PDO) |
| `phpstan.neon` | level 8, `phpVersion: 80300` |
| `phpstan.neon` | level 8, `phpVersion: 80400` |
| `phpunit.xml.dist` | unit suite |
| `phpunit.integration.xml.dist` | integration suite, skipped without `CAMELIA_TEST_DSN` |
`mago.toml` pins `php-version = "8.3"`. Do not raise it to 8.4: with 8.4 the formatter emits
`new Foo()->bar()`, which the package cannot ship because it promises PHP 8.3 support.
`mago.toml` pins `php-version = "8.4"`, matching the minimum supported version, so `mago fmt` and
the runtime agree on which syntax the package may ship.
## License
+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)));
+5 -2
View File
@@ -11,14 +11,14 @@
}
],
"require": {
"php": ">=8.3",
"php": ">=8.4",
"ext-mbstring": "*",
"ext-pdo": "*",
"psr/log": "^3.0"
},
"require-dev": {
"carthage-software/mago": "^1.60",
"phpstan/phpstan": "^1.11",
"phpstan/phpstan": "2.3",
"phpunit/phpunit": "^10.5 || ^11.0"
},
"suggest": {
@@ -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",
Generated
+18 -7
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "995f47882c4069e4904f4637e3219078",
"content-hash": "d7369cefc9ff778b213f99238b1f8f2d",
"packages": [
{
"name": "psr/log",
@@ -359,15 +359,15 @@
},
{
"name": "phpstan/phpstan",
"version": "1.12.34",
"version": "2.3.0",
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/4dd89ca7aa30fdc6760be21550d583bcc32e8476",
"reference": "4dd89ca7aa30fdc6760be21550d583bcc32e8476",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/b1f9890d9af53a25c58129e78f0aadd31f90d7f4",
"reference": "b1f9890d9af53a25c58129e78f0aadd31f90d7f4",
"shasum": ""
},
"require": {
"php": "^7.2|^8.0"
"php": "^7.4|^8.0"
},
"conflict": {
"phpstan/phpstan-shim": "*"
@@ -386,6 +386,17 @@
"license": [
"MIT"
],
"authors": [
{
"name": "Ondřej Mirtes"
},
{
"name": "Markus Staab"
},
{
"name": "Vincent Langlet"
}
],
"description": "PHPStan - PHP Static Analysis Tool",
"keywords": [
"dev",
@@ -408,7 +419,7 @@
"type": "github"
}
],
"time": "2026-07-28T10:04:39+00:00"
"time": "2026-10-06T06:15:36+00:00"
},
{
"name": "phpunit/php-code-coverage",
@@ -2018,7 +2029,7 @@
"prefer-stable": true,
"prefer-lowest": false,
"platform": {
"php": ">=8.3",
"php": ">=8.4",
"ext-mbstring": "*",
"ext-pdo": "*"
},
+68
View File
@@ -0,0 +1,68 @@
# Seeder
A `Seeder` populates a table with reference or bootstrap rows: the permission catalogue, the
built-in roles, the first administrator. It is not a migration: it runs on demand, it is
idempotent, and it never changes the schema.
## Contract
```php
interface Seeder
{
public function name(): string;
public function run(Orm $orm): void;
}
```
- `name()` is what you type on the command line and what the runner orders by. Keep it short and
unique: `permissions`, `roles`, `admin-user`.
- `run()` receives the `Orm`, so a seeder writes through repositories like any other consumer. It
must be safe to run twice: an insert of an existing row is a no-op, not an error.
- A seeder throws nothing it cannot explain. A failure stops the batch and is reported.
## Runner
`Camelia\Orm\Seeding\SeederRunner` executes an ordered list of seeders inside one transaction:
```php
$runner = new SeederRunner($orm, [new PermissionsSeeder(), new RolesSeeder(), new AdminSeeder()]);
$report = $runner->run();
```
Every seeder runs in the same transaction: either the whole batch applies or none of it does. The
report tells you what happened per seeder.
## Writing a seeder
Subclass `AbstractSeeder` to get idempotent helpers instead of hand-rolling `findOrCreate` calls:
```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(),
]);
}
}
}
```
`seedOnce()` inserts when the criteria match nothing and reports whether it did. It never updates an
existing row, because a seeder that silently overwrites data the user edited is a footgun.
## Ordering
Seeders run in the order you pass them. When a seeder depends on rows another one creates (roles
need permissions), pass them in dependency order and let the transaction protect you.
+2 -3
View File
@@ -1,9 +1,8 @@
# Mago toolchain configuration — camelia/orm
# Docs: https://mago.carthage.software
# The library promises PHP >= 8.3. Pinning the parser to 8.3 keeps the formatter from emitting
# syntax the package cannot ship (for example `new Foo()->bar()`, which needs 8.4).
php-version = "8.3"
# The library promises PHP >= 8.4.
php-version = "8.4"
[source]
paths = ["src", "tests"]
+29
View File
@@ -0,0 +1,29 @@
{
"name": "camelia-orm-dev",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "camelia-orm-dev",
"devDependencies": {
"husky": "^9.1.7"
}
},
"node_modules/husky": {
"version": "9.1.7",
"resolved": "https://registry.npmjs.org/husky/-/husky-9.1.7.tgz",
"integrity": "sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA==",
"dev": true,
"license": "MIT",
"bin": {
"husky": "bin.js"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/typicode"
}
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"name": "camelia-orm-dev",
"private": true,
"description": "Development-only tooling. Not published; the package is installed through Composer.",
"scripts": {
"prepare": "husky || true"
},
"devDependencies": {
"husky": "^9.1.7"
}
}
+2 -3
View File
@@ -1,8 +1,7 @@
parameters:
level: 8
# The library promises PHP >= 8.3, so analysis targets the oldest supported version.
# This is why `(new Foo())->bar()` keeps its parentheses: `new Foo()->bar()` only parses on 8.4+.
phpVersion: 80300
# The library promises PHP >= 8.4, so analysis targets the only supported version.
phpVersion: 80400
paths:
- src
- tests
+1
View File
@@ -68,6 +68,7 @@ final class ConnectionFactory
public static function fromEnvironment(): Connection
{
/** @var array<string, string> $values */
$values = [];
$missing = [];
+1 -1
View File
@@ -23,7 +23,7 @@ final class PdoConnection implements Connection
/** @var array<string, PDOStatement> */
private array $statements = [];
/** @var list<string> LRU order, most recent last */
/** @var array<int, string> LRU order, most recent last; reindexed after eviction */
private array $lru = [];
/** @var list<string> savepoint names for nested transactions */
+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;
}
}
+13
View File
@@ -38,4 +38,17 @@ final class ConfigurationException extends OrmException
$max,
));
}
/**
* @param list<string> $unknown
* @param list<string> $known
*/
public static function unknownSeeder(array $unknown, array $known): self
{
return new self(sprintf(
'Unknown seeder(s): %s. Registered: %s.',
implode(', ', $unknown),
$known === [] ? '(none)' : implode(', ', $known),
));
}
}
+3 -3
View File
@@ -113,7 +113,7 @@ final class MetadataFactory
/**
* @param class-string<\Camelia\Orm\Model> $class
* @param ReflectionClass<object> $reflection
* @param ReflectionClass<\Camelia\Orm\Model> $reflection
*/
private function buildProperty(
string $class,
@@ -169,7 +169,7 @@ final class MetadataFactory
/**
* @param class-string<\Camelia\Orm\Model> $class
* @param ReflectionClass<object> $reflection
* @param ReflectionClass<\Camelia\Orm\Model> $reflection
*/
private function buildRelation(
string $class,
@@ -238,7 +238,7 @@ final class MetadataFactory
/**
* @param class-string<\Camelia\Orm\Model> $class
* @param ReflectionClass<object> $reflection
* @param ReflectionClass<\Camelia\Orm\Model> $reflection
* @return class-string<\Camelia\Orm\Model>
*/
private function resolveRelatedClass(
+3 -9
View File
@@ -56,10 +56,7 @@ abstract class Model
public static function metadata(): ClassMetadata
{
/** @var class-string<\Camelia\Orm\Model> $class */
$class = static::class;
return self::metadataFor($class);
return self::metadataFor(static::class);
}
/**
@@ -193,7 +190,7 @@ abstract class Model
*/
public function validate(): array
{
return (new Validator())->validate($this);
return new Validator()->validate($this);
}
public function isValid(): bool
@@ -286,10 +283,7 @@ abstract class Model
$errors = $this->validate();
if ($errors !== []) {
/** @var class-string<\Camelia\Orm\Model> $class */
$class = static::class;
throw new ValidationException($errors, $class);
throw new ValidationException($errors, static::class);
}
}
+6 -3
View File
@@ -82,14 +82,17 @@ final class Orm
*/
public function repository(string $class): Repository
{
/** @var Repository<T> $repository */
$repository =
$this->repositories[$class] ??= new Repository(
if (!isset($this->repositories[$class])) {
$this->repositories[$class] = new Repository(
$this->connection,
$class,
$this->dialect,
$this->persister(),
);
}
/** @var Repository<T> $repository */
$repository = $this->repositories[$class];
return $repository;
}
+1 -4
View File
@@ -303,10 +303,7 @@ final class Persister
private function assertNotPartial(Model $model, string $operation): void
{
if ($model->isPartial()) {
/** @var class-string<\Camelia\Orm\Model> $class */
$class = $model::class;
throw PartialModelException::onWrite($class, $operation);
throw PartialModelException::onWrite($model::class, $operation);
}
}
}
+10 -1
View File
@@ -74,12 +74,21 @@ final class CriteriaCompiler
return [$quotedColumn . ' IS NULL', []];
}
// A backed enum is compared by its scalar value: PDO cannot bind the enum instance itself.
if ($value instanceof \BackedEnum) {
return [$quotedColumn . ' = ?', [$value->value]];
}
if (is_array($value)) {
if ($value === []) {
return ['1 = 0', []];
}
return $this->dialect->renderCondition($quotedColumn, Cond::in(array_values($value)));
$values = array_map(static fn(mixed $entry): mixed => $entry instanceof \BackedEnum
? $entry->value
: $entry, array_values($value));
return $this->dialect->renderCondition($quotedColumn, Cond::in($values));
}
return [$quotedColumn . ' = ?', [$value]];
+3 -3
View File
@@ -35,7 +35,7 @@ final class QueryBuilder
$table = $this->dialect->quoteIdentifier($metadata->table());
$list = $this->compileSelectList($metadata, $columns);
[$where, $params] = (new CriteriaCompiler($this->dialect))->compile($metadata, $criteria);
[$where, $params] = new CriteriaCompiler($this->dialect)->compile($metadata, $criteria);
$sql = 'SELECT ' . $list . ' FROM ' . $table;
@@ -56,7 +56,7 @@ final class QueryBuilder
public function count(ClassMetadata $metadata, array $criteria): array
{
$table = $this->dialect->quoteIdentifier($metadata->table());
[$where, $params] = (new CriteriaCompiler($this->dialect))->compile($metadata, $criteria);
[$where, $params] = new CriteriaCompiler($this->dialect)->compile($metadata, $criteria);
$sql = 'SELECT COUNT(*) AS aggregate FROM ' . $table;
@@ -89,7 +89,7 @@ final class QueryBuilder
$quoted = $this->dialect->quoteIdentifier($metadata->propertyMetadata($property)->column);
$table = $this->dialect->quoteIdentifier($metadata->table());
[$where, $params] = (new CriteriaCompiler($this->dialect))->compile($metadata, $criteria);
[$where, $params] = new CriteriaCompiler($this->dialect)->compile($metadata, $criteria);
$sql = 'SELECT ' . $function . '(' . $quoted . ') AS aggregate FROM ' . $table;
+33 -9
View File
@@ -25,7 +25,7 @@ use Camelia\Orm\Support\TypeCaster;
* Public read and write API for one model class.
*
* @api
* @template T of Model
* @template-covariant T of Model
*/
final class Repository
{
@@ -34,7 +34,7 @@ final class Repository
private readonly QueryBuilder $builder;
/**
* @param class-string<T> $class
* @param class-string<T> $class Not a field of the covariant template; kept for IDE inference.
*/
public function __construct(
private readonly Connection $connection,
@@ -218,6 +218,13 @@ final class Repository
}
/**
* Builds a new model from $values and inserts it.
*
* `hydrate()` deliberately skips #[Guarded] properties, which is right for request payloads but
* wrong here: this method is called from trusted server code (a seeder, a service), and a guarded
* column such as a password hash would otherwise be silently dropped. Guarded values are applied
* after hydration, so `create()` can persist every column it is given.
*
* @param array<string, mixed> $values
* @return T
*/
@@ -226,6 +233,23 @@ final class Repository
/** @var T $model */
$model = new $this->class();
$model->hydrate($values);
$metadata = $this->metadata();
foreach ($values as $key => $value) {
$property = $metadata->resolveProperty((string) $key);
if ($property === null) {
continue;
}
$definition = $metadata->propertyMetadata($property);
if ($definition->guarded && !$definition->ignored && !$definition->primaryKey) {
$model->set($property, $model->castFor($definition, $value));
}
}
$this->persister()->insert($model);
return $model;
@@ -329,6 +353,10 @@ final class Repository
return null;
}
if ($definition->enumClass !== null) {
return TypeCaster::castEnum($value, $definition->enumClass, true, $definition->name);
}
return TypeCaster::cast($value, $definition->type, true, $definition->name);
}
@@ -726,7 +754,9 @@ final class Repository
throw ConfigurationException::relationDepthExceeded(self::MAX_RELATION_DEPTH);
}
if (!$metadata->hasProperty($name) || $metadata->properties()[$name]->relation === null) {
$relation = $metadata->hasProperty($name) ? $metadata->properties()[$name]->relation : null;
if ($relation === null) {
throw MetadataException::unknownRelation($metadata->class, $name);
}
@@ -734,12 +764,6 @@ final class Repository
return;
}
$relation = $metadata->properties()[$name]->relation;
if ($relation === null) {
return;
}
$next = $this->relatedRepository($relation->relatedClass)->metadata();
foreach ($nested as $key => $value) {
+62
View File
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Seeding;
use Camelia\Orm\Model;
use Camelia\Orm\Repository;
/**
* Convenience base for seeders that insert reference rows.
*
* It offers the two things hand-written seeders get wrong: an idempotent insert and a count. It
* never updates an existing row, because a seeder that silently overwrites data a user edited is
* a footgun.
*
* @api
*/
abstract class AbstractSeeder implements Seeder
{
private int $inserted = 0;
private int $skipped = 0;
/**
* Inserts $values when $criteria match nothing, and leaves the row alone when they do.
*
* @template T of Model
* @param Repository<T> $repository
* @param array<string, mixed> $criteria
* @param array<string, mixed> $values merged into the criteria on insert
* @return T|null the new row, or null when it already existed
*/
final protected function seedOnce(
Repository $repository,
array $criteria,
array $values = [],
): ?Model {
if ($repository->findFirst($criteria) !== null) {
$this->skipped++;
return null;
}
$this->inserted++;
return $repository->create([...$criteria, ...$values]);
}
/**
* Rows inserted by the last run(). Used by the runner for its report.
*/
final public function inserted(): int
{
return $this->inserted;
}
final public function skipped(): int
{
return $this->skipped;
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Seeding;
use Camelia\Orm\Orm;
/**
* Fills reference or bootstrap data: the permission catalogue, the built-in roles, the first
* administrator.
*
* A seeder is not a migration. It never changes the schema, it runs on demand, and it must be safe
* to run twice: seeding an existing row is a no-op, not an error.
*
* @api
*/
interface Seeder
{
/**
* Stable, command-line friendly identifier. Also the sort key when order matters.
*/
public function name(): string;
/**
* Writes the rows. Called inside the runner's transaction.
*/
public function run(Orm $orm): void;
}
+51
View File
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Seeding;
/**
* What one seeder did, so the caller can report it without inspecting the database.
*
* @api
*/
final readonly class SeederResult
{
public function __construct(
public string $seeder,
public int $inserted,
public int $skipped,
public float $seconds,
public ?string $error = null,
) {}
public static function started(string $seeder): self
{
return new self($seeder, 0, 0, 0.0);
}
public function isSuccessful(): bool
{
return $this->error === null;
}
public function isNoOp(): bool
{
return $this->error === null && $this->inserted === 0;
}
public function summary(): string
{
if ($this->error !== null) {
return sprintf('%s: FAILED — %s', $this->seeder, $this->error);
}
return sprintf(
'%s: %d inserted, %d skipped (%.0f ms)',
$this->seeder,
$this->inserted,
$this->skipped,
$this->seconds * 1000,
);
}
}
+114
View File
@@ -0,0 +1,114 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Seeding;
use Camelia\Orm\Exception\ConfigurationException;
use Camelia\Orm\Orm;
/**
* Runs an ordered list of seeders inside one transaction.
*
* Either the whole batch applies or none of it does: a seeder that fails leaves the database
* untouched, which is what makes re-running the command after a fix safe.
*
* Seeders that extend AbstractSeeder report how many rows they inserted; a plain Seeder reports
* zero and is still executed.
*
* @api
*/
final class SeederRunner
{
/** @var list<Seeder> */
private array $seeders = [];
public function __construct(
private readonly Orm $orm,
) {}
/**
* @param list<Seeder> $seeders
*/
public function addMany(array $seeders): self
{
foreach ($seeders as $seeder) {
$this->add($seeder);
}
return $this;
}
public function add(Seeder $seeder): self
{
$this->seeders[] = $seeder;
return $this;
}
/**
* Commands read this to offer `--only <name>` without running anything.
*
* @return list<string>
*/
public function names(): array
{
return array_map(static fn(Seeder $seeder): string => $seeder->name(), $this->seeders);
}
/**
* @param list<string> $only run just these, in the order given
* @return list<SeederResult>
*/
public function run(array $only = []): array
{
$selected = $this->select($only);
if ($selected === []) {
return [];
}
return $this->orm->transaction(fn(): array => array_map($this->execute(...), $selected));
}
/**
* @param list<string> $only
* @return list<Seeder>
*/
private function select(array $only): array
{
if ($only === []) {
return $this->seeders;
}
$unknown = array_values(array_diff($only, $this->names()));
if ($unknown !== []) {
throw ConfigurationException::unknownSeeder($unknown, $this->names());
}
$selected = [];
foreach ($only as $name) {
foreach ($this->seeders as $seeder) {
if ($seeder->name() === $name) {
$selected[] = $seeder;
}
}
}
return $selected;
}
private function execute(Seeder $seeder): SeederResult
{
$started = hrtime(true);
$seeder->run($this->orm);
$elapsed = (hrtime(true) - $started) / 1_000_000_000;
$inserted = $seeder instanceof AbstractSeeder ? $seeder->inserted() : 0;
$skipped = $seeder instanceof AbstractSeeder ? $seeder->skipped() : 0;
return new SeederResult($seeder->name(), $inserted, $skipped, $elapsed);
}
}
+6
View File
@@ -116,6 +116,12 @@ final class TypeCaster
return $value->format('Y-m-d H:i:s');
}
// PDO with ATTR_EMULATE_PREPARES = false sends a native bool as an empty string, which a
// TINYINT rejects with "Incorrect integer value: ''". Boolean columns are always 0/1.
if (is_bool($value)) {
return $value ? 1 : 0;
}
return $value;
}
+29
View File
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Fixture;
use Camelia\Orm\Attribute\AutoIncrement;
use Camelia\Orm\Attribute\Enum;
use Camelia\Orm\Attribute\PrimaryKey;
use Camelia\Orm\Attribute\TableName;
use Camelia\Orm\Model;
enum EstadoArticulo: string
{
case Borrador = 'borrador';
case Publicado = 'publicado';
}
#[TableName('articulos_estado')]
final class ArticuloConEstado extends Model
{
#[PrimaryKey, AutoIncrement]
public ?int $codigo = null;
public string $nombre = '';
#[Enum(EstadoArticulo::class)]
public ?EstadoArticulo $estado = EstadoArticulo::Borrador;
}
+11
View File
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Fixture;
enum EstadoPedido: string
{
case Pendiente = 'pendiente';
case Confirmado = 'confirmado';
}
+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);
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit;
use Camelia\Orm\Attribute\AutoIncrement;
use Camelia\Orm\Attribute\Guarded;
use Camelia\Orm\Attribute\PrimaryKey;
use Camelia\Orm\Attribute\TableName;
use Camelia\Orm\Model;
use Camelia\Orm\Orm;
use Camelia\Orm\Tests\Support\FakeConnection;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
#[TableName('cuentas_prueba')]
final class CuentaDePrueba extends Model
{
#[PrimaryKey, AutoIncrement]
public ?int $id = null;
public string $correo = '';
#[Guarded]
public string $passwordHash = '';
}
/**
* Regression: Repository::create() delegated to hydrate(), which skips #[Guarded] properties by
* design, so a trusted caller passing a password hash silently persisted an empty string.
*/
final class CreateWithGuardedTest extends TestCase
{
#[Test]
public function create_persists_a_guarded_column_from_trusted_values(): void
{
$connection = new FakeConnection();
$model = Orm::fromConnection($connection)
->repository(CuentaDePrueba::class)
->create([
'correo' => 'a@x',
'passwordHash' => 'ARGON2ID',
]);
self::assertSame('ARGON2ID', $model->passwordHash);
self::assertStringContainsString('`password_hash`', $connection->lastSql());
}
#[Test]
public function hydrate_still_rejects_a_guarded_column_from_a_payload(): void
{
$model = new CuentaDePrueba()->hydrate([
'correo' => 'a@x',
'passwordHash' => 'FROM-PAYLOAD',
]);
self::assertSame('', $model->passwordHash);
self::assertSame('a@x', $model->correo);
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit;
use Camelia\Orm\Orm;
use Camelia\Orm\Tests\Fixture\ArticuloConEstado;
use Camelia\Orm\Tests\Fixture\EstadoArticulo;
use Camelia\Orm\Tests\Support\FakeConnection;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
/**
* Regression: reading a row whose model declares #[Enum] threw a TypeError because
* Repository::castDatabaseValue() called TypeCaster::cast() instead of castEnum().
*/
final class EnumHydrationTest extends TestCase
{
#[Test]
public function it_hydrates_an_enum_column_from_its_scalar_value(): void
{
$connection = new FakeConnection();
$connection->rows = [['codigo' => '3', 'nombre' => 'Taladro', 'estado' => 'publicado']];
$models = Orm::fromConnection($connection)->repository(ArticuloConEstado::class)->find();
self::assertCount(1, $models);
self::assertInstanceOf(ArticuloConEstado::class, $models[0]);
self::assertSame(EstadoArticulo::Publicado, $models[0]->estado);
}
#[Test]
public function it_hydrates_a_nullable_enum_column_as_null(): void
{
$connection = new FakeConnection();
$connection->rows = [['codigo' => '4', 'nombre' => 'Sierra', 'estado' => null]];
$models = Orm::fromConnection($connection)->repository(ArticuloConEstado::class)->find();
self::assertCount(1, $models);
self::assertNull($models[0]->estado);
}
}
+12 -12
View File
@@ -23,7 +23,7 @@ final class MetadataFactoryTest extends TestCase
#[Test]
public function it_reads_table_and_primary_key(): void
{
$metadata = (new MetadataFactory())->forClass(Usuario::class);
$metadata = new MetadataFactory()->forClass(Usuario::class);
self::assertSame('usuarios', $metadata->table());
self::assertSame('codigo', $metadata->primaryKey());
@@ -33,7 +33,7 @@ final class MetadataFactoryTest extends TestCase
#[Test]
public function it_converts_property_names_to_columns(): void
{
$metadata = (new MetadataFactory())->forClass(Usuario::class);
$metadata = new MetadataFactory()->forClass(Usuario::class);
self::assertSame('password_hash', $metadata->column('passwordHash'));
self::assertSame('passwordHash', $metadata->property('password_hash'));
@@ -43,7 +43,7 @@ final class MetadataFactoryTest extends TestCase
#[Test]
public function it_honours_an_explicit_column_name(): void
{
$metadata = (new MetadataFactory())->forClass(Factura::class);
$metadata = new MetadataFactory()->forClass(Factura::class);
self::assertSame('importe_total', $metadata->column('total'));
}
@@ -51,7 +51,7 @@ final class MetadataFactoryTest extends TestCase
#[Test]
public function it_excludes_relations_from_writable_columns(): void
{
$metadata = (new MetadataFactory())->forClass(Factura::class);
$metadata = new MetadataFactory()->forClass(Factura::class);
self::assertSame(['usuarioCodigo', 'total'], $metadata->writable());
self::assertCount(2, $metadata->relations());
@@ -60,7 +60,7 @@ final class MetadataFactoryTest extends TestCase
#[Test]
public function it_resolves_belongs_to_metadata(): void
{
$metadata = (new MetadataFactory())->forClass(Factura::class);
$metadata = new MetadataFactory()->forClass(Factura::class);
$relation = $metadata->properties()['usuario']->relation;
self::assertNotNull($relation);
@@ -72,7 +72,7 @@ final class MetadataFactoryTest extends TestCase
#[Test]
public function it_resolves_belongs_to_many_pivot_metadata(): void
{
$metadata = (new MetadataFactory())->forClass(Articulo::class);
$metadata = new MetadataFactory()->forClass(Articulo::class);
$relation = $metadata->properties()['etiquetas']->relation;
self::assertNotNull($relation);
@@ -89,7 +89,7 @@ final class MetadataFactoryTest extends TestCase
$this->expectException(MetadataException::class);
$this->expectExceptionMessage('[M2]');
(new MetadataFactory())->forClass(SinTableName::class);
new MetadataFactory()->forClass(SinTableName::class);
}
#[Test]
@@ -98,7 +98,7 @@ final class MetadataFactoryTest extends TestCase
$this->expectException(MetadataException::class);
$this->expectExceptionMessage('[M3]');
(new MetadataFactory())->forClass(SinPrimaryKey::class);
new MetadataFactory()->forClass(SinPrimaryKey::class);
}
#[Test]
@@ -107,7 +107,7 @@ final class MetadataFactoryTest extends TestCase
$this->expectException(MetadataException::class);
$this->expectExceptionMessage('[M3]');
(new MetadataFactory())->forClass(DosPrimaryKeys::class);
new MetadataFactory()->forClass(DosPrimaryKeys::class);
}
#[Test]
@@ -116,7 +116,7 @@ final class MetadataFactoryTest extends TestCase
$this->expectException(MetadataException::class);
$this->expectExceptionMessage('[M4]');
(new MetadataFactory())->forClass(SinTipo::class);
new MetadataFactory()->forClass(SinTipo::class);
}
#[Test]
@@ -125,7 +125,7 @@ final class MetadataFactoryTest extends TestCase
$this->expectException(MetadataException::class);
$this->expectExceptionMessage('[M7]');
(new MetadataFactory())->forClass(ColumnaDuplicada::class);
new MetadataFactory()->forClass(ColumnaDuplicada::class);
}
#[Test]
@@ -134,6 +134,6 @@ final class MetadataFactoryTest extends TestCase
$this->expectException(MetadataException::class);
$this->expectExceptionMessage('[M5]');
(new MetadataFactory())->forClass(RelacionNoNulable::class);
new MetadataFactory()->forClass(RelacionNoNulable::class);
}
}
+13 -13
View File
@@ -33,7 +33,7 @@ final class ModelTest extends TestCase
#[Test]
public function it_hydrates_by_property_name(): void
{
$usuario = (new Usuario())->hydrate(['nombre' => 'Ana', 'activo' => false]);
$usuario = new Usuario()->hydrate(['nombre' => 'Ana', 'activo' => false]);
self::assertSame('Ana', $usuario->nombre);
self::assertFalse($usuario->activo);
@@ -42,7 +42,7 @@ final class ModelTest extends TestCase
#[Test]
public function it_hydrates_by_column_name(): void
{
$factura = (new Factura())->hydrate(['importe_total' => '12.5']);
$factura = new Factura()->hydrate(['importe_total' => '12.5']);
self::assertSame(12.5, $factura->total);
}
@@ -50,7 +50,7 @@ final class ModelTest extends TestCase
#[Test]
public function it_prefers_the_property_when_both_forms_are_present(): void
{
$factura = (new Factura())->hydrate(['total' => 1.0, 'importe_total' => 2.0]);
$factura = new Factura()->hydrate(['total' => 1.0, 'importe_total' => 2.0]);
self::assertSame(1.0, $factura->total);
}
@@ -58,7 +58,7 @@ final class ModelTest extends TestCase
#[Test]
public function it_skips_guarded_properties(): void
{
$usuario = (new Usuario())->hydrate(['passwordHash' => 'secreto']);
$usuario = new Usuario()->hydrate(['passwordHash' => 'secreto']);
self::assertSame('', $usuario->passwordHash);
}
@@ -68,13 +68,13 @@ final class ModelTest extends TestCase
{
$this->expectException(\InvalidArgumentException::class);
(new Usuario())->hydrateStrict(['passwordHash' => 'secreto']);
new Usuario()->hydrateStrict(['passwordHash' => 'secreto']);
}
#[Test]
public function it_ignores_unknown_keys(): void
{
$usuario = (new Usuario())->hydrate(['inexistente' => 1, 'nombre' => 'Ana']);
$usuario = new Usuario()->hydrate(['inexistente' => 1, 'nombre' => 'Ana']);
self::assertSame('Ana', $usuario->nombre);
}
@@ -82,7 +82,7 @@ final class ModelTest extends TestCase
#[Test]
public function it_never_hydrates_the_primary_key(): void
{
$usuario = (new Usuario())->hydrate(['codigo' => 99]);
$usuario = new Usuario()->hydrate(['codigo' => 99]);
self::assertNull($usuario->codigo);
}
@@ -92,13 +92,13 @@ final class ModelTest extends TestCase
{
$this->expectException(\InvalidArgumentException::class);
(new Usuario())->hydrate(['activo' => 'no-es-bool']);
new Usuario()->hydrate(['activo' => 'no-es-bool']);
}
#[Test]
public function it_serializes_writable_columns_by_column_name(): void
{
$usuario = (new Usuario())->hydrate(['nombre' => 'Ana']);
$usuario = new Usuario()->hydrate(['nombre' => 'Ana']);
$array = $usuario->toArray();
self::assertSame('Ana', $array['nombre']);
@@ -109,7 +109,7 @@ final class ModelTest extends TestCase
#[Test]
public function it_serializes_json(): void
{
$json = (new Usuario())->hydrate(['nombre' => 'Ana'])->toJson();
$json = new Usuario()->hydrate(['nombre' => 'Ana'])->toJson();
$decoded = json_decode($json, true);
self::assertIsArray($decoded);
@@ -129,7 +129,7 @@ final class ModelTest extends TestCase
#[Test]
public function it_reports_a_too_long_value(): void
{
$usuario = (new Usuario())->hydrate(['clave' => 'supercalifragilistico']);
$usuario = new Usuario()->hydrate(['clave' => 'supercalifragilistico']);
self::assertStringContainsString('10', $usuario->validate()['clave'][0]);
}
@@ -137,7 +137,7 @@ final class ModelTest extends TestCase
#[Test]
public function it_is_valid_when_no_rule_fails(): void
{
$usuario = (new Usuario())->hydrate(['clave' => 'abc']);
$usuario = new Usuario()->hydrate(['clave' => 'abc']);
self::assertTrue($usuario->isValid());
}
@@ -145,7 +145,7 @@ final class ModelTest extends TestCase
#[Test]
public function it_replicates_without_the_primary_key(): void
{
$usuario = (new Usuario())->hydrate(['nombre' => 'Ana']);
$usuario = new Usuario()->hydrate(['nombre' => 'Ana']);
$usuario->codigo = 5;
$copy = $usuario->replicate();
+7 -7
View File
@@ -31,7 +31,7 @@ final class PersisterTest extends TestCase
public function it_inserts_and_assigns_the_generated_key(): void
{
$this->connection->lastInsertId = '42';
$usuario = (new Usuario())->hydrate(['nombre' => 'Ana', 'clave' => 'abc']);
$usuario = new Usuario()->hydrate(['nombre' => 'Ana', 'clave' => 'abc']);
$key = $this->persister->insert($usuario);
@@ -44,7 +44,7 @@ final class PersisterTest extends TestCase
public function it_only_writes_writable_columns(): void
{
$this->connection->lastInsertId = '1';
$usuario = (new Usuario())->hydrate(['nombre' => 'Ana', 'clave' => 'abc']);
$usuario = new Usuario()->hydrate(['nombre' => 'Ana', 'clave' => 'abc']);
$this->persister->insert($usuario);
@@ -57,7 +57,7 @@ final class PersisterTest extends TestCase
#[Test]
public function it_saves_as_update_when_the_key_is_present(): void
{
$usuario = (new Usuario())->hydrate(['nombre' => 'Ana', 'clave' => 'abc']);
$usuario = new Usuario()->hydrate(['nombre' => 'Ana', 'clave' => 'abc']);
$usuario->codigo = 9;
$this->persister->save($usuario);
@@ -69,7 +69,7 @@ final class PersisterTest extends TestCase
public function it_saves_as_insert_when_the_key_is_absent(): void
{
$this->connection->lastInsertId = '3';
$usuario = (new Usuario())->hydrate(['nombre' => 'Ana', 'clave' => 'abc']);
$usuario = new Usuario()->hydrate(['nombre' => 'Ana', 'clave' => 'abc']);
$this->persister->save($usuario);
@@ -81,13 +81,13 @@ final class PersisterTest extends TestCase
{
$this->expectException(ValidationException::class);
$this->persister->insert((new Usuario())->hydrate(['nombre' => 'Ana']));
$this->persister->insert(new Usuario()->hydrate(['nombre' => 'Ana']));
}
#[Test]
public function it_refuses_to_write_a_partial_model(): void
{
$usuario = (new Usuario())->hydrate(['nombre' => 'Ana', 'clave' => 'abc']);
$usuario = new Usuario()->hydrate(['nombre' => 'Ana', 'clave' => 'abc']);
$usuario->codigo = 1;
$usuario->markPartial();
@@ -149,7 +149,7 @@ final class PersisterTest extends TestCase
$listener,
);
$persister->insert((new Usuario())->hydrate(['nombre' => 'Ana', 'clave' => 'abc']));
$persister->insert(new Usuario()->hydrate(['nombre' => 'Ana', 'clave' => 'abc']));
self::assertSame([['action' => 'insert', 'pk' => 7]], $listener->calls);
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit\Query;
use Camelia\Orm\Metadata\MetadataFactory;
use Camelia\Orm\Query\CriteriaCompiler;
use Camelia\Orm\Query\MySqlDialect;
use Camelia\Orm\Tests\Fixture\ArticuloConEstado;
use Camelia\Orm\Tests\Fixture\EstadoPedido;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
/**
* Regression: an enum used as a criteria value reached PDO as an object and failed with
* "Object of class X could not be converted to string". A backed enum must be compared by its
* scalar value, both alone and inside an IN list.
*/
final class CriteriaCompilerEnumTest extends TestCase
{
private CriteriaCompiler $compiler;
protected function setUp(): void
{
$this->compiler = new CriteriaCompiler(new MySqlDialect());
}
#[Test]
public function it_compiles_an_enum_criterion_to_its_scalar_value(): void
{
$metadata = new MetadataFactory()->forClass(ArticuloConEstado::class);
[$sql, $params] = $this->compiler->compile($metadata, [
'estado' => EstadoPedido::Confirmado,
]);
self::assertSame('`estado` = ?', $sql);
self::assertSame(['confirmado'], $params);
}
#[Test]
public function it_compiles_a_list_of_enums_to_their_scalar_values(): void
{
$metadata = new MetadataFactory()->forClass(ArticuloConEstado::class);
[, $params] = $this->compiler->compile($metadata, [
'estado' => [EstadoPedido::Pendiente, EstadoPedido::Confirmado],
]);
self::assertSame(['pendiente', 'confirmado'], $params);
}
}
+1 -1
View File
@@ -143,6 +143,6 @@ final class CriteriaCompilerTest extends TestCase
private function metadata(): \Camelia\Orm\Metadata\ClassMetadata
{
return (new MetadataFactory())->forClass(Usuario::class);
return new MetadataFactory()->forClass(Usuario::class);
}
}
+2 -2
View File
@@ -23,7 +23,7 @@ final class QueryBuilderTest extends TestCase
protected function setUp(): void
{
$this->builder = new QueryBuilder(new MySqlDialect());
$this->usuarios = (new MetadataFactory())->forClass(Usuario::class);
$this->usuarios = new MetadataFactory()->forClass(Usuario::class);
}
#[Test]
@@ -42,7 +42,7 @@ final class QueryBuilderTest extends TestCase
#[Test]
public function it_excludes_relations_from_the_select_list(): void
{
$metadata = (new MetadataFactory())->forClass(Factura::class);
$metadata = new MetadataFactory()->forClass(Factura::class);
$compiled = $this->builder->select($metadata, []);
self::assertStringNotContainsString('`usuario`', $compiled['sql']);
+205
View File
@@ -0,0 +1,205 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit\Seeding;
use Camelia\Orm\Exception\ConfigurationException;
use Camelia\Orm\Orm;
use Camelia\Orm\Seeding\AbstractSeeder;
use Camelia\Orm\Seeding\Seeder;
use Camelia\Orm\Seeding\SeederRunner;
use Camelia\Orm\Tests\Fixture\Usuario;
use Camelia\Orm\Tests\Support\FakeConnection;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class SeederRunnerTest extends TestCase
{
private FakeConnection $connection;
private Orm $orm;
protected function setUp(): void
{
$this->connection = new FakeConnection();
$this->orm = Orm::fromConnection($this->connection);
}
#[Test]
public function it_runs_seeders_in_registration_order(): void
{
$log = new \ArrayObject();
$runner = new SeederRunner($this->orm)->addMany([
$this->recordingSeeder('first', $log),
$this->recordingSeeder('second', $log),
]);
$runner->run();
self::assertSame(['first', 'second'], $log->getArrayCopy());
}
#[Test]
public function it_wraps_the_batch_in_one_transaction(): void
{
$log = new \ArrayObject();
new SeederRunner($this->orm)->add($this->recordingSeeder('only', $log))->run();
self::assertSame(1, $this->connection->beginCount);
self::assertSame(1, $this->connection->commitCount);
self::assertSame(0, $this->connection->rollBackCount);
}
#[Test]
public function it_rolls_back_the_whole_batch_when_a_seeder_throws(): void
{
$log = new \ArrayObject();
$failing = new class implements Seeder {
public function name(): string
{
return 'failing';
}
public function run(Orm $orm): void
{
throw new \RuntimeException('boom');
}
};
$runner = new SeederRunner($this->orm)->addMany([
$this->recordingSeeder('ok', $log),
$failing,
]);
$this->expectException(\RuntimeException::class);
try {
$runner->run();
} finally {
self::assertSame(1, $this->connection->rollBackCount);
self::assertSame(0, $this->connection->commitCount);
}
}
#[Test]
public function it_lists_registered_names(): void
{
$log = new \ArrayObject();
$runner = new SeederRunner($this->orm)->addMany([
$this->recordingSeeder('roles', $log),
$this->recordingSeeder('admin-user', $log),
]);
self::assertSame(['roles', 'admin-user'], $runner->names());
}
#[Test]
public function it_runs_only_the_requested_seeders_in_the_requested_order(): void
{
$log = new \ArrayObject();
$runner = new SeederRunner($this->orm)->addMany([
$this->recordingSeeder('permissions', $log),
$this->recordingSeeder('roles', $log),
$this->recordingSeeder('admin-user', $log),
]);
$runner->run(['admin-user', 'permissions']);
self::assertSame(['admin-user', 'permissions'], $log->getArrayCopy());
}
#[Test]
public function it_rejects_an_unknown_seeder_name(): void
{
$log = new \ArrayObject();
$runner = new SeederRunner($this->orm)->add($this->recordingSeeder('known', $log));
$this->expectException(ConfigurationException::class);
$this->expectExceptionMessage('Unknown seeder(s): nope');
$runner->run(['nope']);
}
#[Test]
public function it_does_nothing_without_seeders(): void
{
$results = new SeederRunner($this->orm)->run();
self::assertSame([], $results);
self::assertSame(0, $this->connection->beginCount);
}
#[Test]
public function it_reports_inserted_and_skipped_counts(): void
{
$this->connection->rowBatches = [
[],
[['codigo' => '1']],
];
$seeder = new class extends AbstractSeeder {
public function name(): string
{
return 'counted';
}
public function run(Orm $orm): void
{
$repository = $orm->repository(Usuario::class);
$this->seedOnce($repository, ['correo' => 'a@x'], ['clave' => 'a']);
$this->seedOnce($repository, ['correo' => 'b@x'], ['clave' => 'b']);
}
};
$results = new SeederRunner($this->orm)->add($seeder)->run();
self::assertCount(1, $results);
self::assertSame(1, $results[0]->inserted);
self::assertSame(1, $results[0]->skipped);
self::assertTrue($results[0]->isSuccessful());
}
#[Test]
public function a_plain_seeder_reports_zero_counts(): void
{
$log = new \ArrayObject();
$results = new SeederRunner($this->orm)->add($this->recordingSeeder('plain', $log))->run();
self::assertSame(0, $results[0]->inserted);
self::assertTrue($results[0]->isNoOp());
}
/**
* @param \ArrayObject<int, string> $log
*/
private function recordingSeeder(string $name, \ArrayObject $log): Seeder
{
return new class($name, $log) implements Seeder {
/**
* @param \ArrayObject<int, string> $log
*/
public function __construct(
private readonly string $label,
private readonly \ArrayObject $log,
) {}
public function name(): string
{
return $this->label;
}
public function run(Orm $orm): void
{
$this->log->append($this->label);
}
};
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit\Support;
use Camelia\Orm\Support\TypeCaster;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
/**
* Regression: PDO with ATTR_EMULATE_PREPARES = false sends a native PHP bool as an empty string.
* MySQL/MariaDB answers "Incorrect integer value: '' for column ...", so every TINYINT column was
* unwritable. Booleans must reach the driver as 1/0.
*/
final class TypeCasterDatabaseValueTest extends TestCase
{
#[Test]
public function it_converts_a_bool_to_an_integer(): void
{
self::assertSame(1, TypeCaster::toDatabaseValue(true));
self::assertSame(0, TypeCaster::toDatabaseValue(false));
}
#[Test]
public function it_leaves_other_scalars_untouched(): void
{
self::assertSame(42, TypeCaster::toDatabaseValue(42));
self::assertSame('texto', TypeCaster::toDatabaseValue('texto'));
self::assertSame(1.5, TypeCaster::toDatabaseValue(1.5));
self::assertNull(TypeCaster::toDatabaseValue(null));
}
}