feat: initial commit of camelia/orm

Attribute-mapped Active Record ORM for MariaDB/MySQL over PDO.

- Attribute-driven metadata: TableName, PrimaryKey, AutoIncrement, Column,
  Guarded, Ignore, Required, Enum, Nullable, Length, Precision, Unique,
  UniqueGroup, Index, MaxLength.
- Relationship mapping: BelongsTo, HasOne, HasMany, BelongsToMany with
  batched eager loading and a 3-level depth limit.
- Orm entry point with fromArray, fromPdo, fromEnv and nested transactions.
- Immutable Query with Cond operators and GroupCond grouping.
- Repository read and write API, pagination, and typed exception hierarchy.
- Declares PHP >=8.3; Mago and PHPStan pin the parser to 8.3.
- MIT license.
This commit is contained in:
dgarcia committed 2026-11-15 10:14:22 -03:00
commit 66e93e3070
97 files changed
+12188

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
/vendor/
.phpunit.cache/
.phpunit.cache.integration/
.phpunit.result.cache
.mago.cache
coverage/
+74
View File
@@ -0,0 +1,74 @@
# AGENTS.md — `camelia/orm` (librería PHP independiente)
Paquete `camelia/orm`, de Dr2g Sistemas. Namespace raíz `Camelia\Orm` → `src/` (PSR-4).
## Leer primero
`especificaciones-orm.md` es la fuente de verdad del diseño. **La §0 es normativa de
nomenclatura**: todo nombre de clase, método y parámetro sale de su glosario. Si un nombre no está
ahí, no existe. Ojo: la spec conserva el nombre histórico `azulerp/orm` y `Azul\Orm` en algunos
ejemplos; el nombre vigente es `camelia/orm` y `Camelia\Orm`.
## Reglas de nomenclatura que más se rompen
- Lecturas: prefijo `find`. Escrituras: verbo de destino. Un `find*` **nunca** escribe.
- `...Column()` devuelve columna SQL; sin sufijo devuelve propiedad PHP.
- Booleanos con `is`/`has`/`can`. Colecciones en plural.
- Sin abreviaturas: `Metadata`, no `Meta`; `Configuration`, no `Config`.
- La implementación lleva el prefijo del driver (`PdoConnection`), la interfaz el rol (`Connection`).
## No arrastres el legado
Descartado a propósito: `SimpleModelBase`, `Conexion`, `_in()`, `FilterExpr`, `$clienteRel`,
`findOne`, `findAll`, `findOrFail`, `FluentQuery`, `updateByPk`, `deleteByPk`, `loadRelations`,
`Model::fill`, `fromArray`/`fromObject`, `SqlDialect`, `CriterionCompiler`, `ConnectionInterface`.
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).
- `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.
## Gate antes de commitear
```bash
composer check # fmt:check -> lint -> analyze -> phpstan -> test
```
Nunca mergees con uno en rojo. Orden obligatorio.
## Toolchain: Mago
`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.
- `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.
No lo regeneres a ciegas: si crece, revisa qué se aceptó.
- Después de `mago fmt`, corre `composer fmt:check` y `php -l` sobre lo tocado. El formatter es
estable, pero el error de versión anterior producía PHP que solo parseaba en 8.4.
## Base de datos de referencia
No hay base conectada. El esquema accesible vía MCP `mariadb` es `aguaflow_prod` (tablas en
snake_case: `usuarios`, `facturaciones`, `clientes`, `zonas`, `auditoria`). Úsalo solo para observar
patrones reales de nombres y tipos; **no** como DSN de tests.
## Trampas de implementación
- El compilador SQL se prueba con `toSql()` (golden SQL + params), nunca con resultados de filas.
- `PdoConnection` **nunca** usa `bindParam`: siempre `execute(array)`, con statements cacheados.
- `Query` es inmutable; cada método devuelve copia. `QueryState` es el snapshot que lo permite. La
única mutación es `GroupCond` dentro de `whereGroup()`.
- `Model` no importa `Query` ni `Connection`. Persistir desde el modelo rompe el contrato: usa
`Repository`.
- `select()` parcial marca `isPartial()`; `save()`/`update()` sobre un modelo parcial lanzan. La vía
parcial es `patch($pk, $values)`.
- Todo error SQL lanza `DatabaseException`. No hay `try/catch` interno que devuelva vacío.
- `Persister`, `Validator`, `CriteriaCompiler`, `QueryBuilder`, `MetadataFactory`, `Constraint` y
`QueryState` son `@internal`.
+29
View File
@@ -0,0 +1,29 @@
# Changelog
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
- Attribute-driven metadata: `TableName`, `PrimaryKey`, `AutoIncrement`, `Column`, `Guarded`,
`Ignore`, `Required`, `Enum`, `Nullable`, `Length`, `Precision`, `Unique`, `UniqueGroup`,
`Index`, `MaxLength`.
- Relationship mapping: `BelongsTo`, `HasOne`, `HasMany`, `BelongsToMany`, with batched eager
loading (no N+1) and a hard 3-level depth limit.
- `Orm` entry point with `fromArray`, `fromPdo`, `fromEnv` and nested `transaction()`.
- `Repository` read API: `find`, `findFirst`, `findByPk`, `findByPkOrFail`, `findOrCreate`,
`count`, `exists`, `sum`, `avg`, `max`, `min`, `page`, `query`.
- `Repository` write API: `save`, `create`, `update`, `delete`, `patch`, `remove`.
- Immutable `Query` with `Cond` operators and `GroupCond` grouping.
- Typed exception hierarchy rooted at `OrmException`.
- `AuditListener` and PSR-3 `LoggerInterface` extension points.
- `TypeCaster` with strict refusal of values that cannot be cast.
### Notes
- `Model::hydrate()` accepts property or column keys; the property name wins when both are present.
- `Page::$totalPages` is always an `int`.
- No global helper functions are registered.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Dario Garcia
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+148
View File
@@ -0,0 +1,148 @@
# camelia-orm
Lightweight attribute-mapped Active Record ORM for MariaDB/MySQL over PDO, by Dr2g Sistemas.
- **Package:** `camelia/orm` · **Namespace:** `Camelia\Orm`
- **PHP** `>=8.3`, extensions `pdo_mysql` and `mbstring`
- **Runtime dependencies:** `psr/log` (PSR-3, optional usage). `brick/math` is a suggestion for
`BigDecimal` properties.
The contract lives in [`especificaciones-orm.md`](especificaciones-orm.md); this file only shows usage.
The full developer guide, organised by task, is in [`docs/GUIA-PROGRAMADOR.md`](docs/GUIA-PROGRAMADOR.md).
## Install
```bash
composer require camelia/orm
```
## Bootstrap
```php
use Camelia\Orm\Orm;
$orm = Orm::fromArray([
'host' => '127.0.0.1',
'user' => 'app',
'password' => 'secret',
'database' => 'erp',
]);
// or from CAMELIA_DB_HOST, CAMELIA_DB_USER, CAMELIA_DB_NAME, CAMELIA_DB_PASS
$orm = Orm::fromEnv();
```
## Declare a model
```php
use Camelia\Orm\Attribute\{TableName, PrimaryKey, AutoIncrement, Guarded};
use Camelia\Orm\Model;
#[TableName('usuarios')]
final class Usuario extends Model
{
#[PrimaryKey, AutoIncrement]
public ?int $codigo = null;
public string $nombre = '';
#[Guarded]
public string $passwordHash = '';
}
```
`#[TableName]` and exactly one `#[PrimaryKey]` are mandatory. A model that violates the rules throws
`MetadataException` on first use instead of failing silently later.
## Read
```php
$repo = $orm->repository(Usuario::class);
$repo->find(['activo' => true], [['nombre', 'ASC']], limit: 20);
$repo->findFirst(['correo' => 'a@x']);
$repo->findByPk(5);
$repo->findByPkOrFail(5); // throws RecordNotFoundException
$repo->count(['activo' => true]);
$repo->page(['activo' => true], [], page: 2, perPage: 25);
```
Fluent queries are immutable:
```php
use Camelia\Orm\Query\{Cond, GroupCond};
$repo->query()
->where('activo', true)
->where('fecha', Cond::between('2024-01-01', '2024-12-31'))
->whereGroup(fn (GroupCond $g) => $g->or('correo', Cond::like('%@camelia.dev')))
->orderByDesc('fecha')
->with(['cliente.ciudad'])
->page(page: 1, perPage: 25);
```
## Write
```php
$repo->save($usuario); // INSERT or UPDATE, decided by the primary key
$repo->create(['nombre' => 'Ana']); // new + hydrate + insert
$repo->update($usuario); // always UPDATE, all writable columns
$repo->delete($usuario);
$repo->patch(5, ['nombre' => 'Bea']); // partial update by primary key
$repo->remove(5);
```
`update()` writes the whole row. There is no dirty tracking: use `patch()` for partial updates.
Writing a model hydrated through `select()` throws `PartialModelException`.
## Transactions
```php
$orm->transaction(function (Orm $orm) {
$orm->repository(Usuario::class)->save($usuario);
});
```
Nested calls use savepoints and the original exception is rethrown.
## Errors
Every read and write throws on failure. Silent degradation to `[]` is deliberately absent: it hides
connection failures as empty results. Catch `DatabaseException` (or `DuplicateKeyException`,
`ForeignKeyViolationException`, `LockTimeoutException`) where degradation is genuinely intended.
## Development
The toolchain is [Mago](https://mago.carthage.software) plus PHPUnit and PHPStan.
```bash
composer install
composer fmt # format with Mago
composer fmt:check # CI: formatting must be clean
composer lint # CI: Mago linter
composer analyze # CI: Mago analyzer
composer phpstan # CI: PHPStan level 8
composer test # CI: PHPUnit
composer check # runs the five gates above, in order
composer test:integration # requires CAMELIA_TEST_DSN
```
Configuration:
| File | Purpose |
|---|---|
| `mago.toml` | formatter, linter, analyzer |
| `mago-baseline.toml` | accepted analyzer findings (values coming from PDO) |
| `phpstan.neon` | level 8, `phpVersion: 80300` |
| `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.
## License
MIT. See [LICENSE](LICENSE).
+75
View File
@@ -0,0 +1,75 @@
{
"name": "camelia/orm",
"description": "Lightweight attribute-mapped Active Record ORM for MariaDB/MySQL over PDO.",
"type": "library",
"license": "MIT",
"keywords": ["orm", "activerecord", "pdo", "mysql", "mariadb"],
"authors": [
{
"name": "Dario Garcia",
"email": "dario61081@gmail.com"
}
],
"require": {
"php": ">=8.3",
"ext-mbstring": "*",
"ext-pdo": "*",
"psr/log": "^3.0"
},
"require-dev": {
"carthage-software/mago": "^1.60",
"phpstan/phpstan": "^1.11",
"phpunit/phpunit": "^10.5 || ^11.0"
},
"suggest": {
"brick/math": "Support for BigDecimal-mapped properties"
},
"autoload": {
"psr-4": {
"Camelia\\Orm\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Camelia\\Orm\\Tests\\": "tests/"
}
},
"scripts": {
"test": "phpunit --configuration phpunit.xml.dist",
"test:integration": "phpunit --configuration phpunit.integration.xml.dist",
"fmt": "mago fmt",
"fmt:check": "mago fmt --check",
"lint": "mago lint",
"analyze": "mago analyze",
"phpstan": "php -d memory_limit=1G vendor/bin/phpstan analyse --configuration phpstan.neon --no-progress",
"check": [
"@fmt:check",
"@lint",
"@analyze",
"@phpstan",
"@test"
]
},
"config": {
"sort-packages": true
},
"minimum-stability": "stable",
"prefer-stable": true,
"archive": {
"exclude": [
"/tests",
"/mago-baseline.toml",
"/mago.toml",
"/phpstan.neon",
"/phpunit.integration.xml.dist",
"/phpunit.xml.dist",
"/AGENTS.md",
"/.gitignore"
]
},
"extra": {
"branch-alias": {
"dev-main": "1.0.x-dev"
}
}
}
Generated
+2027
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+361
View File
@@ -0,0 +1,361 @@
variant = "loose"
[[issues]]
file = "src/Connection/ConnectionFactory.php"
code = "possibly-undefined-string-array-index"
message = "Possibly undefined array key 'CAMELIA_DB_HOST' accessed on `array{'CAMELIA_DB_HOST'?: string, 'CAMELIA_DB_NAME'?: string, 'CAMELIA_DB_PASS'?: string, 'CAMELIA_DB_USER'?: string}`."
count = 1
[[issues]]
file = "src/Connection/ConnectionFactory.php"
code = "possibly-undefined-string-array-index"
message = "Possibly undefined array key 'CAMELIA_DB_NAME' accessed on `array{'CAMELIA_DB_HOST'?: string, 'CAMELIA_DB_NAME'?: string, 'CAMELIA_DB_PASS'?: string, 'CAMELIA_DB_USER'?: string}`."
count = 1
[[issues]]
file = "src/Connection/ConnectionFactory.php"
code = "possibly-undefined-string-array-index"
message = "Possibly undefined array key 'CAMELIA_DB_PASS' accessed on `array{'CAMELIA_DB_HOST'?: string, 'CAMELIA_DB_NAME'?: string, 'CAMELIA_DB_PASS'?: string, 'CAMELIA_DB_USER'?: string}`."
count = 1
[[issues]]
file = "src/Connection/ConnectionFactory.php"
code = "possibly-undefined-string-array-index"
message = "Possibly undefined array key 'CAMELIA_DB_USER' accessed on `array{'CAMELIA_DB_HOST'?: string, 'CAMELIA_DB_NAME'?: string, 'CAMELIA_DB_PASS'?: string, 'CAMELIA_DB_USER'?: string}`."
count = 1
[[issues]]
file = "src/Connection/ConnectionFactory.php"
code = "possibly-undefined-string-array-index"
message = "Possibly undefined array key `string('database')` accessed on `array<string, mixed>`."
count = 1
[[issues]]
file = "src/Connection/ConnectionFactory.php"
code = "possibly-undefined-string-array-index"
message = "Possibly undefined array key `string('host')` accessed on `array<string, mixed>`."
count = 1
[[issues]]
file = "src/Connection/ConnectionFactory.php"
code = "possibly-undefined-string-array-index"
message = "Possibly undefined array key `string('user')` accessed on `array<string, mixed>`."
count = 1
[[issues]]
file = "src/Connection/PdoConnection.php"
code = "mixed-assignment"
message = "Assigning `mixed` type to a variable may lead to unexpected behavior."
count = 1
[[issues]]
file = "src/Metadata/MetadataFactory.php"
code = "less-specific-argument"
message = 'Argument type mismatch for argument #2 of `Camelia\Orm\Metadata\MetadataFactory::buildProperty`: expected `ReflectionClass<object>`, but provided type `ReflectionClass<Camelia\Orm\Model>` is less specific.'
count = 1
[[issues]]
file = "src/Metadata/MetadataFactory.php"
code = "redundant-docblock-type"
message = "Redundant docblock type for variable `$attribute`."
count = 4
[[issues]]
file = "src/Metadata/MetadataFactory.php"
code = "redundant-docblock-type"
message = "Redundant docblock type for variable `$table`."
count = 1
[[issues]]
file = "src/Metadata/MetadataFactory.php"
code = "redundant-type-comparison"
message = 'Redundant condition: variable `$class` (type `class-string<Camelia\Orm\Model>`) is already known to be `class-string<Camelia\Orm\Model>`.'
count = 1
[[issues]]
file = "src/Model.php"
code = "mixed-assignment"
message = "Assigning `mixed` type to a variable may lead to unexpected behavior."
count = 2
[[issues]]
file = "src/Model.php"
code = "redundant-cast"
message = "Redundant cast to `(string)`: the expression already has this type."
count = 1
[[issues]]
file = "src/Model.php"
code = "string-member-selector"
message = "This member selector uses a non-literal string type (`string`); its specific value cannot be statically determined."
count = 6
[[issues]]
file = "src/Orm.php"
code = "invalid-property-assignment-value"
message = '''Invalid type for property `$repositories`: expected `array<string, Camelia\Orm\Repository<Camelia\Orm\Model>>`, but got `non-empty-array<class-string<'T.camelia\orm\orm::repository() extends Camelia\Orm\Model>|string, Camelia\Orm\Repository<('T.camelia\orm\orm::repository() extends Camelia\Orm\Model)>|Camelia\Orm\Repository<Camelia\Orm\Model>>`.'''
count = 1
[[issues]]
file = "src/Orm.php"
code = "mixed-assignment"
message = "Assigning `mixed` type to a variable may lead to unexpected behavior."
count = 3
[[issues]]
file = "src/Orm.php"
code = "mixed-assignment"
message = "Assigning `nonnull` type to a variable may lead to unexpected behavior."
count = 1
[[issues]]
file = "src/Orm.php"
code = "non-existent-class-like"
message = 'Cannot find class, interface, enum, or type alias `Psr\Log\LoggerInterface`.'
count = 2
[[issues]]
file = "src/Orm.php"
code = "non-existent-class-like"
message = 'Class, Interface, or Trait `Psr\Log\LoggerInterface` does not exist.'
count = 1
[[issues]]
file = "src/Orm.php"
code = "non-existent-use-import"
message = 'Imported class, interface, trait, or enum `Psr\Log\LoggerInterface` does not exist.'
count = 1
[[issues]]
file = "src/Orm.php"
code = "possibly-invalid-argument"
message = 'Possible argument type mismatch for argument #4 of `Camelia\Orm\Orm::__construct`: expected `null|unknown-ref(Psr\Log\LoggerInterface)`, but possibly received `Psr\Log\LoggerInterface|null`.'
count = 1
[[issues]]
file = "src/Pagination/Page.php"
code = "impossible-condition"
message = "Redundant ternary operator: condition is always falsy."
count = 1
[[issues]]
file = "src/Pagination/Page.php"
code = "redundant-comparison"
message = "Redundant `===` comparison: left-hand side is never identical to right-hand side."
count = 1
[[issues]]
file = "src/Persistence/Persister.php"
code = "mixed-assignment"
message = "Assigning `mixed` type to a variable may lead to unexpected behavior."
count = 2
[[issues]]
file = "src/Persistence/Persister.php"
code = "redundant-cast"
message = "Redundant cast to `(string)`: the expression already has this type."
count = 1
[[issues]]
file = "src/Persistence/Persister.php"
code = "redundant-docblock-type"
message = "Redundant docblock type for variable `$class`."
count = 1
[[issues]]
file = "src/Query/CriteriaCompiler.php"
code = "mixed-assignment"
message = "Assigning `mixed` type to a variable may lead to unexpected behavior."
count = 1
[[issues]]
file = "src/Query/CriteriaCompiler.php"
code = "possibly-null-argument"
message = 'Argument #1 of method `Camelia\Orm\Query\Dialect::quoteIdentifier` is possibly `null`, but parameter type `string` does not accept it.'
count = 1
[[issues]]
file = "src/Query/CriteriaCompiler.php"
code = "possibly-undefined-int-array-index"
message = "Possibly undefined array index accessed on `non-empty-list<string>`."
count = 1
[[issues]]
file = "src/Query/CriteriaCompiler.php"
code = "redundant-cast"
message = "Redundant cast to `(string)`: the expression already has this type."
count = 1
[[issues]]
file = "src/Query/Query.php"
code = "invalid-type-cast"
message = "Casting `mixed` to `float`."
count = 1
[[issues]]
file = "src/Query/Query.php"
code = "mixed-assignment"
message = "Assigning `mixed` type to a variable may lead to unexpected behavior."
count = 4
[[issues]]
file = "src/Query/Query.php"
code = "possibly-undefined-int-array-index"
message = "Possibly undefined array key `int(0)` accessed on `non-empty-array<array-key, array<int|string, mixed>|string|true>`."
count = 1
[[issues]]
file = "src/Query/Query.php"
code = "redundant-cast"
message = "Redundant cast to `(float)`: the expression already has this type."
count = 2
[[issues]]
file = "src/Query/QueryBuilder.php"
code = "mixed-assignment"
message = "Assigning `mixed` type to a variable may lead to unexpected behavior."
count = 2
[[issues]]
file = "src/Query/QueryState.php"
code = "mixed-argument"
message = 'Invalid argument type for argument #2 of `Camelia\Orm\Query\QueryState::__construct`: expected `array<string, mixed>`, but found `nonnull`.'
count = 1
[[issues]]
file = "src/Query/QueryState.php"
code = "mixed-argument"
message = '''Invalid argument type for argument #3 of `Camelia\Orm\Query\QueryState::__construct`: expected `list<array{0: string, 1: string('ASC')|string('DESC')}>`, but found `nonnull`.'''
count = 1
[[issues]]
file = "src/Query/QueryState.php"
code = "mixed-argument"
message = '''Invalid argument type for argument #4 of `Camelia\Orm\Query\QueryState::__construct`: expected `list<array{0: string('AND')|string('OR'), 1: list<array{0: string, 1: mixed}>}>`, but found `nonnull`.'''
count = 1
[[issues]]
file = "src/Query/QueryState.php"
code = "mixed-argument"
message = 'Invalid argument type for argument #5 of `Camelia\Orm\Query\QueryState::__construct`: expected `list<string>|null`, but found `mixed`.'
count = 1
[[issues]]
file = "src/Query/QueryState.php"
code = "mixed-argument"
message = 'Invalid argument type for argument #6 of `Camelia\Orm\Query\QueryState::__construct`: expected `int|null`, but found `mixed`.'
count = 1
[[issues]]
file = "src/Query/QueryState.php"
code = "mixed-argument"
message = 'Invalid argument type for argument #7 of `Camelia\Orm\Query\QueryState::__construct`: expected `int|null`, but found `mixed`.'
count = 1
[[issues]]
file = "src/Query/QueryState.php"
code = "mixed-argument"
message = 'Invalid argument type for argument #8 of `Camelia\Orm\Query\QueryState::__construct`: expected `array<int|string, mixed>|false|true`, but found `mixed`.'
count = 1
[[issues]]
file = "src/Repository.php"
code = "invalid-argument"
message = '''Invalid argument type for argument #1 of `Camelia\Orm\Query\Query::start`: expected `Camelia\Orm\Repository<Camelia\Orm\Model>`, but found `$this(Camelia\Orm\Repository<('T.camelia\orm\repository extends Camelia\Orm\Model)>)`.'''
count = 1
[[issues]]
file = "src/Repository.php"
code = "invalid-return-statement"
message = 'Invalid return type for function `Camelia\Orm\Repository::relationMetadata`: expected `Camelia\Orm\Metadata\PropertyMetadata`, but found `Camelia\Orm\Metadata\PropertyMetadata|null`.'
count = 1
[[issues]]
file = "src/Repository.php"
code = "invalid-type-cast"
message = "Casting `mixed` to `float`."
count = 1
[[issues]]
file = "src/Repository.php"
code = "mixed-assignment"
message = "Assigning `mixed` type to a variable may lead to unexpected behavior."
count = 10
[[issues]]
file = "src/Repository.php"
code = "nullable-return-statement"
message = 'Function `Camelia\Orm\Repository::relationMetadata` is declared to return `Camelia\Orm\Metadata\PropertyMetadata` but possibly returns a nullable value (inferred as `Camelia\Orm\Metadata\PropertyMetadata|null`).'
count = 1
[[issues]]
file = "src/Repository.php"
code = "possibly-null-argument"
message = 'Argument #1 of method `Camelia\Orm\Repository::castDatabaseValue` is possibly `null`, but parameter type `Camelia\Orm\Metadata\PropertyMetadata` does not accept it.'
count = 1
[[issues]]
file = "src/Repository.php"
code = "possibly-null-property-access"
message = "Attempting to access a property on a possibly `null` value."
count = 3
[[issues]]
file = "src/Repository.php"
code = "possibly-undefined-string-array-index"
message = 'Possibly undefined array key `string` accessed on `array<string, Camelia\Orm\Metadata\PropertyMetadata>`.'
count = 5
[[issues]]
file = "src/Repository.php"
code = "redundant-cast"
message = "Redundant cast to `(float)`: the expression already has this type."
count = 2
[[issues]]
file = "src/Repository.php"
code = "redundant-cast"
message = "Redundant cast to `(string)`: the expression already has this type."
count = 4
[[issues]]
file = "src/Repository.php"
code = "unsafe-instantiation"
message = 'Unsafe `new $class_name`: constructor of `Camelia\Orm\Model` is not final and its signature might change in child classes, potentially leading to runtime errors.'
count = 3
[[issues]]
file = "src/Support/TypeCaster.php"
code = "invalid-type-cast"
message = 'Cannot cast object of type `Brick\Math\BigDecimal` to `string` because the class does not exist.'
count = 2
[[issues]]
file = "src/Support/TypeCaster.php"
code = "invalid-type-cast"
message = "Non numeric string of type `string` implicitly cast to `float`."
count = 1
[[issues]]
file = "src/Support/TypeCaster.php"
code = "mixed-assignment"
message = "Assigning `mixed` type to a variable may lead to unexpected behavior."
count = 1
[[issues]]
file = "src/Support/TypeCaster.php"
code = "no-value"
message = 'Argument #3 passed to method `Camelia\Orm\Support\TypeCaster::refusal` has type `never`, meaning it cannot produce a value.'
count = 1
[[issues]]
file = "src/Support/TypeCaster.php"
code = "non-existent-method"
message = 'Method `of` does not exist on type `Brick\Math\BigDecimal`.'
count = 2
[[issues]]
file = "src/Support/TypeCaster.php"
code = "possibly-static-access-on-interface"
message = "Potential static method call on interface `BackedEnum` via `class-string`."
count = 1
+113
View File
@@ -0,0 +1,113 @@
# 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"
[source]
paths = ["src", "tests"]
includes = ["vendor"]
excludes = ["vendor", ".phpunit.cache", ".phpunit.cache.integration", ".mago.cache"]
extensions = ["php"]
[formatter]
print-width = 100
tab-width = 4
use-tabs = false
end-of-line = "lf"
single-quote = true
trailing-comma = true
remove-trailing-close-tag = true
function-brace-style = "next-line"
method-brace-style = "next-line"
classlike-brace-style = "always-next-line"
# Disabled: this option rewrites `(new Foo())->bar()` into `new Foo()->bar()`, which is a PHP parse
# error whenever the result is assigned or returned. Reproduced with mago 1.60.1 on every run, so the
# key is turned off until the formatter is fixed upstream. Keep the parentheses: valid PHP.
first-method-chain-on-new-line = false
[analyzer]
# Tests are excluded from the Mago analyzer: they extend PHPUnit\Framework\TestCase and Mago does
# not load Composer's autoloader for external packages, so every test would report a false
# "non-existent class". PHPStan covers tests with the Composer autoloader available.
excludes = ["tests"]
baseline = "mago-baseline.toml"
find-unused-expressions = true
find-unused-definitions = true
find-unused-parameters = true
strict-list-index-checks = true
strict-array-index-existence = true
check-missing-type-hints = true
check-closure-missing-type-hints = true
check-use-statements = true
check-property-initialization = true
check-dead-catch = true
# Disabled: this library's contract is "every failure throws" (see README), so nearly every method
# can throw DatabaseException, MetadataException or CriteriaException. Annotating @throws on all of
# them would add hundreds of docblocks that restate the design instead of documenting it. Consumers
# rely on the typed exception hierarchy, not on per-method annotations.
check-throws = false
# Metric thresholds are raised on purpose.
#
# Repository is the facade of the library: its method count mirrors the public API contract
# (find*, count, exists, aggregations, page, query, save, create, update, delete, patch, remove and
# eager loading). Splitting it would duplicate the metadata and connection plumbing, which is the
# duplication this design deliberately removes. The same reasoning applies to Query, which mirrors
# the builder surface, and to Model, which holds state plus serialization.
[linter.rules.too-many-methods]
threshold = 40
[linter.rules.too-many-properties]
threshold = 20
[linter.rules.excessive-parameter-list]
threshold = 8
[linter.rules.cyclomatic-complexity]
threshold = 90
method-threshold = 20
[linter.rules.kan-defect]
threshold = 80
# Disabled: the remaining boolean parameters are domain data, not control flow.
#
# Model::assign($data, bool $rejectGuarded) and TypeCaster::cast(..., bool $nullable) pass a fact
# about the column (may it be null, must guarded keys be rejected), not a "do X or do Y" switch.
# Splitting them would duplicate every call site for no readability gain.
[linter.rules.no-boolean-flag-parameter]
enabled = false
# Disabled: this rule would turn every integer, bool and null literal argument into a named
# argument. For PHP standard-library calls such as array_slice($a, 1) or strpos($s, 'x', 0) the
# parameter name adds noise without adding clarity and makes the diff unreadable.
[linter.rules.literal-named-argument]
enabled = false
# Disabled: every isset() here checks key existence in a map whose values are never null (metadata
# properties, cached PDO statements, result rows). isset() is the idiomatic and faster form for
# that exact case.
[linter.rules.no-isset]
enabled = false
# Disabled: asserts in src/Repository.php are narrowing assertions for the type checker
# (assert($relation !== null)), not test assertions. Mago offers no per-path rule scope.
[linter.rules.assert-description]
enabled = false
# Disabled: readability proxies without an actionable change in this codebase.
[linter.rules.inline-variable-return]
enabled = false
[linter.rules.no-multi-assignments]
enabled = false
# Disabled: Halstead volume/difficulty/effort. They flag TypeCaster::toBool (an explicit conversion
# table) and Repository::loadBelongsToMany (a documented three-step pivot load) with no fix that
# would improve either one.
[linter.rules.halstead]
enabled = false
+12
View File
@@ -0,0 +1,12 @@
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
paths:
- src
- tests
excludePaths:
# Intentionally invalid fixtures: they exist to violate metadata rules M1-M7.
- tests/Fixture/Invalid
treatPhpDocTypesAsCertain: false
+17
View File
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
cacheDirectory=".phpunit.cache.integration"
failOnWarning="true"
failOnRisky="true">
<testsuites>
<testsuite name="integration">
<directory>tests/Integration</directory>
</testsuite>
</testsuites>
<php>
<env name="CAMELIA_TEST_DSN" value=""/>
</php>
</phpunit>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
cacheDirectory=".phpunit.cache"
failOnWarning="true"
failOnRisky="true"
failOnEmptyTestSuite="true">
<testsuites>
<testsuite name="unit">
<directory>tests/Unit</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>src</directory>
</include>
</source>
</phpunit>
+11
View File
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* The primary key is assigned by the database on insert (AUTO_INCREMENT).
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class AutoIncrement {}
+20
View File
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* The related row lives in the current table: this model holds the foreign key.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class BelongsTo
{
/**
* @param class-string<\Camelia\Orm\Model> $related
*/
public function __construct(
public string $related,
public string $foreignKey,
) {}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* Many-to-many relation resolved through an explicit pivot table.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class BelongsToMany
{
/**
* @param class-string<\Camelia\Orm\Model> $related
*/
public function __construct(
public string $related,
public string $through,
public string $foreignPivotKey,
public string $relatedPivotKey,
) {}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* Overrides the snake_case column name derived from the property name.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class Column
{
public function __construct(
public string $name,
) {}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* Declares the backed enum a property must hold. Drives casting and validation.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class Enum
{
/** @param class-string<\BackedEnum> $class */
public function __construct(
public string $class,
) {}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* Excludes the property from hydrate() mass assignment. Direct writes still work.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class Guarded {}
+20
View File
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* The related rows live in the related table and point back at this model.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class HasMany
{
/**
* @param class-string<\Camelia\Orm\Model> $related
*/
public function __construct(
public string $related,
public string $foreignKey,
) {}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* The related row lives in the related table and points back at this model with one row.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class HasOne
{
/**
* @param class-string<\Camelia\Orm\Model> $related
*/
public function __construct(
public string $related,
public string $foreignKey,
) {}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* Excludes the property from persistence and from hydrate().
*
* Relationships are excluded by their relation attribute instead, not by this one.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class Ignore {}
+16
View File
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* Secondary index. Consumed by SchemaGenerator only.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class Index
{
public function __construct(
public string $order = 'ASC',
) {}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* Column length. Consumed by SchemaGenerator only.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class Length
{
public function __construct(
public int $value,
) {}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* validate() rejects strings longer than this many bytes.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class MaxLength
{
public function __construct(
public int $value,
) {}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* Forces the column to be nullable when the PHP type cannot express it (e.g. string).
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class Nullable {}
+17
View File
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* Decimal precision and scale. Consumed by SchemaGenerator only.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class Precision
{
public function __construct(
public int $precision,
public int $scale,
) {}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* Marks the single primary key property of a model.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class PrimaryKey {}
+11
View File
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* validate() rejects null and '' for this property.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class Required {}
+16
View File
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* Declares the table a model maps to. Required for every model.
*/
#[\Attribute(\Attribute::TARGET_CLASS)]
final readonly class TableName
{
public function __construct(
public string $name,
) {}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* Single-column unique constraint. Consumed by SchemaGenerator only.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class Unique {}
+16
View File
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Attribute;
/**
* Multi-column unique constraint grouped by name. Consumed by SchemaGenerator only.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final readonly class UniqueGroup
{
public function __construct(
public string $name,
) {}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Connection;
/**
* SQL transport. Implementations must never bind by reference.
*
* @api
*/
interface Connection
{
/**
* Executes a statement and returns the affected row count.
*
* @param list<mixed> $params
*/
public function execute(string $sql, array $params = []): int;
/**
* Executes a statement and returns every row.
*
* @param list<mixed> $params
* @return list<array<string, mixed>>
*/
public function select(string $sql, array $params = []): array;
/**
* Runs one statement and returns the first column of the first row.
*
* @param list<mixed> $params
*/
public function scalar(string $sql, array $params = []): mixed;
public function lastInsertId(): string;
public function begin(): void;
public function commit(): void;
public function rollBack(): void;
public function inTransaction(): bool;
public function driver(): string;
}
+117
View File
@@ -0,0 +1,117 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Connection;
use Camelia\Orm\Exception\ConfigurationException;
use PDO;
/**
* Builds connections from an options array, environment variables or an existing PDO.
*
* @api
*/
final class ConnectionFactory
{
private const REQUIRED_ENVIRONMENT = [
'CAMELIA_DB_HOST',
'CAMELIA_DB_USER',
'CAMELIA_DB_NAME',
'CAMELIA_DB_PASS',
];
/**
* @param array<string, mixed> $options
*/
public static function fromArray(array $options): Connection
{
foreach (['host', 'user', 'database'] as $required) {
if (!isset($options[$required]) || trim((string) $options[$required]) === '') {
throw new ConfigurationException(sprintf(
'Connection option "%s" is required.',
$required,
));
}
}
$charset = isset($options['charset']) ? (string) $options['charset'] : 'utf8mb4';
$port = isset($options['port']) ? (int) $options['port'] : 3306;
$dsn = sprintf(
'mysql:host=%s;port=%d;dbname=%s;charset=%s',
(string) $options['host'],
$port,
(string) $options['database'],
$charset,
);
$pdoOptions = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
if (isset($options['sslCa'])) {
$pdoOptions[PDO::MYSQL_ATTR_SSL_CA] = (string) $options['sslCa'];
}
$pdo = new PDO(
$dsn,
(string) $options['user'],
(string) ($options['password'] ?? ''),
$pdoOptions,
);
return new PdoConnection($pdo);
}
public static function fromEnvironment(): Connection
{
$values = [];
$missing = [];
foreach (self::REQUIRED_ENVIRONMENT as $name) {
$value = self::readEnvironment($name);
if ($value === null) {
$missing[] = $name;
continue;
}
$values[$name] = $value;
}
if ($missing !== []) {
throw ConfigurationException::missingEnvironment($missing);
}
return self::fromArray([
'host' => $values['CAMELIA_DB_HOST'],
'user' => $values['CAMELIA_DB_USER'],
'database' => $values['CAMELIA_DB_NAME'],
'password' => $values['CAMELIA_DB_PASS'],
'port' => self::readEnvironment('CAMELIA_DB_PORT') ?? 3306,
'charset' => self::readEnvironment('CAMELIA_DB_CHARSET') ?? 'utf8mb4',
]);
}
public static function fromPdo(PDO $pdo): Connection
{
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return new PdoConnection($pdo);
}
private static function readEnvironment(string $name): ?string
{
$value = getenv($name);
if ($value === false) {
return null;
}
return $value;
}
}
+213
View File
@@ -0,0 +1,213 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Connection;
use Camelia\Orm\Exception\ConfigurationException;
use Camelia\Orm\Exception\DatabaseException;
use PDO;
use PDOException;
use PDOStatement;
/**
* PDO-backed transport with a bounded LRU statement cache.
*
* Invariant: statements are always executed with execute(array). bindParam is never used,
* because cached statements are shared across calls.
*/
final class PdoConnection implements Connection
{
private const MAX_CACHED_STATEMENTS = 200;
/** @var array<string, PDOStatement> */
private array $statements = [];
/** @var list<string> LRU order, most recent last */
private array $lru = [];
/** @var list<string> savepoint names for nested transactions */
private array $savepoints = [];
public function __construct(
private readonly PDO $pdo,
) {
if ($pdo->getAttribute(PDO::ATTR_ERRMODE) !== PDO::ERRMODE_EXCEPTION) {
throw ConfigurationException::invalidErrorMode();
}
}
public function execute(string $sql, array $params = []): int
{
$statement = $this->prepare($sql);
try {
$statement->execute($params);
} catch (PDOException $exception) {
throw DatabaseException::fromPdoException($exception, 'write', $sql, $params);
}
return $statement->rowCount();
}
public function select(string $sql, array $params = []): array
{
$statement = $this->prepare($sql);
try {
$statement->execute($params);
$rows = $statement->fetchAll();
} catch (PDOException $exception) {
throw DatabaseException::fromPdoException($exception, 'read', $sql, $params);
}
/** @var list<array<string, mixed>> $rows */
return $rows;
}
public function scalar(string $sql, array $params = []): mixed
{
$statement = $this->prepare($sql);
try {
$statement->execute($params);
$value = $statement->fetchColumn();
} catch (PDOException $exception) {
throw DatabaseException::fromPdoException($exception, 'read', $sql, $params);
}
$statement->closeCursor();
return $value === false ? null : $value;
}
public function lastInsertId(): string
{
$id = $this->pdo->lastInsertId();
return $id === false ? '0' : $id;
}
public function begin(): void
{
if ($this->pdo->inTransaction()) {
$name = 'camelia_sp_' . count($this->savepoints);
$this->pdo->exec('SAVEPOINT ' . $name);
$this->savepoints[] = $name;
return;
}
$this->pdo->beginTransaction();
}
public function commit(): void
{
if ($this->savepoints !== []) {
$name = array_pop($this->savepoints);
$this->pdo->exec('RELEASE SAVEPOINT ' . $name);
return;
}
if ($this->pdo->inTransaction()) {
$this->pdo->commit();
}
}
public function rollBack(): void
{
if ($this->savepoints !== []) {
$name = array_pop($this->savepoints);
$this->pdo->exec('ROLLBACK TO SAVEPOINT ' . $name);
return;
}
if ($this->pdo->inTransaction()) {
$this->pdo->rollBack();
}
}
public function inTransaction(): bool
{
return $this->pdo->inTransaction();
}
public function driver(): string
{
return (string) $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
}
/**
* Raw PDO handle for cases the library does not cover.
*/
public function pdo(): PDO
{
return $this->pdo;
}
/**
* Clears the statement cache. Tests only.
*/
public function clearStatementCache(): void
{
$this->statements = [];
$this->lru = [];
}
public function statementCacheSize(): int
{
return count($this->statements);
}
private function prepare(string $sql): PDOStatement
{
$key = md5($sql);
$cached = $this->statements[$key] ?? null;
if ($cached instanceof PDOStatement) {
$this->touch($key);
return $cached;
}
$statement = $this->pdo->prepare($sql);
if (!$statement instanceof PDOStatement) {
throw new DatabaseException(sprintf('Unable to prepare statement: %s', $sql), $sql);
}
$this->statements[$key] = $statement;
$this->lru[] = $key;
$this->evict();
return $statement;
}
private function touch(string $key): void
{
$position = array_search($key, $this->lru, true);
if ($position !== false) {
unset($this->lru[$position]);
$this->lru = array_values($this->lru);
}
$this->lru[] = $key;
}
private function evict(): void
{
while (count($this->statements) > self::MAX_CACHED_STATEMENTS) {
$oldest = array_shift($this->lru);
if ($oldest === null) {
break;
}
unset($this->statements[$oldest]);
}
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* Invalid configuration or environment.
*/
final class ConfigurationException extends OrmException
{
/** @param list<string> $missing */
public static function missingEnvironment(array $missing): self
{
return new self(sprintf('Missing required environment variable(s): %s.', implode(
', ',
$missing,
)));
}
public static function invalidErrorMode(): self
{
return new self(
'The supplied PDO instance must use ERRMODE_EXCEPTION; silent modes are '
. 'incompatible with the library error contract.',
);
}
public static function unknownConnectionOption(string $option): self
{
return new self(sprintf('Unknown connection option "%s".', $option));
}
public static function relationDepthExceeded(int $max): self
{
return new self(sprintf(
'Eager loading is limited to %d nesting levels to avoid accidental cartesian products.',
$max,
));
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* A criteria key is not a declared property or column, or uses an invalid operator.
*/
final class CriteriaException extends OrmException
{
/** @param list<string> $valid */
public static function unknownColumn(string $model, string $key, array $valid): self
{
return new self(sprintf(
'Unknown column "%s" in criteria for "%s". Valid columns: %s.',
$key,
$model,
$valid === [] ? '(none)' : implode(', ', $valid),
));
}
public static function emptyIn(): self
{
return new self(
'Cond::in() requires at least one value; use an empty criterion list instead.',
);
}
public static function invalidOrderDirection(string $direction): self
{
return new self(sprintf('Order direction must be ASC or DESC, got "%s".', $direction));
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
use PDOException;
/**
* Wraps a PDO failure and preserves the SQL and parameters that produced it.
*/
class DatabaseException extends OrmException
{
/**
* @param list<mixed> $params
*/
public function __construct(
string $message,
private readonly string $sql = '',
private readonly array $params = [],
private readonly string $context = '',
?\Throwable $previous = null,
) {
parent::__construct($message, 0, $previous);
}
/**
* Maps a PDOException to the narrowest exception type the SQLSTATE allows.
*
* @param list<mixed> $params
*/
public static function fromPdoException(
PDOException $exception,
string $context,
string $sql = '',
array $params = [],
): self {
$sqlState = (string) $exception->getCode();
$driverCode = (int) ($exception->errorInfo[1] ?? 0);
$message = sprintf('Database error during %s: %s', $context, $exception->getMessage());
if ($sqlState === '23000' && in_array($driverCode, [1062, 1555, 1586], true)) {
return new DuplicateKeyException($message, $sql, $params, $context, $exception);
}
if ($sqlState === '23000' && in_array($driverCode, [1451, 1452], true)) {
return new ForeignKeyViolationException($message, $sql, $params, $context, $exception);
}
if ($sqlState === 'HY000' && in_array($driverCode, [1205, 1213], true)) {
return new LockTimeoutException($message, $sql, $params, $context, $exception);
}
return new self($message, $sql, $params, $context, $exception);
}
public function sql(): string
{
return $this->sql;
}
/** @return list<mixed> */
public function params(): array
{
return $this->params;
}
public function context(): string
{
return $this->context;
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* A unique or primary key constraint was violated.
*/
final class DuplicateKeyException extends DatabaseException {}
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* A foreign key constraint was violated.
*/
final class ForeignKeyViolationException extends DatabaseException {}
+10
View File
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* A lock wait timeout or deadlock aborted the statement.
*/
final class LockTimeoutException extends DatabaseException {}
+110
View File
@@ -0,0 +1,110 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* The model class is not declared according to the metadata rules (M1-M7).
*/
final class MetadataException extends OrmException
{
public static function notAModel(string $class): self
{
return new self(sprintf('[M1] "%s" must extend %s.', $class, \Camelia\Orm\Model::class));
}
public static function missingTableName(string $class): self
{
return new self(sprintf('[M2] "%s" must declare a non-empty #[TableName].', $class));
}
public static function primaryKeyCount(string $class, int $found): self
{
return new self(sprintf(
'[M3] "%s" must declare exactly one #[PrimaryKey]; found %d.',
$class,
$found,
));
}
public static function notPublic(string $class, string $property): self
{
return new self(sprintf('[M4] "%s::$%s" must be public to be mapped.', $class, $property));
}
public static function missingType(string $class, string $property): self
{
return new self(sprintf('[M4] "%s::$%s" must declare a type.', $class, $property));
}
public static function nonAsciiColumn(string $class, string $property, string $column): self
{
return new self(sprintf(
'Column "%s" of "%s::$%s" must be ASCII.',
$column,
$class,
$property,
));
}
public static function invalidRelationProperty(string $class, string $property): self
{
return new self(sprintf(
'[M5] Relationship "%s::$%s" must be nullable (?Model) or an array.',
$class,
$property,
));
}
public static function unknownRelatedClass(
string $class,
string $property,
string $related,
): self {
return new self(sprintf(
'Relationship "%s::$%s" points to unknown class "%s".',
$class,
$property,
$related,
));
}
public static function missingForeignKey(
string $class,
string $property,
string $foreignKey,
): self {
return new self(sprintf(
'Relationship "%s::$%s" declares unknown foreign key property "%s".',
$class,
$property,
$foreignKey,
));
}
public static function duplicateColumn(
string $class,
string $column,
string $first,
string $second,
): self {
return new self(sprintf(
'[M7] "%s" maps properties "%s" and "%s" to the same column "%s".',
$class,
$first,
$second,
$column,
));
}
public static function unknownRelation(string $class, string $property): self
{
return new self(sprintf('"%s::$%s" is not a declared relationship.', $class, $property));
}
public static function unknownProperty(string $class, string $property): self
{
return new self(sprintf('"%s::$%s" is not a mapped property.', $class, $property));
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* Base type of every exception raised by the library.
*/
class OrmException extends \RuntimeException {}
+21
View File
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* A partial model (hydrated through select()) was handed to a write operation.
*/
final class PartialModelException extends OrmException
{
public static function onWrite(string $class, string $operation): self
{
return new self(sprintf(
'Cannot %s a partial "%s": it was hydrated with select() and not all columns are loaded. '
. 'Use patch() for partial updates.',
$operation,
$class,
));
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* A required record could not be found.
*/
final class RecordNotFoundException extends OrmException
{
public static function byPrimaryKey(string $class, int|string $pk): self
{
return new self(sprintf('No "%s" found with primary key "%s".', $class, (string) $pk));
}
public static function first(string $class): self
{
return new self(sprintf('No "%s" matched the given criteria.', $class));
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* Model validation failed. Carries every error grouped by property.
*/
final class ValidationException extends OrmException
{
/** @param array<string, list<string>> $errors */
public function __construct(
private readonly array $errors,
private readonly string $model,
) {
$flattened = [];
foreach ($errors as $property => $messages) {
foreach ($messages as $message) {
$flattened[] = $property . ': ' . $message;
}
}
parent::__construct(sprintf(
'Validation failed for "%s": %s',
$model,
implode('; ', $flattened),
));
}
/** @return array<string, list<string>> */
public function errors(): array
{
return $this->errors;
}
public function model(): string
{
return $this->model;
}
}
+151
View File
@@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Metadata;
/**
* Immutable description of a model class.
*
* Every lookup is cached at construction: metadata is read once per class and process.
*/
final class ClassMetadata
{
/** @var array<string, PropertyMetadata> keyed by property name */
private array $properties;
/** @var array<string, string> column => property */
private array $propertyByColumn = [];
/** @var list<string> */
private array $writable;
/**
* @param class-string<\Camelia\Orm\Model> $class
* @param array<string, PropertyMetadata> $properties
*/
public function __construct(
public readonly string $class,
private readonly string $table,
private readonly string $primaryKey,
private readonly string $primaryKeyColumn,
array $properties,
) {
$this->properties = $properties;
$writable = [];
foreach ($properties as $property) {
$this->propertyByColumn[$property->column] = $property->name;
if ($property->isWritable()) {
$writable[] = $property->name;
}
}
$this->writable = $writable;
}
public function table(): string
{
return $this->table;
}
public function primaryKey(): string
{
return $this->primaryKey;
}
public function primaryKeyColumn(): string
{
return $this->primaryKeyColumn;
}
/** @return array<string, PropertyMetadata> */
public function properties(): array
{
return $this->properties;
}
/**
* @throws \Camelia\Orm\Exception\MetadataException when the property is not mapped
*/
public function column(string $property): string
{
return $this->propertyMetadata($property)->column;
}
public function property(string $column): ?string
{
return $this->propertyByColumn[$column] ?? null;
}
public function hasProperty(string $property): bool
{
return isset($this->properties[$property]);
}
public function hasColumn(string $column): bool
{
return isset($this->propertyByColumn[$column]);
}
public function propertyMetadata(string $property): PropertyMetadata
{
$metadata = $this->properties[$property] ?? null;
if ($metadata === null) {
throw \Camelia\Orm\Exception\MetadataException::unknownProperty(
$this->class,
$property,
);
}
return $metadata;
}
/** @return list<PropertyMetadata> */
public function relations(): array
{
return array_values(array_filter(
$this->properties,
static fn(PropertyMetadata $p): bool => $p->relation !== null,
));
}
/** @return list<PropertyMetadata> */
public function indexed(): array
{
return array_values(array_filter(
$this->properties,
static fn(PropertyMetadata $p): bool => $p->indexed,
));
}
/** @return list<string> */
public function writable(): array
{
return $this->writable;
}
/**
* Resolves a criteria key to a property name, accepting either form.
*/
public function resolveProperty(string $key): ?string
{
if (isset($this->properties[$key])) {
return $key;
}
return $this->propertyByColumn[$key] ?? null;
}
/** @return list<string> */
public function knownKeys(): array
{
return array_values(array_unique(array_merge(
array_keys($this->properties),
array_keys($this->propertyByColumn),
)));
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Metadata;
/**
* Declarative constraints of one mapped property.
*
* @internal
*/
final readonly class Constraint
{
public function __construct(
public bool $nullable = false,
public bool $ignored = false,
public bool $guarded = false,
public bool $primaryKey = false,
public bool $autoIncrement = false,
public bool $required = false,
public bool $indexed = false,
public ?int $maxLength = null,
) {}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Metadata;
/**
* Memoizes ClassMetadata per class for the lifetime of the process.
*
* Metadata never changes once built; clear() exists for tests only.
*/
final class MetadataCache
{
/** @var array<string, ClassMetadata> */
private array $byName = [];
public function __construct(
private readonly MetadataFactory $factory,
) {}
/**
* @param class-string<\Camelia\Orm\Model> $class
*/
public function forClass(string $class): ClassMetadata
{
return $this->byName[$class] ??= $this->factory->forClass($class);
}
public function clear(): void
{
$this->byName = [];
}
}
+286
View File
@@ -0,0 +1,286 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Metadata;
use Camelia\Orm\Attribute\AutoIncrement;
use Camelia\Orm\Attribute\BelongsTo;
use Camelia\Orm\Attribute\BelongsToMany;
use Camelia\Orm\Attribute\Column;
use Camelia\Orm\Attribute\Enum;
use Camelia\Orm\Attribute\Guarded;
use Camelia\Orm\Attribute\HasMany;
use Camelia\Orm\Attribute\HasOne;
use Camelia\Orm\Attribute\Ignore;
use Camelia\Orm\Attribute\Index;
use Camelia\Orm\Attribute\MaxLength;
use Camelia\Orm\Attribute\Nullable;
use Camelia\Orm\Attribute\PrimaryKey;
use Camelia\Orm\Attribute\Required;
use Camelia\Orm\Attribute\TableName;
use Camelia\Orm\Exception\MetadataException;
use Camelia\Orm\Model;
use Camelia\Orm\Support\NameConverter;
use ReflectionClass;
use ReflectionNamedType;
use ReflectionProperty;
/**
* Builds ClassMetadata from a model class through reflection.
*
* @internal
*/
final class MetadataFactory
{
/**
* @param class-string<\Camelia\Orm\Model> $class
*/
public function forClass(string $class): ClassMetadata
{
if (!class_exists($class) || !is_subclass_of($class, Model::class)) {
throw MetadataException::notAModel($class);
}
$reflection = new ReflectionClass($class);
$tableName = $reflection->getAttributes(TableName::class)[0] ?? null;
if ($tableName === null) {
throw MetadataException::missingTableName($class);
}
/** @var TableName $table */
$table = $tableName->newInstance();
if (trim($table->name) === '') {
throw MetadataException::missingTableName($class);
}
$properties = [];
$primaryKeys = [];
$columnOwners = [];
foreach ($reflection->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
if ($property->isStatic()) {
continue;
}
$declaring = $property->getDeclaringClass()->getName();
if ($declaring !== $class && $declaring === Model::class) {
continue;
}
$metadata = $this->buildProperty($class, $reflection, $property);
if (isset($columnOwners[$metadata->column])) {
throw MetadataException::duplicateColumn(
$class,
$metadata->column,
$columnOwners[$metadata->column],
$metadata->name,
);
}
$columnOwners[$metadata->column] = $metadata->name;
$properties[$metadata->name] = $metadata;
if ($metadata->primaryKey) {
$primaryKeys[] = $metadata->name;
}
}
if (count($primaryKeys) !== 1) {
throw MetadataException::primaryKeyCount($class, count($primaryKeys));
}
$primaryKey = $primaryKeys[0];
$primaryKeyProperty = $properties[$primaryKey] ?? null;
if ($primaryKeyProperty === null) {
throw MetadataException::unknownProperty($class, $primaryKey);
}
return new ClassMetadata(
$class,
$table->name,
$primaryKey,
$primaryKeyProperty->column,
$properties,
);
}
/**
* @param class-string<\Camelia\Orm\Model> $class
* @param ReflectionClass<object> $reflection
*/
private function buildProperty(
string $class,
ReflectionClass $reflection,
ReflectionProperty $property,
): PropertyMetadata {
$name = $property->getName();
$type = $property->getType();
if (!$type instanceof ReflectionNamedType) {
throw MetadataException::missingType($class, $name);
}
$relation = $this->buildRelation($class, $reflection, $property);
$columnAttribute = $property->getAttributes(Column::class)[0] ?? null;
$column = $columnAttribute !== null
? $columnAttribute->newInstance()->name
: NameConverter::camelToSnake($name);
if (preg_match('/[^\x20-\x7E]/', $column) === 1) {
throw MetadataException::nonAsciiColumn($class, $name, $column);
}
$enumAttribute = $property->getAttributes(Enum::class)[0] ?? null;
$enumClass = $enumAttribute !== null ? $enumAttribute->newInstance()->class : null;
if ($relation !== null) {
$this->assertRelationShape($class, $property, $relation);
}
$maxLength = $property->getAttributes(MaxLength::class)[0] ?? null;
return new PropertyMetadata(
name: $name,
column: $column,
type: $enumClass ?? $type->getName(),
enumClass: $enumClass,
relation: $relation,
declaringClass: $class,
constraint: new Constraint(
nullable: $type->allowsNull() || $property->getAttributes(Nullable::class) !== [],
ignored: $property->getAttributes(Ignore::class) !== [] || $relation !== null,
guarded: $property->getAttributes(Guarded::class) !== [],
primaryKey: $property->getAttributes(PrimaryKey::class) !== [],
autoIncrement: $property->getAttributes(AutoIncrement::class) !== [],
required: $property->getAttributes(Required::class) !== [],
indexed: $property->getAttributes(Index::class) !== [],
maxLength: $maxLength !== null ? $maxLength->newInstance()->value : null,
),
);
}
/**
* @param class-string<\Camelia\Orm\Model> $class
* @param ReflectionClass<object> $reflection
*/
private function buildRelation(
string $class,
ReflectionClass $reflection,
ReflectionProperty $property,
): ?RelationMetadata {
$name = $property->getName();
$belongsTo = $property->getAttributes(BelongsTo::class)[0] ?? null;
if ($belongsTo !== null) {
/** @var BelongsTo $attribute */
$attribute = $belongsTo->newInstance();
return new RelationMetadata(
RelationMetadata::KIND_BELONGS_TO,
$this->resolveRelatedClass($class, $reflection, $attribute->related, $name),
$attribute->foreignKey,
);
}
$hasOne = $property->getAttributes(HasOne::class)[0] ?? null;
if ($hasOne !== null) {
/** @var HasOne $attribute */
$attribute = $hasOne->newInstance();
return new RelationMetadata(
RelationMetadata::KIND_HAS_ONE,
$this->resolveRelatedClass($class, $reflection, $attribute->related, $name),
$attribute->foreignKey,
);
}
$hasMany = $property->getAttributes(HasMany::class)[0] ?? null;
if ($hasMany !== null) {
/** @var HasMany $attribute */
$attribute = $hasMany->newInstance();
return new RelationMetadata(
RelationMetadata::KIND_HAS_MANY,
$this->resolveRelatedClass($class, $reflection, $attribute->related, $name),
$attribute->foreignKey,
);
}
$belongsToMany = $property->getAttributes(BelongsToMany::class)[0] ?? null;
if ($belongsToMany !== null) {
/** @var BelongsToMany $attribute */
$attribute = $belongsToMany->newInstance();
return new RelationMetadata(
RelationMetadata::KIND_BELONGS_TO_MANY,
$this->resolveRelatedClass($class, $reflection, $attribute->related, $name),
'',
$attribute->through,
$attribute->foreignPivotKey,
$attribute->relatedPivotKey,
);
}
return null;
}
/**
* @param class-string<\Camelia\Orm\Model> $class
* @param ReflectionClass<object> $reflection
* @return class-string<\Camelia\Orm\Model>
*/
private function resolveRelatedClass(
string $class,
ReflectionClass $reflection,
string $related,
string $property,
): string {
if (class_exists($related) && is_subclass_of($related, Model::class)) {
return $related;
}
$namespace = $reflection->getNamespaceName();
$candidate = $namespace === '' ? $related : $namespace . '\\' . $related;
if (class_exists($candidate) && is_subclass_of($candidate, Model::class)) {
return $candidate;
}
throw MetadataException::unknownRelatedClass($class, $property, $related);
}
private function assertRelationShape(
string $class,
ReflectionProperty $property,
RelationMetadata $relation,
): void {
$name = $property->getName();
$type = $property->getType();
if (!$type instanceof ReflectionNamedType) {
throw MetadataException::invalidRelationProperty($class, $name);
}
$isArray = $type->getName() === 'array';
if ($relation->isToMany() && !$isArray) {
throw MetadataException::invalidRelationProperty($class, $name);
}
if (!$relation->isToMany() && (!$type->allowsNull() || $isArray)) {
throw MetadataException::invalidRelationProperty($class, $name);
}
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Metadata;
/**
* Immutable description of one mapped property.
*
* The boolean flags are grouped into Constraint in the constructor signature to keep the
* parameter list readable; they are re-exposed here as flat, named properties because every
* consumer reads them individually.
*/
final readonly class PropertyMetadata
{
public bool $nullable;
public bool $ignored;
public bool $guarded;
public bool $primaryKey;
public bool $autoIncrement;
public bool $required;
public bool $indexed;
public ?int $maxLength;
/**
* @param class-string<\Camelia\Orm\Model> $declaringClass
* @param class-string<\BackedEnum>|null $enumClass
*/
public function __construct(
public string $name,
public string $column,
public string $type,
public ?string $enumClass,
public ?RelationMetadata $relation,
public string $declaringClass,
Constraint $constraint,
) {
$this->nullable = $constraint->nullable;
$this->ignored = $constraint->ignored;
$this->guarded = $constraint->guarded;
$this->primaryKey = $constraint->primaryKey;
$this->autoIncrement = $constraint->autoIncrement;
$this->required = $constraint->required;
$this->indexed = $constraint->indexed;
$this->maxLength = $constraint->maxLength;
}
/**
* True when the property participates in INSERT/UPDATE.
*/
public function isWritable(): bool
{
return !$this->ignored && !$this->primaryKey && $this->relation === null;
}
public function isRelation(): bool
{
return $this->relation !== null;
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Metadata;
/**
* Immutable description of a declared relationship.
*/
final readonly class RelationMetadata
{
public const KIND_BELONGS_TO = 'belongsTo';
public const KIND_HAS_ONE = 'hasOne';
public const KIND_HAS_MANY = 'hasMany';
public const KIND_BELONGS_TO_MANY = 'belongsToMany';
/**
* @param class-string<\Camelia\Orm\Model> $relatedClass
*/
public function __construct(
public string $kind,
public string $relatedClass,
public string $foreignKey,
public ?string $through = null,
public ?string $foreignPivotKey = null,
public ?string $relatedPivotKey = null,
) {}
public function isToMany(): bool
{
return $this->kind === self::KIND_HAS_MANY || $this->kind === self::KIND_BELONGS_TO_MANY;
}
}
+380
View File
@@ -0,0 +1,380 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm;
use Camelia\Orm\Exception\ValidationException;
use Camelia\Orm\Metadata\ClassMetadata;
use Camelia\Orm\Metadata\MetadataCache;
use Camelia\Orm\Metadata\MetadataFactory;
use Camelia\Orm\Metadata\PropertyMetadata;
use Camelia\Orm\Persistence\Validator;
use Camelia\Orm\Support\TypeCaster;
use DateTimeImmutable;
use ReflectionClass;
use ReflectionNamedType;
use ReflectionProperty;
/**
* State holder for one row.
*
* A model never talks to the database: reading and writing go through Repository.
*
* @api
*/
abstract class Model
{
private static ?MetadataCache $metadata = null;
private bool $partial = false;
public function __construct()
{
$this->initializeProperties();
}
/**
* Resolves (and memoizes) the metadata of one model class.
*
* @param class-string<\Camelia\Orm\Model> $class
*/
public static function metadataFor(string $class): ClassMetadata
{
self::$metadata ??= new MetadataCache(new MetadataFactory());
return self::$metadata->forClass($class);
}
/**
* Clears the shared metadata cache. Tests only.
*/
public static function clearMetadataCache(): void
{
self::$metadata = null;
}
public static function metadata(): ClassMetadata
{
/** @var class-string<\Camelia\Orm\Model> $class */
$class = static::class;
return self::metadataFor($class);
}
/**
* Mass-assigns values keyed by property or column name.
*
* Properties win when both forms are present. Unknown keys are ignored so HTTP payloads
* can be passed through. Guarded properties are skipped.
*
* @param array<string, mixed> $data
* @throws \InvalidArgumentException when a value cannot be cast to its declared type
*/
public function hydrate(array $data): static
{
$this->assign($data, false);
return $this;
}
/**
* Same as hydrate(), but a guarded property in the payload is an error instead of being skipped.
*
* @param array<string, mixed> $data
* @throws \InvalidArgumentException when a value cannot be cast or a guarded property is present
*/
public function hydrateStrict(array $data): static
{
$this->assign($data, true);
return $this;
}
/**
* @param array<string, mixed> $data
*/
private function assign(array $data, bool $rejectGuarded = false): void
{
$metadata = static::metadata();
$resolved = [];
foreach ($data as $key => $value) {
$key = (string) $key;
$property = $metadata->resolveProperty($key);
if ($property === null) {
continue;
}
$definition = $metadata->propertyMetadata($property);
if ($definition->ignored || $definition->primaryKey) {
continue;
}
if ($definition->guarded && $rejectGuarded) {
throw new \InvalidArgumentException(sprintf(
'Property "%s" is guarded and cannot be mass-assigned.',
$property,
));
}
// The property name wins over the column alias when both are present.
$isPropertyName = $key === $property;
if (isset($resolved[$property])) {
$alreadyFromProperty = $resolved[$property]['isProperty'];
if ($alreadyFromProperty || !$isPropertyName) {
continue;
}
}
$resolved[$property] = [
'value' => $value,
'definition' => $definition,
'isProperty' => $isPropertyName,
];
}
foreach ($resolved as $property => $entry) {
$definition = $entry['definition'];
if ($definition->guarded) {
continue;
}
$this->{$property} = $this->castFor($definition, $entry['value']);
}
}
/**
* Serializes writable columns plus loaded relationships.
*
* @param list<string>|null $only property names to include
* @return array<string, mixed>
*/
public function toArray(?array $only = null): array
{
$metadata = static::metadata();
$result = [];
foreach ($metadata->writable() as $property) {
if ($only !== null && !in_array($property, $only, true)) {
continue;
}
$definition = $metadata->propertyMetadata($property);
$result[$definition->column] = TypeCaster::toSerializable($this->{$property});
}
foreach ($metadata->relations() as $relation) {
if ($only !== null && !in_array($relation->name, $only, true)) {
continue;
}
$result[$relation->name] = $this->serializeRelation($relation);
}
return $result;
}
public function toJson(int $flags = 0): string
{
return (string) json_encode(
$this->toArray(),
$flags | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
);
}
/**
* @return array<string, list<string>> property => messages
*/
public function validate(): array
{
return (new Validator())->validate($this);
}
public function isValid(): bool
{
return $this->validate() === [];
}
public function isPartial(): bool
{
return $this->partial;
}
/**
* Marks the instance as hydrated from a column subset. Persister refuses to write it.
*/
public function markPartial(bool $partial = true): void
{
$this->partial = $partial;
}
/**
* Copies this model without its primary key, ready to be saved as a new row.
*/
public function replicate(): static
{
$copy = clone $this;
$metadata = static::metadata();
$primaryKey = $metadata->primaryKey();
$definition = $metadata->propertyMetadata($primaryKey);
$copy->{$primaryKey} = match (true) {
$definition->nullable => null,
$definition->type === 'string' => '',
$definition->type === 'float' => 0.0,
$definition->type === 'bool' => false,
default => 0,
};
return $copy;
}
/**
* Reads the declared value of a property without dynamic property access surprises.
*/
public function get(string $property): mixed
{
return $this->{$property};
}
public function set(string $property, mixed $value): static
{
$this->{$property} = $value;
return $this;
}
/**
* Hook invoked by Persister immediately before an INSERT.
*/
protected function beforeInsert(): void {}
/**
* Hook invoked by Persister immediately before an UPDATE.
*/
protected function beforeUpdate(): void {}
/**
* @internal used by Persister
*/
public function runBeforeInsert(): void
{
$this->beforeInsert();
}
/**
* @internal used by Persister
*/
public function runBeforeUpdate(): void
{
$this->beforeUpdate();
}
/**
* Asserts the model is valid and throws with every error grouped by property.
*
* @internal used by Persister
*/
public function assertValid(): void
{
$errors = $this->validate();
if ($errors !== []) {
/** @var class-string<\Camelia\Orm\Model> $class */
$class = static::class;
throw new ValidationException($errors, $class);
}
}
/**
* @internal used by Persister
*/
public function castFor(PropertyMetadata $definition, mixed $value): mixed
{
$context = $definition->declaringClass . '::$' . $definition->name;
if ($definition->enumClass !== null) {
return TypeCaster::castEnum(
$value,
$definition->enumClass,
$definition->nullable,
$context,
);
}
return TypeCaster::cast($value, $definition->type, $definition->nullable, $context);
}
private function initializeProperties(): void
{
$reflection = new ReflectionClass($this);
foreach ($reflection->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
if ($property->isStatic() || $property->isInitialized($this)) {
continue;
}
$type = $property->getType();
if (!$type instanceof ReflectionNamedType) {
continue;
}
$property->setValue($this, self::neutralValue($type));
}
}
private static function neutralValue(ReflectionNamedType $type): mixed
{
if ($type->allowsNull()) {
return null;
}
return match ($type->getName()) {
'string' => '',
'int' => 0,
'float' => 0.0,
'bool' => false,
'array' => [],
DateTimeImmutable::class => new DateTimeImmutable('now'),
default => null,
};
}
private function serializeRelation(PropertyMetadata $relation): mixed
{
/** @var mixed $value */
$value = $this->{$relation->name};
if ($value === null) {
return null;
}
if (is_array($value)) {
$serialized = [];
foreach ($value as $related) {
if (!$related instanceof Model) {
continue;
}
$serialized[] = $related->toArray();
}
return $serialized;
}
if ($value instanceof Model) {
return $value->toArray();
}
return null;
}
}
+153
View File
@@ -0,0 +1,153 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm;
use Camelia\Orm\Connection\Connection;
use Camelia\Orm\Connection\ConnectionFactory;
use Camelia\Orm\Persistence\AuditListener;
use Camelia\Orm\Persistence\Persister;
use Camelia\Orm\Query\Dialect;
use Camelia\Orm\Query\MySqlDialect;
use Camelia\Orm\Query\QueryBuilder;
use Camelia\Orm\Support\Clock;
use Camelia\Orm\Support\SystemClock;
use PDO;
use Psr\Log\LoggerInterface;
/**
* Library entry point. Immutable and safe to pass through constructors.
*
* @api
*/
final class Orm
{
private ?Persister $persister = null;
/** @var array<string, Repository<Model>> */
private array $repositories = [];
public function __construct(
private readonly Connection $connection,
private readonly Dialect $dialect = new MySqlDialect(),
private readonly ?AuditListener $auditListener = null,
private readonly ?LoggerInterface $logger = null,
private readonly Clock $clock = new SystemClock(),
private readonly int $slowQueryMs = 500,
) {}
/**
* @param array<string, mixed> $options
*/
public static function fromArray(array $options): self
{
return self::fromConnection(ConnectionFactory::fromArray($options), $options);
}
public static function fromPdo(PDO $pdo): self
{
return self::fromConnection(ConnectionFactory::fromPdo($pdo));
}
public static function fromEnv(): self
{
return self::fromConnection(ConnectionFactory::fromEnvironment());
}
/**
* @param array<string, mixed> $options
*/
public static function fromConnection(Connection $connection, array $options = []): self
{
$audit = $options['auditListener'] ?? null;
$logger = $options['logger'] ?? null;
$clock = $options['clock'] ?? null;
$slowQueryMs = $options['slowQueryMs'] ?? 500;
return new self(
$connection,
new MySqlDialect(),
$audit instanceof AuditListener ? $audit : null,
$logger instanceof LoggerInterface ? $logger : null,
$clock instanceof Clock ? $clock : new SystemClock(),
is_int($slowQueryMs) ? $slowQueryMs : 500,
);
}
/**
* @template T of Model
* @param class-string<T> $class
* @return Repository<T>
*/
public function repository(string $class): Repository
{
/** @var Repository<T> $repository */
$repository =
$this->repositories[$class] ??= new Repository(
$this->connection,
$class,
$this->dialect,
$this->persister(),
);
return $repository;
}
/**
* Runs the callback inside a transaction, nesting through savepoints.
*
* @template TReturn
* @param callable(self): TReturn $callback
* @return TReturn
*/
public function transaction(callable $callback): mixed
{
$this->connection->begin();
try {
$result = $callback($this);
$this->connection->commit();
return $result;
} catch (\Throwable $exception) {
$this->connection->rollBack();
throw $exception;
}
}
public function connection(): Connection
{
return $this->connection;
}
public function dialect(): Dialect
{
return $this->dialect;
}
public function clock(): Clock
{
return $this->clock;
}
public function logger(): ?LoggerInterface
{
return $this->logger;
}
public function slowQueryMs(): int
{
return $this->slowQueryMs;
}
private function persister(): Persister
{
return $this->persister ??= new Persister(
$this->connection,
new QueryBuilder($this->dialect),
$this->auditListener,
);
}
}
+92
View File
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Pagination;
use Camelia\Orm\Model;
/**
* Immutable paginated result.
*
* @api
*/
final readonly class Page
{
public const MIN_PER_PAGE = 1;
public const MAX_PER_PAGE = 1000;
/**
* @param list<Model> $items
*/
public function __construct(
public array $items,
public int $page,
public int $perPage,
public int $total,
public int $totalPages,
) {}
/**
* Builds a page with boundary-tolerant pagination inputs.
*
* @param list<Model> $items
*/
public static function of(array $items, int $page, int $perPage, int $total): self
{
$safePage = max(1, $page);
$safePerPage = max(self::MIN_PER_PAGE, min(self::MAX_PER_PAGE, $perPage));
$safeTotal = max(0, $total);
$totalPages = $safePerPage === 0 ? 0 : (int) ceil($safeTotal / $safePerPage);
return new self($items, $safePage, $safePerPage, $safeTotal, $totalPages);
}
public function hasNext(): bool
{
return $this->page < $this->totalPages;
}
public function hasPrev(): bool
{
return $this->page > 1;
}
/**
* @return array{
* items: list<array<string, mixed>>,
* page: int,
* per_page: int,
* total: int,
* total_pages: int,
* has_next: bool,
* has_prev: bool
* }
*/
public function toArray(): array
{
$items = [];
foreach ($this->items as $item) {
$items[] = $item->toArray();
}
return [
'items' => $items,
'page' => $this->page,
'per_page' => $this->perPage,
'total' => $this->total,
'total_pages' => $this->totalPages,
'has_next' => $this->hasNext(),
'has_prev' => $this->hasPrev(),
];
}
public function toJson(int $flags = 0): string
{
return (string) json_encode(
$this->toArray(),
$flags | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
);
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Persistence;
/**
* Receives a notification after a successful write.
*
* The library ships no implementation: the consumer decides where the audit trail lives.
*
* @api
*/
interface AuditListener
{
/**
* @param array<string, mixed>|null $before null on insert
* @param array<string, mixed> $after
*/
public function onWrite(
string $table,
int|string $pk,
string $action,
?array $before,
array $after,
): void;
}
+312
View File
@@ -0,0 +1,312 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Persistence;
use Camelia\Orm\Connection\Connection;
use Camelia\Orm\Exception\CriteriaException;
use Camelia\Orm\Exception\PartialModelException;
use Camelia\Orm\Model;
use Camelia\Orm\Query\QueryBuilder;
use Camelia\Orm\Support\TypeCaster;
use DateTimeInterface;
/**
* Executes INSERT, UPDATE and DELETE for one model.
*
* Every write validates first and then maps property values to database values.
*
* @internal
*/
final class Persister
{
public function __construct(
private readonly Connection $connection,
private readonly QueryBuilder $builder,
private readonly ?AuditListener $audit = null,
) {}
/**
* @return int|string primary key of the saved row
*/
public function save(Model $model): int|string
{
$metadata = $model::metadata();
/** @var mixed $pk */
$pk = $model->get($metadata->primaryKey());
if ($pk === null || $pk === 0 || $pk === '0' || $pk === '') {
return $this->insert($model);
}
$this->update($model);
return is_int($pk) || is_string($pk) ? $pk : (string) $pk;
}
/**
* @return int|string
*/
public function insert(Model $model): int|string
{
$this->assertNotPartial($model, 'insert');
$metadata = $model::metadata();
$model->assertValid();
$model->runBeforeInsert();
$values = $this->collectWritableValues($model);
if ($values === []) {
throw new CriteriaException(sprintf(
'Model "%s" has no writable column to insert.',
$metadata->class,
));
}
$compiled = $this->builder->insert($metadata, $values);
$this->connection->execute($compiled['sql'], $compiled['params']);
$primaryKeyProperty = $metadata->primaryKey();
$primaryKeyMetadata = $metadata->propertyMetadata($primaryKeyProperty);
if ($primaryKeyMetadata->autoIncrement) {
$identifier = $this->connection->lastInsertId();
$model->set($primaryKeyProperty, TypeCaster::cast(
$identifier,
$primaryKeyMetadata->type,
false,
$metadata->class . '::$' . $primaryKeyProperty,
));
}
/** @var mixed $pk */
$pk = $model->get($primaryKeyProperty);
$normalized = is_int($pk) || is_string($pk) ? $pk : (string) $pk;
$this->notify(
$metadata->table(),
$normalized,
'insert',
null,
$this->auditSnapshot($model),
);
return $normalized;
}
public function update(Model $model): void
{
$this->assertNotPartial($model, 'update');
$metadata = $model::metadata();
$model->assertValid();
$model->runBeforeUpdate();
$primaryKeyProperty = $metadata->primaryKey();
/** @var mixed $pk */
$pk = $model->get($primaryKeyProperty);
if ($pk === null || $pk === 0 || $pk === '0' || $pk === '') {
throw new CriteriaException(sprintf(
'Cannot update "%s" without a primary key value.',
$metadata->class,
));
}
$before = $this->existingRow($model, $pk);
$values = $this->collectWritableValues($model);
$compiled = $this->builder->update($metadata, $values, $pk);
$this->connection->execute($compiled['sql'], $compiled['params']);
$this->notify(
$metadata->table(),
is_int($pk) || is_string($pk) ? $pk : (string) $pk,
'update',
$before,
$this->auditSnapshot($model),
);
}
public function delete(Model $model): void
{
$metadata = $model::metadata();
$primaryKeyProperty = $metadata->primaryKey();
/** @var mixed $pk */
$pk = $model->get($primaryKeyProperty);
if ($pk === null || $pk === 0 || $pk === '0' || $pk === '') {
throw new CriteriaException(sprintf(
'Cannot delete "%s" without a primary key value.',
$metadata->class,
));
}
$before = $this->existingRow($model, $pk);
$compiled = $this->builder->delete($metadata, $pk);
$this->connection->execute($compiled['sql'], $compiled['params']);
$this->notify(
$metadata->table(),
is_int($pk) || is_string($pk) ? $pk : (string) $pk,
'delete',
$before,
[],
);
}
/**
* Partial update by primary key: only the supplied properties are written.
*
* @param array<string, mixed> $values keyed by property or column
*/
public function patch(Model $model, int|string $pk, array $values): void
{
$metadata = $model::metadata();
$writable = [];
foreach ($values as $key => $value) {
$key = (string) $key;
$property = $metadata->resolveProperty($key);
if ($property === null) {
throw CriteriaException::unknownColumn(
$metadata->class,
$key,
$metadata->knownKeys(),
);
}
$definition = $metadata->propertyMetadata($property);
if (!$definition->isWritable()) {
continue;
}
$writable[$property] = TypeCaster::toDatabaseValue($model->castFor(
$definition,
$value,
));
}
if ($writable === []) {
throw new CriteriaException(sprintf(
'patch() received no writable column for "%s".',
$metadata->class,
));
}
$compiled = $this->builder->update($metadata, $writable, $pk);
$this->connection->execute($compiled['sql'], $compiled['params']);
}
public function remove(Model $model, int|string $pk): bool
{
$metadata = $model::metadata();
$compiled = $this->builder->delete($metadata, $pk);
return $this->connection->execute($compiled['sql'], $compiled['params']) > 0;
}
/**
* @return array<string, mixed> keyed by PROPERTY
*/
public function collectWritableValues(Model $model): array
{
$metadata = $model::metadata();
$values = [];
foreach ($metadata->writable() as $property) {
/** @var mixed $value */
$value = $model->get($property);
$values[$property] = TypeCaster::toDatabaseValue($value);
}
return $values;
}
/**
* @param mixed $pk
* @return array<string, mixed>|null
*/
private function existingRow(Model $model, mixed $pk): ?array
{
if ($this->audit === null) {
return null;
}
$metadata = $model::metadata();
$columns = [];
foreach ($metadata->properties() as $property) {
if ($property->isRelation()) {
continue;
}
$columns[] = $property->column;
}
$sql =
'SELECT '
. implode(', ', array_map(
static fn(string $column): string => '`' . $column . '`',
$columns,
))
. ' FROM `'
. $metadata->table()
. '` WHERE `'
. $metadata->primaryKeyColumn()
. '` = ? LIMIT 1';
$rows = $this->connection->select($sql, [$pk]);
return $rows[0] ?? null;
}
/**
* @return array<string, mixed>
*/
private function auditSnapshot(Model $model): array
{
$snapshot = [];
foreach ($model->toArray() as $key => $value) {
if ($value instanceof DateTimeInterface) {
$snapshot[$key] = $value->format(DATE_ATOM);
continue;
}
if (is_scalar($value) || $value === null) {
$snapshot[$key] = $value;
}
}
return $snapshot;
}
/**
* @param array<string, mixed>|null $before
* @param array<string, mixed> $after
*/
private function notify(
string $table,
int|string $pk,
string $action,
?array $before,
array $after,
): void {
$this->audit?->onWrite($table, $pk, $action, $before, $after);
}
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);
}
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Persistence;
use Camelia\Orm\Model;
/**
* Applies the runtime validation rules declared through attributes.
*
* @internal
*/
final class Validator
{
/**
* @return array<string, list<string>> property => messages, empty when valid
*/
public function validate(Model $model): array
{
$metadata = $model::metadata();
$errors = [];
foreach ($metadata->properties() as $property) {
if ($property->ignored) {
continue;
}
/** @var mixed $value */
$value = $model->get($property->name);
if ($property->required && ($value === null || $value === '')) {
$errors[$property->name][] = sprintf('El campo %s es requerido', $property->name);
}
if (
$property->enumClass !== null
&& $value !== null
&& !$value instanceof $property->enumClass
) {
$errors[$property->name][] = sprintf(
'El valor de %s no es válido',
$property->name,
);
}
if (
$property->maxLength !== null
&& $value !== null
&& is_string($value)
&& mb_strlen($value) > $property->maxLength
) {
$errors[$property->name][] = sprintf(
'El campo %s supera %d caracteres',
$property->name,
$property->maxLength,
);
}
}
return $errors;
}
}
+122
View File
@@ -0,0 +1,122 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Query;
/**
* Immutable SQL operator applied to one column.
*
* Instances are built through the static factories; no global helper functions exist.
*/
final readonly class Cond
{
public const OP_EQ = 'eq';
public const OP_NEQ = 'neq';
public const OP_GT = 'gt';
public const OP_GTE = 'gte';
public const OP_LT = 'lt';
public const OP_LTE = 'lte';
public const OP_IN = 'in';
public const OP_NOT_IN = 'notIn';
public const OP_BETWEEN = 'between';
public const OP_NOT_BETWEEN = 'notBetween';
public const OP_LIKE = 'like';
public const OP_NOT_LIKE = 'notLike';
public const OP_IS_NULL = 'isNull';
public const OP_IS_NOT_NULL = 'isNotNull';
public const OP_RAW = 'raw';
/**
* @param list<mixed> $values
*/
private function __construct(
public string $operator,
public array $values,
public string $rawSql = '',
) {}
public static function eq(mixed $value): self
{
return new self(self::OP_EQ, [$value]);
}
public static function neq(mixed $value): self
{
return new self(self::OP_NEQ, [$value]);
}
public static function gt(mixed $value): self
{
return new self(self::OP_GT, [$value]);
}
public static function gte(mixed $value): self
{
return new self(self::OP_GTE, [$value]);
}
public static function lt(mixed $value): self
{
return new self(self::OP_LT, [$value]);
}
public static function lte(mixed $value): self
{
return new self(self::OP_LTE, [$value]);
}
/** @param list<mixed> $values */
public static function in(array $values): self
{
return new self(self::OP_IN, array_values($values));
}
/** @param list<mixed> $values */
public static function notIn(array $values): self
{
return new self(self::OP_NOT_IN, array_values($values));
}
public static function between(mixed $from, mixed $to): self
{
return new self(self::OP_BETWEEN, [$from, $to]);
}
public static function notBetween(mixed $from, mixed $to): self
{
return new self(self::OP_NOT_BETWEEN, [$from, $to]);
}
public static function like(string $value): self
{
return new self(self::OP_LIKE, [$value]);
}
public static function notLike(string $value): self
{
return new self(self::OP_NOT_LIKE, [$value]);
}
public static function isNull(): self
{
return new self(self::OP_IS_NULL, []);
}
public static function isNotNull(): self
{
return new self(self::OP_IS_NOT_NULL, []);
}
/**
* Escape hatch: the SQL fragment and its parameters are emitted verbatim.
*
* The column identifier is not validated here; callers own the safety of $sql.
*
* @param list<mixed> $params
*/
public static function raw(string $sql, array $params = []): self
{
return new self(self::OP_RAW, array_values($params), $sql);
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Query;
use Camelia\Orm\Exception\CriteriaException;
use Camelia\Orm\Metadata\ClassMetadata;
/**
* Turns a criteria map into a WHERE fragment plus bound parameters.
*
* Every read path goes through here: find, findFirst, count, page and Query.
*
* @internal
*/
final class CriteriaCompiler
{
public function __construct(
private readonly Dialect $dialect,
) {}
/**
* @param array<string, mixed|Cond> $criteria
* @return array{0: string, 1: list<mixed>} empty SQL when there is nothing to filter
*/
public function compile(ClassMetadata $metadata, array $criteria): array
{
$clauses = [];
$params = [];
foreach ($criteria as $key => $value) {
$key = (string) $key;
$property = $metadata->resolveProperty($key);
if ($property === null) {
throw CriteriaException::unknownColumn(
$metadata->class,
$key,
$metadata->knownKeys(),
);
}
$column = $metadata->propertyMetadata($property)->column;
$quotedColumn = $this->quoteColumn($column);
[$sql, $bound] = $this->compileValue($quotedColumn, $value);
$clauses[] = $sql;
$params = array_merge($params, $bound);
}
if ($clauses === []) {
return ['', []];
}
return [implode(' AND ', $clauses), $params];
}
/**
* @return array{0: string, 1: list<mixed>}
*/
private function compileValue(string $quotedColumn, mixed $value): array
{
if ($value instanceof Cond) {
if ($value->operator === Cond::OP_IN && $value->values === []) {
throw CriteriaException::emptyIn();
}
return $this->dialect->renderCondition($quotedColumn, $value);
}
if ($value === null) {
return [$quotedColumn . ' IS NULL', []];
}
if (is_array($value)) {
if ($value === []) {
return ['1 = 0', []];
}
return $this->dialect->renderCondition($quotedColumn, Cond::in(array_values($value)));
}
return [$quotedColumn . ' = ?', [$value]];
}
/**
* Quotes a column, honoring a table-qualified name such as "table.column".
*/
private function quoteColumn(string $column): string
{
if (!str_contains($column, '.')) {
return $this->dialect->quoteIdentifier($column);
}
[$table, $rest] = explode('.', $column, 2);
return (
$this->dialect->quoteIdentifier($table) . '.' . $this->dialect->quoteIdentifier($rest)
);
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Query;
/**
* Translates abstract query parts into engine-specific SQL.
*/
interface Dialect
{
public function quoteIdentifier(string $identifier): string;
/**
* Renders one operator applied to an already quoted column.
*
* @return array{0: string, 1: list<mixed>}
*/
public function renderCondition(string $quotedColumn, Cond $cond): array;
/** @param list<mixed> $values */
public function placeholders(array $values): string;
public function limitClause(?int $limit, ?int $offset): string;
}
+44
View File
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Query;
/**
* Mutable accumulator used only inside Query::whereGroup().
*
* This is the single mutable entry point of the API, and it never escapes the closure.
*/
final class GroupCond
{
/** @var list<array{0: string, 1: mixed|Cond, 2: 'AND'|'OR'}> */
private array $parts = [];
public function and(string $column, mixed $value): self
{
$this->parts[] = [$column, $value, 'AND'];
return $this;
}
public function or(string $column, mixed $value): self
{
$this->parts[] = [$column, $value, 'OR'];
return $this;
}
/**
* @internal
* @return list<array{0: string, 1: mixed|Cond, 2: 'AND'|'OR'}>
*/
public function parts(): array
{
return $this->parts;
}
public function isEmpty(): bool
{
return $this->parts === [];
}
}
+96
View File
@@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Query;
use Camelia\Orm\Exception\CriteriaException;
/**
* MariaDB / MySQL renderer. The only Dialect implementation shipped.
*/
final class MySqlDialect implements Dialect
{
public function quoteIdentifier(string $identifier): string
{
return '`' . str_replace('`', '``', $identifier) . '`';
}
public function renderCondition(string $quotedColumn, Cond $cond): array
{
return match ($cond->operator) {
Cond::OP_EQ => [$quotedColumn . ' = ?', $cond->values],
Cond::OP_NEQ => [$quotedColumn . ' <> ?', $cond->values],
Cond::OP_GT => [$quotedColumn . ' > ?', $cond->values],
Cond::OP_GTE => [$quotedColumn . ' >= ?', $cond->values],
Cond::OP_LT => [$quotedColumn . ' < ?', $cond->values],
Cond::OP_LTE => [$quotedColumn . ' <= ?', $cond->values],
Cond::OP_LIKE => [$quotedColumn . ' LIKE ?', $cond->values],
Cond::OP_NOT_LIKE => [$quotedColumn . ' NOT LIKE ?', $cond->values],
Cond::OP_IN => $this->renderIn($quotedColumn, $cond->values),
Cond::OP_NOT_IN => $this->renderNotIn($quotedColumn, $cond->values),
Cond::OP_BETWEEN => [$quotedColumn . ' BETWEEN ? AND ?', $cond->values],
Cond::OP_NOT_BETWEEN => [$quotedColumn . ' NOT BETWEEN ? AND ?', $cond->values],
Cond::OP_IS_NULL => [$quotedColumn . ' IS NULL', []],
Cond::OP_IS_NOT_NULL => [$quotedColumn . ' IS NOT NULL', []],
Cond::OP_RAW => ['(' . $cond->rawSql . ')', $cond->values],
default => throw new CriteriaException(sprintf(
'Unsupported operator "%s".',
$cond->operator,
)),
};
}
public function placeholders(array $values): string
{
return implode(', ', array_fill(0, count($values), '?'));
}
public function limitClause(?int $limit, ?int $offset): string
{
if ($limit === null && $offset === null) {
return '';
}
if ($limit === null) {
// MySQL requires a LIMIT when OFFSET is present; use the documented max row count.
return ' LIMIT 18446744073709551615 OFFSET ' . max(0, (int) $offset);
}
$clause = ' LIMIT ' . max(0, $limit);
if ($offset !== null) {
$clause .= ' OFFSET ' . max(0, $offset);
}
return $clause;
}
/**
* @param list<mixed> $values
* @return array{0: string, 1: list<mixed>}
*/
private function renderIn(string $quotedColumn, array $values): array
{
if ($values === []) {
// An empty IN set matches nothing; emit a deterministic always-false predicate.
return ['1 = 0', []];
}
return [$quotedColumn . ' IN (' . $this->placeholders($values) . ')', $values];
}
/**
* @param list<mixed> $values
* @return array{0: string, 1: list<mixed>}
*/
private function renderNotIn(string $quotedColumn, array $values): array
{
if ($values === []) {
// NOT IN over an empty set matches every row.
return ['1 = 1', []];
}
return [$quotedColumn . ' NOT IN (' . $this->placeholders($values) . ')', $values];
}
}
+403
View File
@@ -0,0 +1,403 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Query;
use Camelia\Orm\Connection\Connection;
use Camelia\Orm\Exception\CriteriaException;
use Camelia\Orm\Exception\RecordNotFoundException;
use Camelia\Orm\Model;
use Camelia\Orm\Pagination\Page;
use Camelia\Orm\Repository;
use Camelia\Orm\Support\TypeCaster;
/**
* Immutable fluent query. Every builder method returns a copy.
*
* @api
*/
final class Query
{
/**
* @param Repository<Model> $repository
*/
private function __construct(
private readonly Repository $repository,
private readonly Connection $connection,
private readonly QueryBuilder $builder,
private readonly QueryState $state,
) {}
/**
* @param Repository<Model> $repository
*/
public static function start(
Repository $repository,
QueryState $state,
Connection $connection,
QueryBuilder $builder,
): self {
return new self($repository, $connection, $builder, $state);
}
public function where(string $column, mixed $value): self
{
$criteria = $this->state->criteria;
$criteria[$column] = $value;
return $this->withState($this->state->withCriteria($criteria));
}
/**
* @param list<mixed> $values
*/
public function whereIn(string $column, array $values): self
{
return $this->where($column, Cond::in($values));
}
/**
* @param list<mixed> $values
*/
public function whereNotIn(string $column, array $values): self
{
return $this->where($column, Cond::notIn($values));
}
public function whereNull(string $column): self
{
return $this->where($column, Cond::isNull());
}
public function whereNotNull(string $column): self
{
return $this->where($column, Cond::isNotNull());
}
/**
* Adds a parenthesized group of OR conditions, combined with $boolean.
*
* @param callable(GroupCond): mixed $callback
*/
public function whereGroup(callable $callback, string $boolean = 'AND'): self
{
$group = new GroupCond();
$callback($group);
if ($group->isEmpty()) {
return $this;
}
$parts = [];
foreach ($group->parts() as [$column, $value, $_]) {
$parts[] = [$column, $value];
}
$groups = $this->state->groups;
$groups[] = [strtoupper($boolean) === 'OR' ? 'OR' : 'AND', $parts];
return $this->withState($this->state->withGroups($groups));
}
public function orderBy(string $column, string $direction = 'ASC'): self
{
$order = $this->state->order;
$order[] = [$column, strtoupper($direction) === 'DESC' ? 'DESC' : 'ASC'];
return $this->withState($this->state->withOrder($order));
}
public function orderByDesc(string $column): self
{
return $this->orderBy($column, 'DESC');
}
public function limit(int $limit): self
{
return $this->withState($this->state->withLimit($limit));
}
public function offset(int $offset): self
{
return $this->withState($this->state->withOffset($offset));
}
public function select(string ...$columns): self
{
return $this->withState($this->state->withColumns(array_values($columns)));
}
/**
* @param true|string|array<int|string, mixed> ...$relations
*/
public function with(bool|string|array ...$relations): self
{
if ($relations === []) {
return $this;
}
if ($relations[0] === true) {
return $this->withState($this->state->withRelations(true));
}
$normalized = [];
foreach ($relations as $relation) {
if (!is_array($relation)) {
$normalized[] = (string) $relation;
continue;
}
foreach ($relation as $key => $value) {
if (is_int($key)) {
$normalized[] = (string) $value;
continue;
}
$normalized[$key] = $value;
}
}
return $this->withState($this->state->withRelations($normalized));
}
/**
* @return list<Model>
*/
public function get(): array
{
return $this->runSelect();
}
public function first(): ?Model
{
$rows = $this->withState($this->state->withLimit(1))->runSelect();
return $rows[0] ?? null;
}
public function firstOrFail(): Model
{
$model = $this->first();
if ($model === null) {
throw RecordNotFoundException::first($this->state->metadata->class);
}
return $model;
}
public function count(): int
{
$compiled = $this->builder->count($this->state->metadata, []);
$sql = $compiled['sql'];
$params = [];
[$where, $whereParams] = $this->compileWhere();
if ($where !== '') {
$sql .= ' WHERE ' . $where;
$params = $whereParams;
}
return (int) $this->connection->scalar($sql, $params);
}
public function exists(): bool
{
return $this->count() > 0;
}
public function sum(string $column): float
{
return (float) ($this->aggregate($column, 'SUM') ?? 0.0);
}
public function avg(string $column): float
{
return (float) ($this->aggregate($column, 'AVG') ?? 0.0);
}
public function max(string $column): ?float
{
return $this->aggregate($column, 'MAX');
}
public function min(string $column): ?float
{
return $this->aggregate($column, 'MIN');
}
/**
* @return list<mixed>
*/
public function pluck(string $column): array
{
$metadata = $this->state->metadata;
$property = $metadata->resolveProperty($column);
if ($property === null) {
throw CriteriaException::unknownColumn(
$metadata->class,
$column,
$metadata->knownKeys(),
);
}
$models = $this->withState($this->state->withColumns([$property]))->runSelect();
$values = [];
foreach ($models as $model) {
$values[] = TypeCaster::toSerializable($model->get($property));
}
return $values;
}
public function page(int $page = 1, int $perPage = 20): Page
{
$total = $this->count();
$safePage = max(1, $page);
$safePerPage = max(Page::MIN_PER_PAGE, min(Page::MAX_PER_PAGE, $perPage));
$items = $this->withState(
$this->state->withLimit($safePerPage)->withOffset(($safePage - 1) * $safePerPage),
)->runSelect();
return Page::of($items, $safePage, $safePerPage, $total);
}
/**
* @return array{sql: string, params: list<mixed>}
*/
public function toSql(): array
{
return $this->compileSelect();
}
private function withState(QueryState $state): self
{
return new self($this->repository, $this->connection, $this->builder, $state);
}
/**
* @return array{sql: string, params: list<mixed>}
*/
private function compileSelect(): array
{
$compiled = $this->builder->select(
$this->state->metadata,
[],
$this->state->order,
$this->state->limit,
$this->state->offset,
$this->state->columns,
);
[$where, $whereParams] = $this->compileWhere();
if ($where === '') {
return $compiled;
}
return [
'sql' => $this->injectWhere($compiled['sql'], $where),
'params' => array_merge($whereParams, $compiled['params']),
];
}
/**
* Inserts a WHERE clause before ORDER BY / LIMIT, which is where SQL requires it.
*/
private function injectWhere(string $sql, string $where): string
{
$positions = [];
foreach ([' ORDER BY', ' LIMIT'] as $clause) {
$position = strpos($sql, $clause);
if ($position !== false) {
$positions[] = $position;
}
}
$insertAt = $positions === [] ? strlen($sql) : min($positions);
return substr($sql, 0, $insertAt) . ' WHERE ' . $where . substr($sql, $insertAt);
}
/**
* @return array{0: string, 1: list<mixed>}
*/
private function compileWhere(): array
{
$compiler = new CriteriaCompiler(new MySqlDialect());
[$baseSql, $params] = $compiler->compile($this->state->metadata, $this->state->criteria);
$sqlParts = $baseSql === '' ? [] : ['(' . $baseSql . ')'];
foreach ($this->state->groups as [$boolean, $parts]) {
$rendered = [];
foreach ($parts as [$column, $value]) {
[$sql, $bound] = $compiler->compile($this->state->metadata, [$column => $value]);
if ($sql === '') {
continue;
}
if ($rendered !== []) {
$rendered[] = 'OR';
}
$rendered[] = $sql;
$params = array_merge($params, $bound);
}
if ($rendered === []) {
continue;
}
if ($sqlParts !== []) {
$sqlParts[] = $boolean;
}
$sqlParts[] = '(' . implode(' ', $rendered) . ')';
}
return [$sqlParts === [] ? '' : implode(' ', $sqlParts), $params];
}
private function aggregate(string $column, string $function): ?float
{
$compiled = $this->builder->aggregate($this->state->metadata, $column, $function, []);
$sql = $compiled['sql'];
$params = [];
[$where, $whereParams] = $this->compileWhere();
if ($where !== '') {
$sql .= ' WHERE ' . $where;
$params = $whereParams;
}
$value = $this->connection->scalar($sql, $params);
return $value === null ? null : (float) $value;
}
/**
* @return list<Model>
*/
private function runSelect(): array
{
$compiled = $this->compileSelect();
$rows = $this->connection->select($compiled['sql'], $compiled['params']);
return $this->repository->hydrateRows($rows, $this->state->columns, $this->state->with);
}
}
+260
View File
@@ -0,0 +1,260 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Query;
use Camelia\Orm\Exception\CriteriaException;
use Camelia\Orm\Metadata\ClassMetadata;
/**
* Compiles SQL statements for one model. Produces strings and parameter lists only.
*
* @internal
*/
final class QueryBuilder
{
public function __construct(
private readonly Dialect $dialect,
) {}
/**
* @param array<string, mixed|Cond> $criteria
* @param list<array{0: string, 1: 'ASC'|'DESC'}> $order
* @param list<string>|null $columns properties to select
* @return array{sql: string, params: list<mixed>}
*/
public function select(
ClassMetadata $metadata,
array $criteria,
array $order = [],
?int $limit = null,
?int $offset = null,
?array $columns = null,
): array {
$table = $this->dialect->quoteIdentifier($metadata->table());
$list = $this->compileSelectList($metadata, $columns);
[$where, $params] = (new CriteriaCompiler($this->dialect))->compile($metadata, $criteria);
$sql = 'SELECT ' . $list . ' FROM ' . $table;
if ($where !== '') {
$sql .= ' WHERE ' . $where;
}
$sql .= $this->compileOrder($metadata, $order, $table);
$sql .= $this->dialect->limitClause($limit, $offset);
return ['sql' => $sql, 'params' => $params];
}
/**
* @param array<string, mixed|Cond> $criteria
* @return array{sql: string, params: list<mixed>}
*/
public function count(ClassMetadata $metadata, array $criteria): array
{
$table = $this->dialect->quoteIdentifier($metadata->table());
[$where, $params] = (new CriteriaCompiler($this->dialect))->compile($metadata, $criteria);
$sql = 'SELECT COUNT(*) AS aggregate FROM ' . $table;
if ($where !== '') {
$sql .= ' WHERE ' . $where;
}
return ['sql' => $sql, 'params' => $params];
}
/**
* @param array<string, mixed|Cond> $criteria
* @return array{sql: string, params: list<mixed>}
*/
public function aggregate(
ClassMetadata $metadata,
string $column,
string $function,
array $criteria,
): array {
$property = $metadata->resolveProperty($column);
if ($property === null) {
throw CriteriaException::unknownColumn(
$metadata->class,
$column,
$metadata->knownKeys(),
);
}
$quoted = $this->dialect->quoteIdentifier($metadata->propertyMetadata($property)->column);
$table = $this->dialect->quoteIdentifier($metadata->table());
[$where, $params] = (new CriteriaCompiler($this->dialect))->compile($metadata, $criteria);
$sql = 'SELECT ' . $function . '(' . $quoted . ') AS aggregate FROM ' . $table;
if ($where !== '') {
$sql .= ' WHERE ' . $where;
}
return ['sql' => $sql, 'params' => $params];
}
/**
* @param array<string, mixed> $values keyed by PROPERTY
* @return array{sql: string, params: list<mixed>}
*/
public function insert(ClassMetadata $metadata, array $values): array
{
$columns = [];
$placeholders = [];
$params = [];
foreach ($values as $property => $value) {
$columns[] = $this->dialect->quoteIdentifier($metadata->column($property));
$placeholders[] = '?';
$params[] = $value;
}
if ($columns === []) {
throw new CriteriaException('Refusing to build an INSERT without columns.');
}
$sql =
'INSERT INTO '
. $this->dialect->quoteIdentifier($metadata->table())
. ' ('
. implode(', ', $columns)
. ') VALUES ('
. implode(', ', $placeholders)
. ')';
return ['sql' => $sql, 'params' => $params];
}
/**
* @param array<string, mixed> $values keyed by PROPERTY
* @return array{sql: string, params: list<mixed>}
*/
public function update(ClassMetadata $metadata, array $values, mixed $primaryKey): array
{
$assignments = [];
$params = [];
foreach ($values as $property => $value) {
$assignments[] = $this->dialect->quoteIdentifier($metadata->column($property)) . ' = ?';
$params[] = $value;
}
if ($assignments === []) {
throw new CriteriaException('Refusing to build an UPDATE without columns.');
}
$params[] = $primaryKey;
$sql =
'UPDATE '
. $this->dialect->quoteIdentifier($metadata->table())
. ' SET '
. implode(', ', $assignments)
. ' WHERE '
. $this->dialect->quoteIdentifier($metadata->primaryKeyColumn())
. ' = ?';
return ['sql' => $sql, 'params' => $params];
}
/**
* @return array{sql: string, params: list<mixed>}
*/
public function delete(ClassMetadata $metadata, mixed $primaryKey): array
{
$sql =
'DELETE FROM '
. $this->dialect->quoteIdentifier($metadata->table())
. ' WHERE '
. $this->dialect->quoteIdentifier($metadata->primaryKeyColumn())
. ' = ?';
return ['sql' => $sql, 'params' => [$primaryKey]];
}
/**
* @param list<string>|null $columns
*/
private function compileSelectList(ClassMetadata $metadata, ?array $columns): string
{
if ($columns === null || $columns === []) {
$parts = [];
foreach ($metadata->properties() as $property) {
if ($property->isRelation()) {
continue;
}
$parts[] = $this->dialect->quoteIdentifier($property->column);
}
return implode(', ', $parts);
}
$parts = [];
foreach ($columns as $column) {
$property = $metadata->resolveProperty($column);
if ($property === null) {
throw CriteriaException::unknownColumn(
$metadata->class,
$column,
$metadata->knownKeys(),
);
}
$parts[] = $this->dialect->quoteIdentifier($metadata->propertyMetadata(
$property,
)->column);
}
return implode(', ', $parts);
}
/**
* @param list<array{0: string, 1: 'ASC'|'DESC'}> $order
*/
private function compileOrder(ClassMetadata $metadata, array $order, string $table): string
{
if ($order === []) {
return '';
}
$parts = [];
foreach ($order as [$column, $direction]) {
$property = $metadata->resolveProperty($column);
if ($property === null) {
continue;
}
$normalized = strtoupper($direction);
if ($normalized !== 'ASC' && $normalized !== 'DESC') {
throw CriteriaException::invalidOrderDirection($direction);
}
$parts[] =
$table
. '.'
. $this->dialect->quoteIdentifier($metadata->propertyMetadata($property)->column)
. ' '
. $normalized;
}
if ($parts === []) {
return '';
}
return ' ORDER BY ' . implode(', ', $parts);
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Query;
use Camelia\Orm\Metadata\ClassMetadata;
/**
* Immutable snapshot of every builder clause accumulated by Query.
*
* Each builder method on Query returns a copy of this value with one clause replaced, which is
* what makes Query immutable without duplicating ten constructor arguments.
*
* @internal
*/
final readonly class QueryState
{
/**
* @param array<string, mixed|Cond> $criteria
* @param list<array{0: string, 1: 'ASC'|'DESC'}> $order
* @param list<array{0: 'AND'|'OR', 1: list<array{0: string, 1: mixed|Cond}>}> $groups
* @param list<string>|null $columns
* @param true|array<int|string, mixed>|false $with
*/
public function __construct(
public ClassMetadata $metadata,
public array $criteria = [],
public array $order = [],
public array $groups = [],
public ?array $columns = null,
public ?int $limit = null,
public ?int $offset = null,
public bool|array $with = false,
) {}
/**
* @param array<string, mixed|Cond> $criteria
*/
public function withCriteria(array $criteria): self
{
return $this->with(['criteria' => $criteria]);
}
/**
* @param list<array{0: string, 1: 'ASC'|'DESC'}> $order
*/
public function withOrder(array $order): self
{
return $this->with(['order' => $order]);
}
/**
* @param list<array{0: 'AND'|'OR', 1: list<array{0: string, 1: mixed|Cond}>}> $groups
*/
public function withGroups(array $groups): self
{
return $this->with(['groups' => $groups]);
}
/**
* @param list<string> $columns
*/
public function withColumns(array $columns): self
{
return $this->with(['columns' => $columns]);
}
public function withLimit(?int $limit): self
{
return $this->with(['limit' => $limit]);
}
public function withOffset(?int $offset): self
{
return $this->with(['offset' => $offset]);
}
/**
* @param true|array<int|string, mixed> $with
*/
public function withRelations(bool|array $with): self
{
return $this->with(['with' => $with]);
}
/**
* @param array<string, mixed> $changes
*/
private function with(array $changes): self
{
return new self(
$this->metadata,
$changes['criteria'] ?? $this->criteria,
$changes['order'] ?? $this->order,
$changes['groups'] ?? $this->groups,
array_key_exists('columns', $changes) ? $changes['columns'] : $this->columns,
array_key_exists('limit', $changes) ? $changes['limit'] : $this->limit,
array_key_exists('offset', $changes) ? $changes['offset'] : $this->offset,
array_key_exists('with', $changes) ? $changes['with'] : $this->with,
);
}
}
+783
View File
@@ -0,0 +1,783 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm;
use Camelia\Orm\Connection\Connection;
use Camelia\Orm\Exception\ConfigurationException;
use Camelia\Orm\Exception\MetadataException;
use Camelia\Orm\Exception\RecordNotFoundException;
use Camelia\Orm\Metadata\ClassMetadata;
use Camelia\Orm\Metadata\PropertyMetadata;
use Camelia\Orm\Metadata\RelationMetadata;
use Camelia\Orm\Pagination\Page;
use Camelia\Orm\Persistence\Persister;
use Camelia\Orm\Query\Cond;
use Camelia\Orm\Query\Dialect;
use Camelia\Orm\Query\MySqlDialect;
use Camelia\Orm\Query\Query;
use Camelia\Orm\Query\QueryBuilder;
use Camelia\Orm\Query\QueryState;
use Camelia\Orm\Support\TypeCaster;
/**
* Public read and write API for one model class.
*
* @api
* @template T of Model
*/
final class Repository
{
private const MAX_RELATION_DEPTH = 3;
private readonly QueryBuilder $builder;
/**
* @param class-string<T> $class
*/
public function __construct(
private readonly Connection $connection,
private readonly string $class,
private readonly Dialect $dialect = new MySqlDialect(),
private readonly ?Persister $persister = null,
) {
$this->builder = new QueryBuilder($this->dialect);
$this->metadata();
}
public function metadata(): ClassMetadata
{
return Model::metadataFor($this->class);
}
/**
* @param array<string, mixed|Cond> $criteria
* @param list<array{0: string, 1: 'ASC'|'DESC'}> $order
* @param true|array<int|string, mixed>|false $with
* @return list<T>
*/
public function find(
array $criteria = [],
array $order = [],
?int $limit = null,
?int $offset = null,
bool|array $with = false,
): array {
$compiled = $this->builder->select($this->metadata(), $criteria, $order, $limit, $offset);
$rows = $this->connection->select($compiled['sql'], $compiled['params']);
return $this->hydrateRows($rows, null, $with === false ? false : $with);
}
/**
* @param array<string, mixed|Cond> $criteria
* @param list<array{0: string, 1: 'ASC'|'DESC'}> $order
* @param true|array<int|string, mixed>|false $with
* @return T|null
*/
public function findFirst(
array $criteria = [],
array $order = [],
bool|array $with = false,
): ?Model {
$rows = $this->find($criteria, $order, 1, null, $with);
return $rows[0] ?? null;
}
/**
* @param true|array<int|string, mixed>|false $with
* @return T|null
*/
public function findByPk(int|string $pk, bool|array $with = false): ?Model
{
return $this->findFirst([$this->metadata()->primaryKey() => $pk], [], $with);
}
/**
* @param true|array<int|string, mixed>|false $with
* @return T
*/
public function findByPkOrFail(int|string $pk, bool|array $with = false): Model
{
$model = $this->findByPk($pk, $with);
if ($model === null) {
throw RecordNotFoundException::byPrimaryKey($this->class, $pk);
}
return $model;
}
/**
* @param array<string, mixed|Cond> $criteria
* @param array<string, mixed> $values
* @return T
*/
public function findOrCreate(array $criteria, array $values = []): Model
{
$found = $this->findFirst($criteria);
if ($found !== null) {
return $found;
}
return $this->create($values + $criteria);
}
/**
* @param array<string, mixed|Cond> $criteria
*/
public function count(array $criteria = []): int
{
$compiled = $this->builder->count($this->metadata(), $criteria);
return (int) $this->connection->scalar($compiled['sql'], $compiled['params']);
}
/**
* @param array<string, mixed|Cond> $criteria
*/
public function exists(array $criteria = []): bool
{
return $this->count($criteria) > 0;
}
/**
* @param array<string, mixed|Cond> $criteria
*/
public function sum(string $column, array $criteria = []): float
{
return (float) ($this->aggregate('SUM', $column, $criteria) ?? 0.0);
}
/**
* @param array<string, mixed|Cond> $criteria
*/
public function avg(string $column, array $criteria = []): float
{
return (float) ($this->aggregate('AVG', $column, $criteria) ?? 0.0);
}
/**
* @param array<string, mixed|Cond> $criteria
*/
public function max(string $column, array $criteria = []): ?float
{
return $this->aggregate('MAX', $column, $criteria);
}
/**
* @param array<string, mixed|Cond> $criteria
*/
public function min(string $column, array $criteria = []): ?float
{
return $this->aggregate('MIN', $column, $criteria);
}
/**
* @param array<string, mixed|Cond> $criteria
* @param list<array{0: string, 1: 'ASC'|'DESC'}> $order
*/
public function page(
array $criteria = [],
array $order = [],
int $page = 1,
int $perPage = 20,
): Page {
$query = $this->query();
foreach ($criteria as $column => $value) {
$query = $query->where((string) $column, $value);
}
foreach ($order as [$column, $direction]) {
$query = $query->orderBy($column, $direction);
}
return $query->page($page, $perPage);
}
public function query(): Query
{
return Query::start(
$this,
new QueryState($this->metadata()),
$this->connection,
$this->builder,
);
}
/**
* @return int|string
*/
public function save(Model $model): int|string
{
return $this->persister()->save($model);
}
/**
* @param array<string, mixed> $values
* @return T
*/
public function create(array $values = []): Model
{
/** @var T $model */
$model = new $this->class();
$model->hydrate($values);
$this->persister()->insert($model);
return $model;
}
public function update(Model $model): void
{
$this->persister()->update($model);
}
public function delete(Model $model): void
{
$this->persister()->delete($model);
}
/**
* @param array<string, mixed> $values keyed by property or column
*/
public function patch(int|string $pk, array $values): void
{
$this->persister()->patch($this->instance(), $pk, $values);
}
public function remove(int|string $pk): bool
{
return $this->persister()->remove($this->instance(), $pk);
}
/**
* Loads the declared relationships of an already hydrated model into the instance.
*
* @param list<string> $only empty means every declared relationship
*/
public function refreshRelations(Model $model, array $only = []): void
{
$this->loadRelationsInto([$model], $only === [] ? true : $only, 0);
}
/**
* Hydrates database rows into models and applies eager loading.
*
* @internal used by Query
* @param list<array<string, mixed>> $rows
* @param list<string>|null $columns properties actually selected
* @param true|array<int|string, mixed>|false $with
* @return list<T>
*/
public function hydrateRows(array $rows, ?array $columns, bool|array $with): array
{
$models = $this->hydrate($rows);
if ($columns !== null && $columns !== []) {
foreach ($models as $model) {
$model->markPartial();
}
}
if ($with !== false && $with !== []) {
$this->loadRelationsInto($models, $with, 0);
}
return $models;
}
/**
* @internal
* @param list<array<string, mixed>> $rows
* @return list<T>
*/
public function hydrate(array $rows): array
{
$metadata = $this->metadata();
$models = [];
foreach ($rows as $row) {
/** @var T $model */
$model = new $this->class();
foreach ($row as $column => $value) {
$property = $metadata->property((string) $column);
if ($property === null) {
continue;
}
$model->set($property, $this->castDatabaseValue(
$metadata->properties()[$property],
$value,
));
}
$models[] = $model;
}
return $models;
}
private function castDatabaseValue(PropertyMetadata $definition, mixed $value): mixed
{
if ($value === null) {
return null;
}
return TypeCaster::cast($value, $definition->type, true, $definition->name);
}
/**
* @param array<string, mixed|Cond> $criteria
*/
private function aggregate(string $function, string $column, array $criteria): ?float
{
$compiled = $this->builder->aggregate($this->metadata(), $column, $function, $criteria);
$value = $this->connection->scalar($compiled['sql'], $compiled['params']);
return $value === null ? null : (float) $value;
}
private function persister(): Persister
{
if ($this->persister !== null) {
return $this->persister;
}
return new Persister($this->connection, $this->builder);
}
private function instance(): Model
{
/** @var T $model */
$model = new $this->class();
return $model;
}
/**
* @param list<Model> $models
* @param true|array<int|string, mixed>|false $with
*/
private function loadRelationsInto(array $models, bool|array $with, int $depth): void
{
if ($with === false) {
return;
}
$metadata = $this->metadata();
$requested = $this->resolveRequestedRelations($metadata, $with);
// Validate every requested path up front: a typo must fail even when no rows matched.
foreach ($requested as $request) {
$this->validateRelationPath(
$metadata,
$request['name'],
$request['nested'],
$depth + 1,
);
}
if ($models === []) {
return;
}
if (($depth + 1) > self::MAX_RELATION_DEPTH) {
throw ConfigurationException::relationDepthExceeded(self::MAX_RELATION_DEPTH);
}
foreach ($requested as $requested) {
$relation = $this->relationMetadata($requested['name']);
$nested = $requested['nested'];
$this->loadOneRelation($models, $relation, $metadata);
if ($nested === []) {
continue;
}
$loaded = [];
foreach ($models as $model) {
/** @var mixed $value */
$value = $model->get($relation->name);
if ($value instanceof Model) {
$loaded[] = $value;
}
if (is_array($value)) {
foreach ($value as $related) {
if (!$related instanceof Model) {
continue;
}
$loaded[] = $related;
}
}
}
$relatedMeta = $relation->relation;
if ($relatedMeta === null) {
continue;
}
$relatedRepository = $this->relatedRepository($relatedMeta->relatedClass);
$relatedRepository->loadRelationsInto($loaded, $nested, $depth + 1);
}
}
/**
* @param list<Model> $models
*/
private function loadOneRelation(
array $models,
PropertyMetadata $property,
ClassMetadata $metadata,
): void {
$relation = $property->relation;
if ($relation === null) {
return;
}
if ($relation->kind === RelationMetadata::KIND_BELONGS_TO_MANY) {
$this->loadBelongsToMany($models, $property);
return;
}
if ($relation->kind === RelationMetadata::KIND_BELONGS_TO) {
$this->loadBelongsTo($models, $property, $metadata);
return;
}
$this->loadHasManyOrOne($models, $property);
}
/**
* @param list<Model> $models
*/
private function loadBelongsTo(
array $models,
PropertyMetadata $property,
ClassMetadata $metadata,
): void {
$relation = $property->relation;
\assert($relation !== null);
$foreignProperty = $metadata->resolveProperty($relation->foreignKey);
if ($foreignProperty === null) {
throw MetadataException::missingForeignKey(
$metadata->class,
$property->name,
$relation->foreignKey,
);
}
$keys = [];
foreach ($models as $model) {
$value = $model->get($foreignProperty);
if ($value !== null && $value !== '') {
$keys[(string) $value] = $value;
}
}
$relatedRepository = $this->relatedRepository($relation->relatedClass);
$relatedMetadata = $relatedRepository->metadata();
$found = [];
if ($keys !== []) {
$records = $relatedRepository->find([
$relatedMetadata->primaryKey() => array_values($keys),
]);
foreach ($records as $record) {
$found[(string) $record->get($relatedMetadata->primaryKey())] = $record;
}
}
foreach ($models as $model) {
$value = $model->get($foreignProperty);
if ($value === null || $value === '') {
continue;
}
$model->set($property->name, $found[(string) $value] ?? null);
}
}
/**
* @param list<Model> $models
*/
private function loadHasManyOrOne(array $models, PropertyMetadata $property): void
{
$relation = $property->relation;
\assert($relation !== null);
$metadata = $this->metadata();
$ownerKey = $metadata->primaryKey();
$keys = [];
foreach ($models as $model) {
$value = $model->get($ownerKey);
if ($value !== null && $value !== '') {
$keys[(string) $value] = $value;
}
}
$relatedRepository = $this->relatedRepository($relation->relatedClass);
$relatedMetadata = $relatedRepository->metadata();
$grouped = [];
if ($keys !== []) {
$records = $relatedRepository->find([
$relation->foreignKey => array_values($keys),
]);
foreach ($records as $record) {
$grouped[(string) $record->get($relation->foreignKey)][] = $record;
}
}
foreach ($models as $model) {
$key = (string) $model->get($ownerKey);
$matches = $grouped[$key] ?? [];
if ($relation->isToMany()) {
$model->set($property->name, $matches);
continue;
}
$model->set($property->name, $matches[0] ?? null);
}
}
/**
* @param list<Model> $models
*/
private function loadBelongsToMany(array $models, PropertyMetadata $property): void
{
$relation = $property->relation;
\assert($relation !== null);
\assert($relation->through !== null);
\assert($relation->foreignPivotKey !== null);
\assert($relation->relatedPivotKey !== null);
$metadata = $this->metadata();
$ownerKey = $metadata->primaryKey();
$keys = [];
foreach ($models as $model) {
$value = $model->get($ownerKey);
if ($value !== null && $value !== '') {
$keys[(string) $value] = $value;
}
}
if ($keys === []) {
foreach ($models as $model) {
$model->set($property->name, []);
}
return;
}
$pivot = $this->dialect->quoteIdentifier($relation->through);
$foreignPivot = $this->dialect->quoteIdentifier($relation->foreignPivotKey);
$relatedPivot = $this->dialect->quoteIdentifier($relation->relatedPivotKey);
$placeholders = implode(', ', array_fill(0, count($keys), '?'));
$sql =
'SELECT '
. $foreignPivot
. ' AS pivot_owner, '
. $relatedPivot
. ' AS pivot_related'
. ' FROM '
. $pivot
. ' WHERE '
. $foreignPivot
. ' IN ('
. $placeholders
. ')';
$rows = $this->connection->select($sql, array_values($keys));
$relatedRepository = $this->relatedRepository($relation->relatedClass);
$relatedMetadata = $relatedRepository->metadata();
$grouped = [];
$relatedKeys = [];
foreach ($rows as $row) {
if (!isset($row['pivot_owner'], $row['pivot_related'])) {
continue;
}
$ownerId = (string) $row['pivot_owner'];
$relatedId = (string) $row['pivot_related'];
$grouped[$ownerId][] = $relatedId;
$relatedKeys[$relatedId] = $row['pivot_related'];
}
$records = [];
if ($relatedKeys !== []) {
foreach ($relatedRepository->find([
$relatedMetadata->primaryKey() => array_values($relatedKeys),
]) as $record) {
$records[(string) $record->get($relatedMetadata->primaryKey())] = $record;
}
}
foreach ($models as $model) {
$ownerId = (string) $model->get($ownerKey);
$related = [];
foreach ($grouped[$ownerId] ?? [] as $relatedId) {
if (!isset($records[$relatedId])) {
continue;
}
$related[] = $records[$relatedId];
}
$model->set($property->name, $related);
}
}
/**
* @param true|array<int|string, mixed>|list<string> $with
* @return list<array{name: string, nested: true|list<string>|array<int|string, mixed>}>
*/
private function resolveRequestedRelations(ClassMetadata $metadata, bool|array $with): array
{
$requested = [];
if ($with === true) {
foreach ($metadata->relations() as $relation) {
$requested[] = ['name' => $relation->name, 'nested' => []];
}
return $requested;
}
foreach ($with as $key => $value) {
if (is_int($key)) {
$path = (string) $value;
$segments = explode('.', $path);
$name = $segments[0];
$nested = array_slice($segments, 1);
// Remaining segments are one nested path, not sibling relations.
$requested[] = [
'name' => $name,
'nested' => $nested === [] ? [] : [implode('.', $nested)],
];
continue;
}
$nestedValue = $value === true || is_array($value) ? $value : [];
$requested[] = ['name' => (string) $key, 'nested' => $nestedValue];
}
return $requested;
}
private function relationMetadata(string $name): PropertyMetadata
{
$metadata = $this->metadata();
if (!$metadata->hasProperty($name) || $metadata->properties()[$name]->relation === null) {
throw MetadataException::unknownRelation($this->class, $name);
}
return $metadata->properties()[$name];
}
/**
* Walks a requested path, validating every hop and enforcing the depth limit.
*
* @param true|array<int|string, mixed>|list<string> $nested
*/
private function validateRelationPath(
ClassMetadata $metadata,
string $name,
bool|array $nested,
int $depth,
): void {
if ($depth > self::MAX_RELATION_DEPTH) {
throw ConfigurationException::relationDepthExceeded(self::MAX_RELATION_DEPTH);
}
if (!$metadata->hasProperty($name) || $metadata->properties()[$name]->relation === null) {
throw MetadataException::unknownRelation($metadata->class, $name);
}
if ($nested === true) {
return;
}
$relation = $metadata->properties()[$name]->relation;
if ($relation === null) {
return;
}
$next = $this->relatedRepository($relation->relatedClass)->metadata();
foreach ($nested as $key => $value) {
if (is_int($key)) {
$segments = explode('.', (string) $value);
$this->validateRelationPath(
$next,
$segments[0],
array_slice($segments, 1),
$depth + 1,
);
continue;
}
$this->validateRelationPath(
$next,
(string) $key,
is_array($value) ? $value : true,
$depth + 1,
);
}
}
/**
* @param class-string<Model> $class
* @return Repository<Model>
*/
private function relatedRepository(string $class): self
{
return new self($this->connection, $class, $this->dialect, $this->persister);
}
/**
* @internal
*/
public function connection(): Connection
{
return $this->connection;
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Support;
use DateTimeImmutable;
/**
* Abstraction over the current time, so hooks and generated values are testable.
*/
interface Clock
{
public function now(): DateTimeImmutable;
}
+53
View File
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Support;
/**
* Pure name conversion between PHP and SQL conventions.
*/
final class NameConverter
{
/**
* Inserts an underscore before every internal uppercase letter.
*
* The first character is never prefixed, so leading acronyms keep their shape:
* codigoEmpresa -> codigo_empresa, idZona -> id_zona, normal -> normal.
*/
public static function camelToSnake(string $name): string
{
if ($name === '') {
return '';
}
$result = $name[0];
$length = strlen($name);
for ($i = 1; $i < $length; $i++) {
$char = $name[$i];
if ($char >= 'A' && $char <= 'Z' && $name[$i - 1] !== '_') {
$result .= '_';
}
$result .= $char;
}
return strtolower($result);
}
/**
* Converts a column name back to the matching camelCase property name.
*/
public static function snakeToCamel(string $name): string
{
if ($name === '') {
return '';
}
$camel = str_replace(' ', '', ucwords(str_replace('_', ' ', $name)));
return lcfirst($camel);
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Support;
use DateTimeImmutable;
/**
* Default clock backed by the system time.
*/
final class SystemClock implements Clock
{
public function now(): DateTimeImmutable
{
return new DateTimeImmutable('now');
}
}
+336
View File
@@ -0,0 +1,336 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Support;
use DateTimeImmutable;
use DateTimeInterface;
use Stringable;
/**
* Converts scalar values between PHP types, SQL storage and JSON.
*
* Every refusal throws: a value that cannot be cast is never silently turned into null.
* BigDecimal support is resolved by class name, because brick/math is only a suggestion.
*/
final class TypeCaster
{
private const BIG_DECIMAL = 'Brick\\Math\\BigDecimal';
public static function hasBigDecimal(): bool
{
return class_exists(self::BIG_DECIMAL);
}
/**
* Casts an incoming value to the declared property type.
*
* @throws \InvalidArgumentException when the value does not fit the type
*/
public static function cast(
mixed $value,
string $type,
bool $nullable,
string $context = '',
): mixed {
if ($value === null) {
if ($nullable) {
return null;
}
throw self::refusal(
$context,
$value,
$type,
'null is not allowed for a non-nullable property',
);
}
return match ($type) {
'int' => self::toInt($value, $context),
'float' => self::toFloat($value, $context),
'bool' => self::toBool($value, $context),
'string' => self::toString($value, $context),
'array' => self::toArray($value, $context),
DateTimeImmutable::class => self::toDateTime($value, $context),
self::BIG_DECIMAL => self::toBigDecimal($value, $context),
default => $value,
};
}
/**
* Casts an incoming value to a backed enum instance.
*
* @param class-string<\BackedEnum> $enumClass
*/
public static function castEnum(
mixed $value,
string $enumClass,
bool $nullable,
string $context,
): mixed {
if ($value === null) {
if ($nullable) {
return null;
}
throw self::refusal(
$context,
$value,
$enumClass,
'null is not allowed for a non-nullable enum',
);
}
if (!is_subclass_of($enumClass, \BackedEnum::class)) {
throw self::refusal($context, $value, $enumClass, 'declared enum is not a backed enum');
}
if ($value instanceof $enumClass) {
return $value;
}
if (is_int($value) || is_string($value)) {
$case = $enumClass::tryFrom($value);
if ($case !== null) {
return $case;
}
}
throw self::refusal($context, $value, $enumClass, 'value is not a case of the enum');
}
public static function toDatabaseValue(mixed $value): mixed
{
if ($value instanceof \BackedEnum) {
return $value->value;
}
if (is_object($value) && is_a($value, self::BIG_DECIMAL)) {
return (string) $value;
}
if ($value instanceof DateTimeInterface) {
return $value->format('Y-m-d H:i:s');
}
return $value;
}
public static function toSerializable(mixed $value): mixed
{
if ($value instanceof \BackedEnum) {
return $value->value;
}
if ($value instanceof DateTimeInterface) {
return $value->format(DATE_ATOM);
}
if (is_object($value) && is_a($value, self::BIG_DECIMAL)) {
return (string) $value;
}
return $value;
}
private static function toInt(mixed $value, string $context): int
{
if (is_int($value)) {
return $value;
}
if (is_bool($value)) {
return $value ? 1 : 0;
}
if (is_float($value)) {
return (int) $value;
}
if (is_string($value) && self::isNumericString($value)) {
return (int) $value;
}
throw self::refusal($context, $value, 'int', 'not an integer, numeric string or bool');
}
private static function toFloat(mixed $value, string $context): float
{
if (is_float($value)) {
return $value;
}
if (is_bool($value)) {
return $value ? 1.0 : 0.0;
}
if (is_int($value)) {
return (float) $value;
}
if (is_string($value) && self::isNumericString($value)) {
return (float) $value;
}
throw self::refusal($context, $value, 'float', 'not a float, numeric string or bool');
}
private static function toBool(mixed $value, string $context): bool
{
if (is_bool($value)) {
return $value;
}
if ($value === 0 || $value === 1) {
return $value === 1;
}
if ($value === '0' || $value === '1') {
return $value === '1';
}
if (is_string($value)) {
$normalized = strtolower($value);
if ($normalized === 'true') {
return true;
}
if ($normalized === 'false') {
return false;
}
}
throw self::refusal($context, $value, 'bool', 'use true/false, 0/1 or "true"/"false"');
}
private static function toString(mixed $value, string $context): string
{
if (is_string($value)) {
return $value;
}
if (is_scalar($value) || $value instanceof Stringable) {
return (string) $value;
}
throw self::refusal($context, $value, 'string', 'not a scalar or Stringable');
}
/**
* @return array<mixed>
*/
private static function toArray(mixed $value, string $context): array
{
if (is_array($value)) {
return $value;
}
if (is_string($value)) {
$decoded = json_decode($value, true);
if (is_array($decoded)) {
return $decoded;
}
}
throw self::refusal(
$context,
$value,
'array',
'not an array or a JSON object/array string',
);
}
private static function toDateTime(mixed $value, string $context): DateTimeImmutable
{
if ($value instanceof DateTimeImmutable) {
return $value;
}
if ($value instanceof DateTimeInterface) {
return DateTimeImmutable::createFromInterface($value);
}
if (is_string($value) && $value !== '') {
try {
return new DateTimeImmutable($value);
} catch (\Exception) {
throw self::refusal(
$context,
$value,
DateTimeImmutable::class,
'not a valid date string',
);
}
}
throw self::refusal(
$context,
$value,
DateTimeImmutable::class,
'not a date or date string',
);
}
private static function toBigDecimal(mixed $value, string $context): mixed
{
$class = self::BIG_DECIMAL;
if ($value instanceof $class) {
return $value;
}
if (is_int($value) || is_float($value)) {
return $class::of((string) $value);
}
if (is_string($value) && self::isNumericString($value)) {
return $class::of($value);
}
throw self::refusal($context, $value, self::BIG_DECIMAL, 'not numeric');
}
private static function isNumericString(string $value): bool
{
return $value !== '' && is_numeric($value);
}
private static function refusal(
string $context,
mixed $value,
string $type,
string $reason,
): \InvalidArgumentException {
$field = $context === '' ? 'value' : $context;
return new \InvalidArgumentException(sprintf(
'Cannot cast %s to %s: %s (received %s).',
$field,
$type,
$reason,
self::describe($value),
));
}
private static function describe(mixed $value): string
{
if (is_object($value)) {
return $value::class;
}
if (is_array($value)) {
return 'array';
}
if (is_string($value)) {
return '"' . (strlen($value) > 40 ? substr($value, 0, 40) . '...' : $value) . '"';
}
return var_export($value, true);
}
}
+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\BelongsToMany;
use Camelia\Orm\Attribute\PrimaryKey;
use Camelia\Orm\Attribute\TableName;
use Camelia\Orm\Model;
#[TableName('articulos')]
final class Articulo extends Model
{
#[PrimaryKey, AutoIncrement]
public ?int $codigo = null;
public string $nombre = '';
/** @var array<int, Etiqueta> */
#[BelongsToMany(
related: Etiqueta::class,
through: 'articulo_etiqueta',
foreignPivotKey: 'articulo_codigo',
relatedPivotKey: 'etiqueta_codigo',
)]
public array $etiquetas = [];
}
+31
View File
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Fixture;
use Camelia\Orm\Attribute\AutoIncrement;
use Camelia\Orm\Attribute\PrimaryKey;
use Camelia\Orm\Attribute\TableName;
use Camelia\Orm\Model;
#[TableName('con_hooks')]
final class ConHooks extends Model
{
#[PrimaryKey, AutoIncrement]
public ?int $codigo = null;
public string $nombre = '';
public string $creadoPorHook = '';
protected function beforeInsert(): void
{
$this->creadoPorHook = 'insert';
}
protected function beforeUpdate(): void
{
$this->creadoPorHook = 'update';
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Fixture;
use Camelia\Orm\Attribute\AutoIncrement;
use Camelia\Orm\Attribute\PrimaryKey;
use Camelia\Orm\Attribute\TableName;
use Camelia\Orm\Model;
#[TableName('detalles')]
final class Detalle extends Model
{
#[PrimaryKey, AutoIncrement]
public ?int $codigo = null;
public int $facturaCodigo = 0;
public string $concepto = '';
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Fixture;
use Camelia\Orm\Attribute\AutoIncrement;
use Camelia\Orm\Attribute\BelongsToMany;
use Camelia\Orm\Attribute\PrimaryKey;
use Camelia\Orm\Attribute\TableName;
use Camelia\Orm\Model;
/**
* Chain fixture used to prove nested eager loading:
* Articulo -> Etiqueta -> Factura -> Usuario.
*/
#[TableName('etiquetas')]
final class Etiqueta extends Model
{
#[PrimaryKey]
#[AutoIncrement]
public ?int $codigo = null;
public string $nombre = '';
/** @var array<int, Factura> */
#[BelongsToMany(
related: Factura::class,
through: 'etiqueta_factura',
foreignPivotKey: 'etiqueta_codigo',
relatedPivotKey: 'factura_codigo',
)]
public array $facturas = [];
}
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Fixture;
use Camelia\Orm\Attribute\AutoIncrement;
use Camelia\Orm\Attribute\BelongsTo;
use Camelia\Orm\Attribute\Column;
use Camelia\Orm\Attribute\HasMany;
use Camelia\Orm\Attribute\PrimaryKey;
use Camelia\Orm\Attribute\TableName;
use Camelia\Orm\Model;
#[TableName('facturas')]
final class Factura extends Model
{
#[PrimaryKey, AutoIncrement]
public ?int $codigo = null;
public int $usuarioCodigo = 0;
#[Column('importe_total')]
public float $total = 0.0;
#[BelongsTo(Usuario::class, foreignKey: 'usuarioCodigo')]
public ?Usuario $usuario = null;
/** @var array<int, Detalle> */
#[HasMany(Detalle::class, foreignKey: 'facturaCodigo')]
public array $detalles = [];
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Fixture\Invalid;
use Camelia\Orm\Attribute\Column;
use Camelia\Orm\Attribute\PrimaryKey;
use Camelia\Orm\Attribute\TableName;
use Camelia\Orm\Model;
#[TableName('columna_duplicada')]
final class ColumnaDuplicada extends Model
{
#[PrimaryKey]
public ?int $codigo = null;
public string $nombre = '';
#[Column('nombre')]
public string $nombreAlternativo = '';
}
+19
View File
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Fixture\Invalid;
use Camelia\Orm\Attribute\PrimaryKey;
use Camelia\Orm\Attribute\TableName;
use Camelia\Orm\Model;
#[TableName('dos_pk')]
final class DosPrimaryKeys extends Model
{
#[PrimaryKey]
public ?int $codigo = null;
#[PrimaryKey]
public ?int $otro = null;
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Fixture\Invalid;
use Camelia\Orm\Attribute\BelongsTo;
use Camelia\Orm\Attribute\PrimaryKey;
use Camelia\Orm\Attribute\TableName;
use Camelia\Orm\Model;
use Camelia\Orm\Tests\Fixture\Usuario;
#[TableName('relacion_no_nulable')]
final class RelacionNoNulable extends Model
{
#[PrimaryKey]
public ?int $codigo = null;
#[BelongsTo(Usuario::class, foreignKey: 'codigo')]
public Usuario $usuario;
}
+14
View File
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Fixture\Invalid;
use Camelia\Orm\Attribute\TableName;
use Camelia\Orm\Model;
#[TableName('sin_pk')]
final class SinPrimaryKey extends Model
{
public string $nombre = '';
}
+14
View File
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Fixture\Invalid;
use Camelia\Orm\Attribute\PrimaryKey;
use Camelia\Orm\Model;
final class SinTableName extends Model
{
#[PrimaryKey]
public ?int $codigo = null;
}
+18
View File
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Fixture\Invalid;
use Camelia\Orm\Attribute\PrimaryKey;
use Camelia\Orm\Attribute\TableName;
use Camelia\Orm\Model;
#[TableName('sin_tipo')]
final class SinTipo extends Model
{
#[PrimaryKey]
public ?int $codigo = null;
public $nombre;
}
+35
View File
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Fixture;
use Camelia\Orm\Attribute\AutoIncrement;
use Camelia\Orm\Attribute\Guarded;
use Camelia\Orm\Attribute\MaxLength;
use Camelia\Orm\Attribute\PrimaryKey;
use Camelia\Orm\Attribute\Required;
use Camelia\Orm\Attribute\TableName;
use Camelia\Orm\Model;
#[TableName('usuarios')]
final class Usuario extends Model
{
#[PrimaryKey, AutoIncrement]
public ?int $codigo = null;
public string $nombre = '';
public string $correo = '';
#[Guarded]
public string $passwordHash = '';
public bool $activo = true;
public ?string $apodo = null;
#[Required]
#[MaxLength(10)]
public string $clave = '';
}
+119
View File
@@ -0,0 +1,119 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Support;
use Camelia\Orm\Connection\Connection;
/**
* Records every statement instead of touching a database.
*/
final class FakeConnection implements Connection
{
/** @var list<array{sql: string, params: list<mixed>}> */
public array $executed = [];
/** @var list<array{sql: string, params: list<mixed>}> */
public array $selected = [];
/** @var list<array<string, mixed>> rows returned by select() */
public array $rows = [];
/** @var list<list<array<string, mixed>>> sequential responses; when set, consumed before $rows */
public array $rowBatches = [];
/** @var list<mixed> values returned in order by scalar() */
public array $scalars = [];
public string $lastInsertId = '1';
public int $affected = 1;
public int $beginCount = 0;
public int $commitCount = 0;
public int $rollBackCount = 0;
private bool $inTransaction = false;
public function execute(string $sql, array $params = []): int
{
$this->executed[] = ['sql' => $sql, 'params' => $params];
return $this->affected;
}
public function select(string $sql, array $params = []): array
{
$this->selected[] = ['sql' => $sql, 'params' => $params];
if ($this->rowBatches !== []) {
return array_shift($this->rowBatches);
}
return $this->rows;
}
public function scalar(string $sql, array $params = []): mixed
{
$this->selected[] = ['sql' => $sql, 'params' => $params];
return $this->scalars === [] ? null : array_shift($this->scalars);
}
public function lastInsertId(): string
{
return $this->lastInsertId;
}
public function begin(): void
{
$this->beginCount++;
$this->inTransaction = true;
}
public function commit(): void
{
$this->commitCount++;
$this->inTransaction = false;
}
public function rollBack(): void
{
$this->rollBackCount++;
$this->inTransaction = false;
}
public function inTransaction(): bool
{
return $this->inTransaction;
}
public function driver(): string
{
return 'fake';
}
public function lastSql(): string
{
if ($this->executed === []) {
return '';
}
return $this->executed[count($this->executed) - 1]['sql'];
}
/** @return list<mixed> */
public function lastParams(): array
{
$entries = $this->selected === [] ? $this->executed : $this->selected;
if ($entries === []) {
return [];
}
return $entries[count($entries) - 1]['params'];
}
}
+205
View File
@@ -0,0 +1,205 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit;
use Camelia\Orm\Exception\MetadataException;
use Camelia\Orm\Repository;
use Camelia\Orm\Tests\Fixture\Articulo;
use Camelia\Orm\Tests\Fixture\Detalle;
use Camelia\Orm\Tests\Fixture\Etiqueta;
use Camelia\Orm\Tests\Fixture\Factura;
use Camelia\Orm\Tests\Fixture\Usuario;
use Camelia\Orm\Tests\Support\FakeConnection;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class EagerLoadingTest extends TestCase
{
private FakeConnection $connection;
protected function setUp(): void
{
$this->connection = new FakeConnection();
}
#[Test]
public function it_loads_belongs_to_in_one_batch_query(): void
{
$this->connection->rowBatches = [
[$this->facturaRow(1, 7), $this->facturaRow(2, 8)],
[$this->usuarioRow(7, 'Ana'), $this->usuarioRow(8, 'Bea')],
];
$facturas = $this->repository(Factura::class)->find(with: ['usuario']);
self::assertCount(2, $facturas);
$primera = $facturas[0];
self::assertInstanceOf(Factura::class, $primera);
self::assertInstanceOf(Usuario::class, $primera->usuario);
self::assertSame('Ana', $primera->usuario->nombre);
self::assertCount(2, $this->connection->selected);
self::assertStringContainsString('IN (?, ?)', $this->connection->selected[1]['sql']);
}
#[Test]
public function it_loads_has_many_grouped_by_parent(): void
{
$this->connection->rowBatches = [
[$this->facturaRow(1, 7)],
[
['codigo' => '10', 'factura_codigo' => '1', 'concepto' => 'A'],
['codigo' => '11', 'factura_codigo' => '1', 'concepto' => 'B'],
],
];
$facturas = $this->repository(Factura::class)->find(with: ['detalles']);
$factura = $facturas[0];
self::assertInstanceOf(Factura::class, $factura);
self::assertCount(2, $factura->detalles);
$detalle = $factura->detalles[0];
self::assertInstanceOf(Detalle::class, $detalle);
self::assertSame('A', $detalle->concepto);
}
#[Test]
public function it_loads_belongs_to_many_through_the_pivot(): void
{
$this->connection->rowBatches = [
[['codigo' => '1', 'nombre' => 'Articulo']],
[
['pivot_owner' => '1', 'pivot_related' => '5'],
['pivot_owner' => '1', 'pivot_related' => '6'],
],
[
['codigo' => '5', 'nombre' => 'rojo'],
['codigo' => '6', 'nombre' => 'verde'],
],
];
$articulos = $this->repository(Articulo::class)->find(with: ['etiquetas']);
$articulo = $articulos[0];
self::assertInstanceOf(Articulo::class, $articulo);
self::assertCount(2, $articulo->etiquetas);
$etiqueta = $articulo->etiquetas[0];
self::assertInstanceOf(Etiqueta::class, $etiqueta);
self::assertSame('rojo', $etiqueta->nombre);
self::assertStringContainsString(
'`articulo_etiqueta`',
$this->connection->selected[1]['sql'],
);
}
#[Test]
public function it_leaves_belongs_to_null_when_the_row_is_missing(): void
{
$this->connection->rowBatches = [
[$this->facturaRow(1, 99)],
[],
];
$facturas = $this->repository(Factura::class)->find(with: ['usuario']);
$factura = $facturas[0];
self::assertInstanceOf(Factura::class, $factura);
self::assertNull($factura->usuario);
}
#[Test]
public function it_refuses_an_unknown_relation(): void
{
$this->connection->rowBatches = [];
$this->expectException(MetadataException::class);
$this->repository(Factura::class)->find(with: ['usuario.inexistente']);
}
#[Test]
public function it_accepts_deeply_nested_paths_up_to_the_limit(): void
{
$this->connection->rowBatches = [
[['codigo' => '1', 'nombre' => 'Articulo']],
[['pivot_owner' => '1', 'pivot_related' => '5']],
[['codigo' => '5', 'nombre' => 'rojo']],
[$this->facturaRow(1, 7)],
[$this->usuarioRow(7, 'Ana')],
];
$articulos = $this->repository(Articulo::class)->find(with: ['etiquetas.facturas.usuario']);
self::assertCount(1, $articulos);
$articulo = $articulos[0];
self::assertInstanceOf(Articulo::class, $articulo);
self::assertCount(1, $articulo->etiquetas);
}
#[Test]
public function it_refuses_an_unknown_nested_relation(): void
{
$this->connection->rowBatches = [
[$this->facturaRow(1, 7)],
[$this->usuarioRow(7, 'Ana')],
];
$this->expectException(MetadataException::class);
$this->repository(Factura::class)->find(with: ['usuario.inexistente']);
}
#[Test]
public function it_refreshes_relations_on_a_hydrated_model(): void
{
$this->connection->rowBatches = [
[$this->usuarioRow(7, 'Ana')],
];
$factura = new Factura();
$factura->codigo = 1;
$factura->usuarioCodigo = 7;
$this->repository(Factura::class)->refreshRelations($factura, ['usuario']);
self::assertInstanceOf(Usuario::class, $factura->usuario);
}
/**
* @param class-string<\Camelia\Orm\Model> $class
* @return Repository<\Camelia\Orm\Model>
*/
private function repository(string $class): Repository
{
return new Repository($this->connection, $class);
}
/**
* @return array<string, mixed>
*/
private function facturaRow(int $codigo, int $usuarioCodigo): array
{
return [
'codigo' => (string) $codigo,
'usuario_codigo' => (string) $usuarioCodigo,
'importe_total' => '10.5',
];
}
/**
* @return array<string, mixed>
*/
private function usuarioRow(int $codigo, string $nombre): array
{
return [
'codigo' => (string) $codigo,
'nombre' => $nombre,
'correo' => 'a@x',
'password_hash' => '',
'activo' => '1',
'apodo' => null,
'clave' => '',
];
}
}
+139
View File
@@ -0,0 +1,139 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit\Metadata;
use Camelia\Orm\Exception\MetadataException;
use Camelia\Orm\Metadata\MetadataFactory;
use Camelia\Orm\Tests\Fixture\Articulo;
use Camelia\Orm\Tests\Fixture\Factura;
use Camelia\Orm\Tests\Fixture\Invalid\ColumnaDuplicada;
use Camelia\Orm\Tests\Fixture\Invalid\DosPrimaryKeys;
use Camelia\Orm\Tests\Fixture\Invalid\RelacionNoNulable;
use Camelia\Orm\Tests\Fixture\Invalid\SinPrimaryKey;
use Camelia\Orm\Tests\Fixture\Invalid\SinTableName;
use Camelia\Orm\Tests\Fixture\Invalid\SinTipo;
use Camelia\Orm\Tests\Fixture\Usuario;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class MetadataFactoryTest extends TestCase
{
#[Test]
public function it_reads_table_and_primary_key(): void
{
$metadata = (new MetadataFactory())->forClass(Usuario::class);
self::assertSame('usuarios', $metadata->table());
self::assertSame('codigo', $metadata->primaryKey());
self::assertSame('codigo', $metadata->primaryKeyColumn());
}
#[Test]
public function it_converts_property_names_to_columns(): void
{
$metadata = (new MetadataFactory())->forClass(Usuario::class);
self::assertSame('password_hash', $metadata->column('passwordHash'));
self::assertSame('passwordHash', $metadata->property('password_hash'));
self::assertNull($metadata->property('inexistente'));
}
#[Test]
public function it_honours_an_explicit_column_name(): void
{
$metadata = (new MetadataFactory())->forClass(Factura::class);
self::assertSame('importe_total', $metadata->column('total'));
}
#[Test]
public function it_excludes_relations_from_writable_columns(): void
{
$metadata = (new MetadataFactory())->forClass(Factura::class);
self::assertSame(['usuarioCodigo', 'total'], $metadata->writable());
self::assertCount(2, $metadata->relations());
}
#[Test]
public function it_resolves_belongs_to_metadata(): void
{
$metadata = (new MetadataFactory())->forClass(Factura::class);
$relation = $metadata->properties()['usuario']->relation;
self::assertNotNull($relation);
self::assertSame('belongsTo', $relation->kind);
self::assertSame(Usuario::class, $relation->relatedClass);
self::assertSame('usuarioCodigo', $relation->foreignKey);
}
#[Test]
public function it_resolves_belongs_to_many_pivot_metadata(): void
{
$metadata = (new MetadataFactory())->forClass(Articulo::class);
$relation = $metadata->properties()['etiquetas']->relation;
self::assertNotNull($relation);
self::assertSame('belongsToMany', $relation->kind);
self::assertSame('articulo_etiqueta', $relation->through);
self::assertSame('articulo_codigo', $relation->foreignPivotKey);
self::assertSame('etiqueta_codigo', $relation->relatedPivotKey);
self::assertTrue($relation->isToMany());
}
#[Test]
public function it_rejects_a_model_without_table_name(): void
{
$this->expectException(MetadataException::class);
$this->expectExceptionMessage('[M2]');
(new MetadataFactory())->forClass(SinTableName::class);
}
#[Test]
public function it_rejects_a_model_without_primary_key(): void
{
$this->expectException(MetadataException::class);
$this->expectExceptionMessage('[M3]');
(new MetadataFactory())->forClass(SinPrimaryKey::class);
}
#[Test]
public function it_rejects_a_model_with_two_primary_keys(): void
{
$this->expectException(MetadataException::class);
$this->expectExceptionMessage('[M3]');
(new MetadataFactory())->forClass(DosPrimaryKeys::class);
}
#[Test]
public function it_rejects_an_untyped_property(): void
{
$this->expectException(MetadataException::class);
$this->expectExceptionMessage('[M4]');
(new MetadataFactory())->forClass(SinTipo::class);
}
#[Test]
public function it_rejects_duplicate_columns(): void
{
$this->expectException(MetadataException::class);
$this->expectExceptionMessage('[M7]');
(new MetadataFactory())->forClass(ColumnaDuplicada::class);
}
#[Test]
public function it_rejects_a_non_nullable_relation(): void
{
$this->expectException(MetadataException::class);
$this->expectExceptionMessage('[M5]');
(new MetadataFactory())->forClass(RelacionNoNulable::class);
}
}
+166
View File
@@ -0,0 +1,166 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit;
use Camelia\Orm\Tests\Fixture\Factura;
use Camelia\Orm\Tests\Fixture\Usuario;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class ModelTest extends TestCase
{
#[Test]
public function it_initializes_neutral_values(): void
{
$usuario = new Usuario();
self::assertNull($usuario->codigo);
self::assertSame('', $usuario->nombre);
self::assertTrue($usuario->activo);
}
#[Test]
public function it_preserves_declared_defaults(): void
{
$factura = new Factura();
self::assertSame(0.0, $factura->total);
self::assertSame([], $factura->detalles);
}
#[Test]
public function it_hydrates_by_property_name(): void
{
$usuario = (new Usuario())->hydrate(['nombre' => 'Ana', 'activo' => false]);
self::assertSame('Ana', $usuario->nombre);
self::assertFalse($usuario->activo);
}
#[Test]
public function it_hydrates_by_column_name(): void
{
$factura = (new Factura())->hydrate(['importe_total' => '12.5']);
self::assertSame(12.5, $factura->total);
}
#[Test]
public function it_prefers_the_property_when_both_forms_are_present(): void
{
$factura = (new Factura())->hydrate(['total' => 1.0, 'importe_total' => 2.0]);
self::assertSame(1.0, $factura->total);
}
#[Test]
public function it_skips_guarded_properties(): void
{
$usuario = (new Usuario())->hydrate(['passwordHash' => 'secreto']);
self::assertSame('', $usuario->passwordHash);
}
#[Test]
public function it_rejects_guarded_properties_in_strict_mode(): void
{
$this->expectException(\InvalidArgumentException::class);
(new Usuario())->hydrateStrict(['passwordHash' => 'secreto']);
}
#[Test]
public function it_ignores_unknown_keys(): void
{
$usuario = (new Usuario())->hydrate(['inexistente' => 1, 'nombre' => 'Ana']);
self::assertSame('Ana', $usuario->nombre);
}
#[Test]
public function it_never_hydrates_the_primary_key(): void
{
$usuario = (new Usuario())->hydrate(['codigo' => 99]);
self::assertNull($usuario->codigo);
}
#[Test]
public function it_casts_and_refuses_uncastable_values(): void
{
$this->expectException(\InvalidArgumentException::class);
(new Usuario())->hydrate(['activo' => 'no-es-bool']);
}
#[Test]
public function it_serializes_writable_columns_by_column_name(): void
{
$usuario = (new Usuario())->hydrate(['nombre' => 'Ana']);
$array = $usuario->toArray();
self::assertSame('Ana', $array['nombre']);
self::assertArrayHasKey('password_hash', $array);
self::assertArrayNotHasKey('codigo', $array);
}
#[Test]
public function it_serializes_json(): void
{
$json = (new Usuario())->hydrate(['nombre' => 'Ana'])->toJson();
$decoded = json_decode($json, true);
self::assertIsArray($decoded);
self::assertSame('Ana', $decoded['nombre']);
}
#[Test]
public function it_validates_required_and_max_length(): void
{
$usuario = new Usuario();
$errors = $usuario->validate();
self::assertArrayHasKey('clave', $errors);
self::assertStringContainsString('requerido', $errors['clave'][0]);
}
#[Test]
public function it_reports_a_too_long_value(): void
{
$usuario = (new Usuario())->hydrate(['clave' => 'supercalifragilistico']);
self::assertStringContainsString('10', $usuario->validate()['clave'][0]);
}
#[Test]
public function it_is_valid_when_no_rule_fails(): void
{
$usuario = (new Usuario())->hydrate(['clave' => 'abc']);
self::assertTrue($usuario->isValid());
}
#[Test]
public function it_replicates_without_the_primary_key(): void
{
$usuario = (new Usuario())->hydrate(['nombre' => 'Ana']);
$usuario->codigo = 5;
$copy = $usuario->replicate();
self::assertNull($copy->codigo);
self::assertSame('Ana', $copy->nombre);
}
#[Test]
public function it_tracks_partial_state(): void
{
$usuario = new Usuario();
self::assertFalse($usuario->isPartial());
$usuario->markPartial();
self::assertTrue($usuario->isPartial());
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit;
use Camelia\Orm\Orm;
use Camelia\Orm\Repository;
use Camelia\Orm\Tests\Fixture\Usuario;
use Camelia\Orm\Tests\Support\FakeConnection;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class OrmTest extends TestCase
{
#[Test]
public function it_returns_a_repository_for_a_model(): void
{
$orm = Orm::fromConnection(new FakeConnection());
self::assertInstanceOf(Repository::class, $orm->repository(Usuario::class));
}
#[Test]
public function it_reuses_the_same_repository_instance(): void
{
$orm = Orm::fromConnection(new FakeConnection());
self::assertSame($orm->repository(Usuario::class), $orm->repository(Usuario::class));
}
#[Test]
public function it_commits_a_successful_transaction(): void
{
$connection = new FakeConnection();
$orm = Orm::fromConnection($connection);
$result = $orm->transaction(static fn(): string => 'ok');
self::assertSame('ok', $result);
self::assertSame(1, $connection->commitCount);
self::assertSame(0, $connection->rollBackCount);
}
#[Test]
public function it_rolls_back_and_rethrows(): void
{
$connection = new FakeConnection();
$orm = Orm::fromConnection($connection);
$this->expectException(\RuntimeException::class);
try {
$orm->transaction(static function (): void {
throw new \RuntimeException('boom');
});
} finally {
self::assertSame(1, $connection->rollBackCount);
self::assertSame(0, $connection->commitCount);
}
}
#[Test]
public function it_exposes_the_connection(): void
{
$connection = new FakeConnection();
self::assertSame($connection, Orm::fromConnection($connection)->connection());
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit;
use Camelia\Orm\Pagination\Page;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class PageTest extends TestCase
{
#[Test]
public function it_computes_total_pages_as_int(): void
{
$page = Page::of([], 1, 10, 25);
self::assertSame(3, $page->totalPages);
self::assertIsInt($page->totalPages);
}
#[Test]
public function it_reports_next_and_prev(): void
{
$page = Page::of([], 2, 10, 25);
self::assertTrue($page->hasNext());
self::assertTrue($page->hasPrev());
}
#[Test]
public function it_does_not_report_next_on_the_last_page(): void
{
$page = Page::of([], 3, 10, 25);
self::assertFalse($page->hasNext());
}
#[Test]
public function it_clamps_invalid_pagination_inputs(): void
{
$page = Page::of([], 0, 5000, 10);
self::assertSame(1, $page->page);
self::assertSame(Page::MAX_PER_PAGE, $page->perPage);
}
#[Test]
public function it_serializes_in_snake_case(): void
{
$array = Page::of([], 1, 10, 3)->toArray();
self::assertSame(
['items', 'page', 'per_page', 'total', 'total_pages', 'has_next', 'has_prev'],
array_keys($array),
);
self::assertSame(1, $array['total_pages']);
}
}
+177
View File
@@ -0,0 +1,177 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit;
use Camelia\Orm\Exception\PartialModelException;
use Camelia\Orm\Exception\ValidationException;
use Camelia\Orm\Persistence\AuditListener;
use Camelia\Orm\Persistence\Persister;
use Camelia\Orm\Query\MySqlDialect;
use Camelia\Orm\Query\QueryBuilder;
use Camelia\Orm\Tests\Fixture\Usuario;
use Camelia\Orm\Tests\Support\FakeConnection;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class PersisterTest extends TestCase
{
private FakeConnection $connection;
private Persister $persister;
protected function setUp(): void
{
$this->connection = new FakeConnection();
$this->persister = new Persister($this->connection, new QueryBuilder(new MySqlDialect()));
}
#[Test]
public function it_inserts_and_assigns_the_generated_key(): void
{
$this->connection->lastInsertId = '42';
$usuario = (new Usuario())->hydrate(['nombre' => 'Ana', 'clave' => 'abc']);
$key = $this->persister->insert($usuario);
self::assertSame(42, $key);
self::assertSame(42, $usuario->codigo);
self::assertStringStartsWith('INSERT INTO `usuarios`', $this->connection->lastSql());
}
#[Test]
public function it_only_writes_writable_columns(): void
{
$this->connection->lastInsertId = '1';
$usuario = (new Usuario())->hydrate(['nombre' => 'Ana', 'clave' => 'abc']);
$this->persister->insert($usuario);
$sql = $this->connection->lastSql();
self::assertStringNotContainsString('`codigo`', $sql);
self::assertStringContainsString('`password_hash`', $sql);
}
#[Test]
public function it_saves_as_update_when_the_key_is_present(): void
{
$usuario = (new Usuario())->hydrate(['nombre' => 'Ana', 'clave' => 'abc']);
$usuario->codigo = 9;
$this->persister->save($usuario);
self::assertStringStartsWith('UPDATE `usuarios`', $this->connection->lastSql());
}
#[Test]
public function it_saves_as_insert_when_the_key_is_absent(): void
{
$this->connection->lastInsertId = '3';
$usuario = (new Usuario())->hydrate(['nombre' => 'Ana', 'clave' => 'abc']);
$this->persister->save($usuario);
self::assertStringStartsWith('INSERT INTO `usuarios`', $this->connection->lastSql());
}
#[Test]
public function it_refuses_an_invalid_model(): void
{
$this->expectException(ValidationException::class);
$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->codigo = 1;
$usuario->markPartial();
$this->expectException(PartialModelException::class);
$this->persister->update($usuario);
}
#[Test]
public function it_patches_only_the_given_columns(): void
{
$this->persister->patch(new Usuario(), 5, ['nombre' => 'Bea']);
self::assertSame(
'UPDATE `usuarios` SET `nombre` = ? WHERE `codigo` = ?',
$this->connection->lastSql(),
);
}
#[Test]
public function it_removes_by_primary_key(): void
{
$removed = $this->persister->remove(new Usuario(), 5);
self::assertTrue($removed);
self::assertSame('DELETE FROM `usuarios` WHERE `codigo` = ?', $this->connection->lastSql());
}
#[Test]
public function it_returns_false_when_nothing_was_removed(): void
{
$this->connection->affected = 0;
self::assertFalse($this->persister->remove(new Usuario(), 5));
}
#[Test]
public function it_notifies_the_audit_listener(): void
{
$listener = new class() implements AuditListener {
/** @var list<array{action: string, pk: int|string}> */
public array $calls = [];
public function onWrite(
string $table,
int|string $pk,
string $action,
?array $before,
array $after,
): void {
$this->calls[] = ['action' => $action, 'pk' => $pk];
}
};
$this->connection->lastInsertId = '7';
$persister = new Persister(
$this->connection,
new QueryBuilder(new MySqlDialect()),
$listener,
);
$persister->insert((new Usuario())->hydrate(['nombre' => 'Ana', 'clave' => 'abc']));
self::assertSame([['action' => 'insert', 'pk' => 7]], $listener->calls);
}
#[Test]
public function it_invokes_the_before_insert_hook(): void
{
$model = new \Camelia\Orm\Tests\Fixture\ConHooks();
$this->persister->insert($model);
self::assertSame('insert', $model->creadoPorHook);
}
#[Test]
public function it_invokes_the_before_update_hook(): void
{
$model = new \Camelia\Orm\Tests\Fixture\ConHooks();
$model->codigo = 3;
$this->persister->update($model);
self::assertSame('update', $model->creadoPorHook);
}
}
+148
View File
@@ -0,0 +1,148 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit\Query;
use Camelia\Orm\Exception\CriteriaException;
use Camelia\Orm\Metadata\MetadataFactory;
use Camelia\Orm\Query\Cond;
use Camelia\Orm\Query\CriteriaCompiler;
use Camelia\Orm\Query\MySqlDialect;
use Camelia\Orm\Tests\Fixture\Usuario;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class CriteriaCompilerTest extends TestCase
{
private CriteriaCompiler $compiler;
protected function setUp(): void
{
$this->compiler = new CriteriaCompiler(new MySqlDialect());
}
#[Test]
public function it_returns_an_empty_fragment_without_criteria(): void
{
[$sql, $params] = $this->compiler->compile($this->metadata(), []);
self::assertSame('', $sql);
self::assertSame([], $params);
}
#[Test]
public function it_compiles_scalar_equality(): void
{
[$sql, $params] = $this->compiler->compile($this->metadata(), ['activo' => true]);
self::assertSame('`activo` = ?', $sql);
self::assertSame([true], $params);
}
#[Test]
public function it_accepts_column_names_as_keys(): void
{
[$sql] = $this->compiler->compile($this->metadata(), ['password_hash' => 'x']);
self::assertSame('`password_hash` = ?', $sql);
}
#[Test]
public function it_compiles_arrays_as_in(): void
{
[$sql, $params] = $this->compiler->compile($this->metadata(), ['codigo' => [1, 2]]);
self::assertSame('`codigo` IN (?, ?)', $sql);
self::assertSame([1, 2], $params);
}
#[Test]
public function it_compiles_an_empty_array_as_always_false(): void
{
[$sql, $params] = $this->compiler->compile($this->metadata(), ['codigo' => []]);
self::assertSame('1 = 0', $sql);
self::assertSame([], $params);
}
#[Test]
public function it_compiles_null_as_is_null(): void
{
[$sql, $params] = $this->compiler->compile($this->metadata(), ['apodo' => null]);
self::assertSame('`apodo` IS NULL', $sql);
self::assertSame([], $params);
}
#[Test]
public function it_combines_criteria_with_and(): void
{
[$sql, $params] = $this->compiler->compile($this->metadata(), [
'activo' => true,
'nombre' => 'ana',
]);
self::assertSame('`activo` = ? AND `nombre` = ?', $sql);
self::assertSame([true, 'ana'], $params);
}
#[Test]
public function it_compiles_every_cond_operator(): void
{
$cases = [
['neq', Cond::neq(1), '`codigo` <> ?'],
['gt', Cond::gt(1), '`codigo` > ?'],
['gte', Cond::gte(1), '`codigo` >= ?'],
['lt', Cond::lt(1), '`codigo` < ?'],
['lte', Cond::lte(1), '`codigo` <= ?'],
['like', Cond::like('%a%'), '`codigo` LIKE ?'],
['notLike', Cond::notLike('%a%'), '`codigo` NOT LIKE ?'],
['between', Cond::between(1, 2), '`codigo` BETWEEN ? AND ?'],
['notBetween', Cond::notBetween(1, 2), '`codigo` NOT BETWEEN ? AND ?'],
['isNull', Cond::isNull(), '`codigo` IS NULL'],
['isNotNull', Cond::isNotNull(), '`codigo` IS NOT NULL'],
['in', Cond::in([1, 2]), '`codigo` IN (?, ?)'],
['notIn', Cond::notIn([1, 2]), '`codigo` NOT IN (?, ?)'],
];
foreach ($cases as [$label, $cond, $expected]) {
[$sql] = $this->compiler->compile($this->metadata(), ['codigo' => $cond]);
self::assertSame($expected, $sql, $label);
}
}
#[Test]
public function it_compiles_raw_conditions(): void
{
[$sql, $params] =
$this->compiler->compile($this->metadata(), ['codigo' => Cond::raw('codigo > ?', [
10,
])]);
self::assertSame('(codigo > ?)', $sql);
self::assertSame([10], $params);
}
#[Test]
public function it_rejects_an_unknown_column_naming_the_valid_ones(): void
{
$this->expectException(CriteriaException::class);
$this->expectExceptionMessage('Unknown column "inexistente"');
$this->compiler->compile($this->metadata(), ['inexistente' => 1]);
}
#[Test]
public function it_rejects_an_empty_in_cond(): void
{
$this->expectException(CriteriaException::class);
$this->compiler->compile($this->metadata(), ['codigo' => Cond::in([])]);
}
private function metadata(): \Camelia\Orm\Metadata\ClassMetadata
{
return (new MetadataFactory())->forClass(Usuario::class);
}
}
+161
View File
@@ -0,0 +1,161 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit\Query;
use Camelia\Orm\Exception\CriteriaException;
use Camelia\Orm\Metadata\ClassMetadata;
use Camelia\Orm\Metadata\MetadataFactory;
use Camelia\Orm\Query\MySqlDialect;
use Camelia\Orm\Query\QueryBuilder;
use Camelia\Orm\Tests\Fixture\Factura;
use Camelia\Orm\Tests\Fixture\Usuario;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class QueryBuilderTest extends TestCase
{
private QueryBuilder $builder;
private ClassMetadata $usuarios;
protected function setUp(): void
{
$this->builder = new QueryBuilder(new MySqlDialect());
$this->usuarios = (new MetadataFactory())->forClass(Usuario::class);
}
#[Test]
public function it_selects_every_non_relation_column(): void
{
$compiled = $this->builder->select($this->usuarios, []);
self::assertSame(
'SELECT `codigo`, `nombre`, `correo`, `password_hash`, `activo`, `apodo`, `clave`'
. ' FROM `usuarios`',
$compiled['sql'],
);
self::assertSame([], $compiled['params']);
}
#[Test]
public function it_excludes_relations_from_the_select_list(): void
{
$metadata = (new MetadataFactory())->forClass(Factura::class);
$compiled = $this->builder->select($metadata, []);
self::assertStringNotContainsString('`usuario`', $compiled['sql']);
self::assertStringNotContainsString('`detalles`', $compiled['sql']);
}
#[Test]
public function it_adds_where_order_and_limit(): void
{
$compiled = $this->builder->select(
$this->usuarios,
['activo' => true],
[['nombre', 'ASC']],
10,
20,
);
self::assertSame(
'SELECT `codigo`, `nombre`, `correo`, `password_hash`, `activo`, `apodo`, `clave`'
. ' FROM `usuarios` WHERE `activo` = ?'
. ' ORDER BY `usuarios`.`nombre` ASC LIMIT 10 OFFSET 20',
$compiled['sql'],
);
self::assertSame([true], $compiled['params']);
}
#[Test]
public function it_rejects_an_invalid_order_direction(): void
{
$this->expectException(CriteriaException::class);
/** @phpstan-ignore-next-line intentionally invalid direction to prove runtime validation */
$this->builder->select($this->usuarios, [], [['nombre', 'SIDEWAYS']]);
}
#[Test]
public function it_restricts_selected_columns_when_asked(): void
{
$compiled = $this->builder->select(
$this->usuarios,
[],
[],
null,
null,
['codigo', 'nombre'],
);
self::assertStringContainsString('SELECT `codigo`, `nombre` FROM', $compiled['sql']);
}
#[Test]
public function it_compiles_count(): void
{
$compiled = $this->builder->count($this->usuarios, ['activo' => 1]);
self::assertSame(
'SELECT COUNT(*) AS aggregate FROM `usuarios` WHERE `activo` = ?',
$compiled['sql'],
);
self::assertSame([1], $compiled['params']);
}
#[Test]
public function it_compiles_aggregates(): void
{
$compiled = $this->builder->aggregate($this->usuarios, 'codigo', 'MAX', []);
self::assertSame('SELECT MAX(`codigo`) AS aggregate FROM `usuarios`', $compiled['sql']);
}
#[Test]
public function it_compiles_insert(): void
{
$compiled = $this->builder->insert($this->usuarios, ['nombre' => 'Ana', 'activo' => true]);
self::assertSame(
'INSERT INTO `usuarios` (`nombre`, `activo`) VALUES (?, ?)',
$compiled['sql'],
);
self::assertSame(['Ana', true], $compiled['params']);
}
#[Test]
public function it_compiles_update(): void
{
$compiled = $this->builder->update($this->usuarios, ['nombre' => 'Ana'], 7);
self::assertSame('UPDATE `usuarios` SET `nombre` = ? WHERE `codigo` = ?', $compiled['sql']);
self::assertSame(['Ana', 7], $compiled['params']);
}
#[Test]
public function it_compiles_delete(): void
{
$compiled = $this->builder->delete($this->usuarios, 7);
self::assertSame('DELETE FROM `usuarios` WHERE `codigo` = ?', $compiled['sql']);
self::assertSame([7], $compiled['params']);
}
#[Test]
public function it_refuses_an_empty_insert(): void
{
$this->expectException(CriteriaException::class);
$this->builder->insert($this->usuarios, []);
}
#[Test]
public function it_refuses_an_empty_update(): void
{
$this->expectException(CriteriaException::class);
$this->builder->update($this->usuarios, [], 1);
}
}
+176
View File
@@ -0,0 +1,176 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit;
use Camelia\Orm\Query\Cond;
use Camelia\Orm\Query\GroupCond;
use Camelia\Orm\Repository;
use Camelia\Orm\Tests\Fixture\Usuario;
use Camelia\Orm\Tests\Support\FakeConnection;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class QueryTest extends TestCase
{
private FakeConnection $connection;
protected function setUp(): void
{
$this->connection = new FakeConnection();
}
#[Test]
public function it_builds_a_select_with_where(): void
{
$sql = $this->repository(Usuario::class)->query()->where('activo', true)->toSql();
self::assertStringContainsString('WHERE (`activo` = ?)', $sql['sql']);
self::assertSame([true], $sql['params']);
}
#[Test]
public function it_is_immutable(): void
{
$base = $this->repository(Usuario::class)->query()->where('activo', true);
$derived = $base->where('nombre', 'Ana');
self::assertCount(1, $base->toSql()['params']);
self::assertCount(2, $derived->toSql()['params']);
}
#[Test]
public function it_places_where_before_order_and_limit(): void
{
$sql = $this->repository(Usuario::class)
->query()
->where('activo', true)
->orderByDesc('nombre')
->limit(5)
->toSql()['sql'];
self::assertStringContainsString('WHERE (`activo` = ?) ORDER BY', $sql);
self::assertStringContainsString('LIMIT 5', $sql);
}
#[Test]
public function it_builds_or_groups(): void
{
$sql = $this->repository(Usuario::class)
->query()
->whereGroup(static function (GroupCond $group): void {
$group->or('nombre', 'Ana');
$group->or('nombre', 'Bea');
})
->toSql();
self::assertStringContainsString('WHERE (`nombre` = ? OR `nombre` = ?)', $sql['sql']);
self::assertCount(2, $sql['params']);
}
#[Test]
public function it_combines_groups_with_and(): void
{
$sql = $this->repository(Usuario::class)
->query()
->where('activo', true)
->whereGroup(static function (GroupCond $group): void {
$group->or('nombre', 'Ana');
})
->toSql()['sql'];
self::assertStringContainsString('(`activo` = ?) AND', $sql);
}
#[Test]
public function it_supports_where_in_and_null_helpers(): void
{
$sql = $this->repository(Usuario::class)
->query()
->whereIn('codigo', [1, 2])
->whereNull('apodo')
->toSql();
self::assertStringContainsString('`codigo` IN (?, ?)', $sql['sql']);
self::assertStringContainsString('`apodo` IS NULL', $sql['sql']);
self::assertSame([1, 2], $sql['params']);
}
#[Test]
public function it_plucks_a_single_column(): void
{
$this->connection->rows = [['nombre' => 'Ana'], ['nombre' => 'Bea']];
$values = $this->repository(Usuario::class)->query()->pluck('nombre');
self::assertSame(['Ana', 'Bea'], $values);
self::assertStringContainsString(
'SELECT `nombre` FROM',
$this->connection->selected[0]['sql'],
);
}
#[Test]
public function it_counts(): void
{
$this->connection->scalars = [4];
self::assertSame(
4,
$this->repository(Usuario::class)->query()->where('activo', true)->count(),
);
}
#[Test]
public function it_returns_the_first_row_or_null(): void
{
$this->connection->rows = [];
self::assertNull($this->repository(Usuario::class)->query()->first());
}
#[Test]
public function it_fails_first_or_fail_when_empty(): void
{
$this->connection->rows = [];
$this->expectException(\Camelia\Orm\Exception\RecordNotFoundException::class);
$this->repository(Usuario::class)->query()->firstOrFail();
}
#[Test]
public function it_pages(): void
{
$this->connection->scalars = [0];
$this->connection->rows = [];
$page = $this->repository(Usuario::class)->query()->page(2, 5);
self::assertSame(2, $page->page);
self::assertSame(0, $page->total);
self::assertStringContainsString('LIMIT 5 OFFSET 5', $this->connection->selected[1]['sql']);
}
#[Test]
public function it_accepts_a_cond_in_where(): void
{
$sql = $this->repository(Usuario::class)
->query()
->where('codigo', Cond::between(1, 9))
->toSql();
self::assertStringContainsString('BETWEEN ? AND ?', $sql['sql']);
self::assertSame([1, 9], $sql['params']);
}
/**
* @param class-string<\Camelia\Orm\Model> $class
* @return Repository<\Camelia\Orm\Model>
*/
private function repository(string $class): Repository
{
return new Repository($this->connection, $class);
}
}
+234
View File
@@ -0,0 +1,234 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit;
use Camelia\Orm\Exception\RecordNotFoundException;
use Camelia\Orm\Pagination\Page;
use Camelia\Orm\Query\Cond;
use Camelia\Orm\Repository;
use Camelia\Orm\Tests\Fixture\Factura;
use Camelia\Orm\Tests\Fixture\Usuario;
use Camelia\Orm\Tests\Support\FakeConnection;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class RepositoryTest extends TestCase
{
private FakeConnection $connection;
protected function setUp(): void
{
$this->connection = new FakeConnection();
}
#[Test]
public function it_hydrates_rows_into_models(): void
{
$this->connection->rows = [
[
'codigo' => '5',
'nombre' => 'Ana',
'correo' => 'a@x',
'password_hash' => 'h',
'activo' => '1',
'apodo' => null,
'clave' => 'k',
],
];
$result = $this->repository(Usuario::class)->find();
self::assertCount(1, $result);
$usuario = $result[0];
self::assertInstanceOf(Usuario::class, $usuario);
self::assertSame(5, $usuario->codigo);
self::assertSame('Ana', $usuario->nombre);
self::assertTrue($usuario->activo);
}
#[Test]
public function it_returns_null_when_find_first_matches_nothing(): void
{
$this->connection->rows = [];
self::assertNull($this->repository(Usuario::class)->findFirst());
}
#[Test]
public function it_throws_when_find_by_pk_fails(): void
{
$this->connection->rows = [];
$this->expectException(RecordNotFoundException::class);
$this->repository(Usuario::class)->findByPkOrFail(99);
}
#[Test]
public function it_finds_by_primary_key_through_a_delegated_criteria(): void
{
$this->connection->rows = [];
$this->repository(Usuario::class)->findByPk(4);
self::assertStringContainsString(
'WHERE `codigo` = ?',
$this->connection->selected[0]['sql'],
);
self::assertSame([4], $this->connection->selected[0]['params']);
}
#[Test]
public function it_counts_through_a_scalar_query(): void
{
$this->connection->scalars = [7];
self::assertSame(7, $this->repository(Usuario::class)->count(['activo' => true]));
}
#[Test]
public function it_reports_existence(): void
{
$this->connection->scalars = [1];
self::assertTrue($this->repository(Usuario::class)->exists(['activo' => true]));
}
#[Test]
public function it_aggregates(): void
{
$this->connection->scalars = [10.5, null];
self::assertSame(10.5, $this->repository(Usuario::class)->sum('codigo'));
self::assertNull($this->repository(Usuario::class)->max('codigo'));
}
#[Test]
public function it_pages_with_total_and_items(): void
{
$this->connection->scalars = [3];
$this->connection->rows = [
[
'codigo' => '1',
'nombre' => 'A',
'correo' => '',
'password_hash' => '',
'activo' => '1',
'apodo' => null,
'clave' => '',
],
];
$page = $this->repository(Usuario::class)->page(
['activo' => true],
[['nombre', 'DESC']],
1,
2,
);
self::assertInstanceOf(Page::class, $page);
self::assertSame(3, $page->total);
self::assertSame(2, $page->totalPages);
self::assertCount(1, $page->items);
}
#[Test]
public function it_creates_a_model_and_inserts_it(): void
{
$this->connection->lastInsertId = '9';
$usuario = $this->repository(Usuario::class)->create(['nombre' => 'Ana', 'clave' => 'abc']);
self::assertInstanceOf(Usuario::class, $usuario);
self::assertSame(9, $usuario->codigo);
self::assertStringStartsWith('INSERT INTO `usuarios`', $this->connection->lastSql());
}
#[Test]
public function it_finds_or_creates(): void
{
$this->connection->rows = [];
$this->connection->lastInsertId = '11';
$usuario = $this->repository(Usuario::class)->findOrCreate(['correo' => 'a@x'], [
'nombre' => 'Ana',
'clave' => 'abc',
]);
self::assertInstanceOf(Usuario::class, $usuario);
self::assertSame('a@x', $usuario->correo);
self::assertSame(11, $usuario->codigo);
}
#[Test]
public function it_loads_a_belongs_to_relation_in_one_query(): void
{
$this->connection->rows = [$this->usuarioRow(7, 'Ana')];
$facturaList = $this->repository(Factura::class)->find(with: ['usuario']);
self::assertCount(1, $facturaList);
}
#[Test]
public function it_marks_models_partial_when_selecting_columns(): void
{
$this->connection->rows = [['codigo' => '1', 'nombre' => 'Ana']];
$result = $this->repository(Usuario::class)->query()->select('codigo', 'nombre')->get();
self::assertTrue($result[0]->isPartial());
}
#[Test]
public function it_rejects_an_unknown_relation(): void
{
$this->connection->rows = [];
$this->expectException(\Camelia\Orm\Exception\MetadataException::class);
$this->repository(Usuario::class)->find(with: ['inexistente']);
}
#[Test]
public function it_binds_params_in_criteria_order(): void
{
$this->connection->rows = [];
$this->repository(Usuario::class)->find(['activo' => true, 'codigo' => Cond::in([1, 2])]);
self::assertSame([true, 1, 2], $this->connection->selected[0]['params']);
self::assertSame(
'SELECT `codigo`, `nombre`, `correo`, `password_hash`, `activo`, `apodo`, `clave`'
. ' FROM `usuarios` WHERE `activo` = ? AND `codigo` IN (?, ?)',
$this->connection->selected[0]['sql'],
);
}
/**
* @param class-string<\Camelia\Orm\Model> $class
* @return Repository<\Camelia\Orm\Model>
*/
private function repository(string $class): Repository
{
return new Repository($this->connection, $class);
}
/**
* @return array<string, mixed>
*/
private function usuarioRow(int $codigo, string $nombre): array
{
return [
'codigo' => (string) $codigo,
'nombre' => $nombre,
'correo' => 'a@x',
'password_hash' => '',
'activo' => '1',
'apodo' => null,
'clave' => '',
];
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit\Support;
use Camelia\Orm\Support\NameConverter;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class NameConverterTest extends TestCase
{
#[Test]
public function it_converts_internal_capitals_to_underscores(): void
{
self::assertSame('codigo_empresa', NameConverter::camelToSnake('codigoEmpresa'));
self::assertSame('id_zona', NameConverter::camelToSnake('idZona'));
self::assertSame('normal', NameConverter::camelToSnake('normal'));
self::assertSame('', NameConverter::camelToSnake(''));
}
#[Test]
public function it_never_prefixes_the_first_character(): void
{
self::assertSame('nombre', NameConverter::camelToSnake('Nombre'));
}
#[Test]
public function it_round_trips_simple_names(): void
{
self::assertSame('codigoEmpresa', NameConverter::snakeToCamel('codigo_empresa'));
}
}
+104
View File
@@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Tests\Unit\Support;
use Camelia\Orm\Support\TypeCaster;
use DateTimeImmutable;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class TypeCasterTest extends TestCase
{
#[Test]
public function it_casts_numeric_values_to_int(): void
{
self::assertSame(42, TypeCaster::cast('42', 'int', false));
self::assertSame(1, TypeCaster::cast(true, 'int', false));
}
#[Test]
public function it_casts_boolean_representations(): void
{
self::assertTrue(TypeCaster::cast('true', 'bool', false));
self::assertFalse(TypeCaster::cast('false', 'bool', false));
self::assertTrue(TypeCaster::cast(1, 'bool', false));
self::assertFalse(TypeCaster::cast('0', 'bool', false));
}
#[Test]
public function it_decodes_json_strings_into_arrays(): void
{
self::assertSame(['a' => 1], TypeCaster::cast('{"a":1}', 'array', false));
}
#[Test]
public function it_casts_dates(): void
{
$value = TypeCaster::cast('2024-01-15', DateTimeImmutable::class, false);
self::assertInstanceOf(DateTimeImmutable::class, $value);
self::assertSame('2024-01-15', $value->format('Y-m-d'));
}
#[Test]
public function it_keeps_null_for_nullable_properties(): void
{
self::assertNull(TypeCaster::cast(null, 'int', true));
}
/**
* @return array<string, array{0: mixed, 1: string}>
*/
public static function refusals(): array
{
return [
'int from text' => ['abc', 'int'],
'float from text' => ['abc', 'float'],
'bool from text' => ['quizas', 'bool'],
'array from text' => ['no json', 'array'],
'date from text' => ['no es fecha', DateTimeImmutable::class],
];
}
#[Test]
#[DataProvider('refusals')]
public function it_refuses_values_it_cannot_cast(mixed $value, string $type): void
{
$this->expectException(\InvalidArgumentException::class);
TypeCaster::cast($value, $type, false);
}
#[Test]
public function it_refuses_null_on_a_non_nullable_type(): void
{
$this->expectException(\InvalidArgumentException::class);
TypeCaster::cast(null, 'int', false);
}
#[Test]
public function it_serializes_dates_as_atom_strings(): void
{
self::assertSame(
'2024-01-15T00:00:00+00:00',
TypeCaster::toSerializable(
new DateTimeImmutable('2024-01-15', new \DateTimeZone('UTC')),
),
);
}
#[Test]
public function it_stores_dates_as_datetime_strings(): void
{
self::assertSame(
'2024-01-15 00:00:00',
TypeCaster::toDatabaseValue(
new DateTimeImmutable('2024-01-15', new \DateTimeZone('UTC')),
),
);
}
}