From 66e93e30705db6dfcecdfcad57166f0ab2d8b721 Mon Sep 17 00:00:00 2001 From: Dario Garcia Date: Sun, 15 Nov 2026 10:14:22 -0300 Subject: [PATCH] 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. --- .gitignore | 6 + AGENTS.md | 74 + CHANGELOG.md | 29 + LICENSE | 21 + README.md | 148 ++ composer.json | 75 + composer.lock | 2027 +++++++++++++++++ docs/GUIA-PROGRAMADOR.md | 1099 +++++++++ especificaciones-orm.md | 1082 +++++++++ mago-baseline.toml | 361 +++ mago.toml | 113 + phpstan.neon | 12 + phpunit.integration.xml.dist | 17 + phpunit.xml.dist | 20 + src/Attribute/AutoIncrement.php | 11 + src/Attribute/BelongsTo.php | 20 + src/Attribute/BelongsToMany.php | 22 + src/Attribute/Column.php | 16 + src/Attribute/Enum.php | 17 + src/Attribute/Guarded.php | 11 + src/Attribute/HasMany.php | 20 + src/Attribute/HasOne.php | 20 + src/Attribute/Ignore.php | 13 + src/Attribute/Index.php | 16 + src/Attribute/Length.php | 16 + src/Attribute/MaxLength.php | 16 + src/Attribute/Nullable.php | 11 + src/Attribute/Precision.php | 17 + src/Attribute/PrimaryKey.php | 11 + src/Attribute/Required.php | 11 + src/Attribute/TableName.php | 16 + src/Attribute/Unique.php | 11 + src/Attribute/UniqueGroup.php | 16 + src/Connection/Connection.php | 47 + src/Connection/ConnectionFactory.php | 117 + src/Connection/PdoConnection.php | 213 ++ src/Exception/ConfigurationException.php | 41 + src/Exception/CriteriaException.php | 34 + src/Exception/DatabaseException.php | 72 + src/Exception/DuplicateKeyException.php | 10 + .../ForeignKeyViolationException.php | 10 + src/Exception/LockTimeoutException.php | 10 + src/Exception/MetadataException.php | 110 + src/Exception/OrmException.php | 10 + src/Exception/PartialModelException.php | 21 + src/Exception/RecordNotFoundException.php | 21 + src/Exception/ValidationException.php | 41 + src/Metadata/ClassMetadata.php | 151 ++ src/Metadata/Constraint.php | 24 + src/Metadata/MetadataCache.php | 33 + src/Metadata/MetadataFactory.php | 286 +++ src/Metadata/PropertyMetadata.php | 60 + src/Metadata/RelationMetadata.php | 33 + src/Model.php | 380 +++ src/Orm.php | 153 ++ src/Pagination/Page.php | 92 + src/Persistence/AuditListener.php | 27 + src/Persistence/Persister.php | 312 +++ src/Persistence/Validator.php | 63 + src/Query/Cond.php | 122 + src/Query/CriteriaCompiler.php | 103 + src/Query/Dialect.php | 25 + src/Query/GroupCond.php | 44 + src/Query/MySqlDialect.php | 96 + src/Query/Query.php | 403 ++++ src/Query/QueryBuilder.php | 260 +++ src/Query/QueryState.php | 103 + src/Repository.php | 783 +++++++ src/Support/Clock.php | 15 + src/Support/NameConverter.php | 53 + src/Support/SystemClock.php | 18 + src/Support/TypeCaster.php | 336 +++ tests/Fixture/Articulo.php | 29 + tests/Fixture/ConHooks.php | 31 + tests/Fixture/Detalle.php | 21 + tests/Fixture/Etiqueta.php | 34 + tests/Fixture/Factura.php | 32 + tests/Fixture/Invalid/ColumnaDuplicada.php | 22 + tests/Fixture/Invalid/DosPrimaryKeys.php | 19 + tests/Fixture/Invalid/RelacionNoNulable.php | 21 + tests/Fixture/Invalid/SinPrimaryKey.php | 14 + tests/Fixture/Invalid/SinTableName.php | 14 + tests/Fixture/Invalid/SinTipo.php | 18 + tests/Fixture/Usuario.php | 35 + tests/Support/FakeConnection.php | 119 + tests/Unit/EagerLoadingTest.php | 205 ++ tests/Unit/Metadata/MetadataFactoryTest.php | 139 ++ tests/Unit/ModelTest.php | 166 ++ tests/Unit/OrmTest.php | 70 + tests/Unit/PageTest.php | 59 + tests/Unit/PersisterTest.php | 177 ++ tests/Unit/Query/CriteriaCompilerTest.php | 148 ++ tests/Unit/Query/QueryBuilderTest.php | 161 ++ tests/Unit/QueryTest.php | 176 ++ tests/Unit/RepositoryTest.php | 234 ++ tests/Unit/Support/NameConverterTest.php | 33 + tests/Unit/Support/TypeCasterTest.php | 104 + 97 files changed, 12188 insertions(+) create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 CHANGELOG.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 composer.json create mode 100644 composer.lock create mode 100644 docs/GUIA-PROGRAMADOR.md create mode 100644 especificaciones-orm.md create mode 100644 mago-baseline.toml create mode 100644 mago.toml create mode 100644 phpstan.neon create mode 100644 phpunit.integration.xml.dist create mode 100644 phpunit.xml.dist create mode 100644 src/Attribute/AutoIncrement.php create mode 100644 src/Attribute/BelongsTo.php create mode 100644 src/Attribute/BelongsToMany.php create mode 100644 src/Attribute/Column.php create mode 100644 src/Attribute/Enum.php create mode 100644 src/Attribute/Guarded.php create mode 100644 src/Attribute/HasMany.php create mode 100644 src/Attribute/HasOne.php create mode 100644 src/Attribute/Ignore.php create mode 100644 src/Attribute/Index.php create mode 100644 src/Attribute/Length.php create mode 100644 src/Attribute/MaxLength.php create mode 100644 src/Attribute/Nullable.php create mode 100644 src/Attribute/Precision.php create mode 100644 src/Attribute/PrimaryKey.php create mode 100644 src/Attribute/Required.php create mode 100644 src/Attribute/TableName.php create mode 100644 src/Attribute/Unique.php create mode 100644 src/Attribute/UniqueGroup.php create mode 100644 src/Connection/Connection.php create mode 100644 src/Connection/ConnectionFactory.php create mode 100644 src/Connection/PdoConnection.php create mode 100644 src/Exception/ConfigurationException.php create mode 100644 src/Exception/CriteriaException.php create mode 100644 src/Exception/DatabaseException.php create mode 100644 src/Exception/DuplicateKeyException.php create mode 100644 src/Exception/ForeignKeyViolationException.php create mode 100644 src/Exception/LockTimeoutException.php create mode 100644 src/Exception/MetadataException.php create mode 100644 src/Exception/OrmException.php create mode 100644 src/Exception/PartialModelException.php create mode 100644 src/Exception/RecordNotFoundException.php create mode 100644 src/Exception/ValidationException.php create mode 100644 src/Metadata/ClassMetadata.php create mode 100644 src/Metadata/Constraint.php create mode 100644 src/Metadata/MetadataCache.php create mode 100644 src/Metadata/MetadataFactory.php create mode 100644 src/Metadata/PropertyMetadata.php create mode 100644 src/Metadata/RelationMetadata.php create mode 100644 src/Model.php create mode 100644 src/Orm.php create mode 100644 src/Pagination/Page.php create mode 100644 src/Persistence/AuditListener.php create mode 100644 src/Persistence/Persister.php create mode 100644 src/Persistence/Validator.php create mode 100644 src/Query/Cond.php create mode 100644 src/Query/CriteriaCompiler.php create mode 100644 src/Query/Dialect.php create mode 100644 src/Query/GroupCond.php create mode 100644 src/Query/MySqlDialect.php create mode 100644 src/Query/Query.php create mode 100644 src/Query/QueryBuilder.php create mode 100644 src/Query/QueryState.php create mode 100644 src/Repository.php create mode 100644 src/Support/Clock.php create mode 100644 src/Support/NameConverter.php create mode 100644 src/Support/SystemClock.php create mode 100644 src/Support/TypeCaster.php create mode 100644 tests/Fixture/Articulo.php create mode 100644 tests/Fixture/ConHooks.php create mode 100644 tests/Fixture/Detalle.php create mode 100644 tests/Fixture/Etiqueta.php create mode 100644 tests/Fixture/Factura.php create mode 100644 tests/Fixture/Invalid/ColumnaDuplicada.php create mode 100644 tests/Fixture/Invalid/DosPrimaryKeys.php create mode 100644 tests/Fixture/Invalid/RelacionNoNulable.php create mode 100644 tests/Fixture/Invalid/SinPrimaryKey.php create mode 100644 tests/Fixture/Invalid/SinTableName.php create mode 100644 tests/Fixture/Invalid/SinTipo.php create mode 100644 tests/Fixture/Usuario.php create mode 100644 tests/Support/FakeConnection.php create mode 100644 tests/Unit/EagerLoadingTest.php create mode 100644 tests/Unit/Metadata/MetadataFactoryTest.php create mode 100644 tests/Unit/ModelTest.php create mode 100644 tests/Unit/OrmTest.php create mode 100644 tests/Unit/PageTest.php create mode 100644 tests/Unit/PersisterTest.php create mode 100644 tests/Unit/Query/CriteriaCompilerTest.php create mode 100644 tests/Unit/Query/QueryBuilderTest.php create mode 100644 tests/Unit/QueryTest.php create mode 100644 tests/Unit/RepositoryTest.php create mode 100644 tests/Unit/Support/NameConverterTest.php create mode 100644 tests/Unit/Support/TypeCasterTest.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..967172e --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/vendor/ +.phpunit.cache/ +.phpunit.cache.integration/ +.phpunit.result.cache +.mago.cache +coverage/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..34efc07 --- /dev/null +++ b/AGENTS.md @@ -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`. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..6149bc4 --- /dev/null +++ b/CHANGELOG.md @@ -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. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5082191 --- /dev/null +++ b/LICENSE @@ -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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..5de61a8 --- /dev/null +++ b/README.md @@ -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). + diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..d62e01b --- /dev/null +++ b/composer.json @@ -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" + } + } +} diff --git a/composer.lock b/composer.lock new file mode 100644 index 0000000..fae0311 --- /dev/null +++ b/composer.lock @@ -0,0 +1,2027 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "995f47882c4069e4904f4637e3219078", + "packages": [ + { + "name": "psr/log", + "version": "3.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/fe5ea303b0887d5caefd3d431c3e61ad47037001", + "reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "support": { + "source": "https://github.com/php-fig/log/tree/3.0.0" + }, + "time": "2021-07-14T16:46:02+00:00" + } + ], + "packages-dev": [ + { + "name": "carthage-software/mago", + "version": "1.60.1", + "source": { + "type": "git", + "url": "https://github.com/carthage-software/mago.git", + "reference": "4f64a85e4b4c5632eae895a8d8564898ffcaec6e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/carthage-software/mago/zipball/4f64a85e4b4c5632eae895a8d8564898ffcaec6e", + "reference": "4f64a85e4b4c5632eae895a8d8564898ffcaec6e", + "shasum": "" + }, + "require": { + "php": "~8.1 || ~8.2 || ~8.3 || ~8.4 || ~8.5 || ~8.6", + "revolt/event-loop": "^1.0.9" + }, + "require-dev": { + "phpunit/phpunit": "^10.5", + "twig/twig": "^3.30" + }, + "suggest": { + "ext-curl": "To show binary download progress" + }, + "bin": [ + "composer/bin/mago" + ], + "type": "library", + "autoload": { + "files": [ + "composer/src/functions.php", + "composer/src/internal.php" + ], + "psr-4": { + "Mago\\": "composer/src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT OR Apache-2.0" + ], + "authors": [ + { + "name": "Seifeddine Gmati", + "email": "azjezz@carthage.software" + } + ], + "description": "Mago is a toolchain for PHP that aims to provide a set of tools to help developers write better code.", + "keywords": [ + "dev" + ], + "support": { + "issues": "https://github.com/carthage-software/mago/issues", + "source": "https://github.com/carthage-software/mago/tree/1.60.1" + }, + "funding": [ + { + "url": "https://github.com/azjezz", + "type": "github" + } + ], + "time": "2026-11-15T03:04:38+00:00" + }, + { + "name": "myclabs/deep-copy", + "version": "1.14.0", + "source": { + "type": "git", + "url": "https://github.com/myclabs/DeepCopy.git", + "reference": "8680aa248f8e07bc8fb43f56f0f5fc77a0c96aae" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/8680aa248f8e07bc8fb43f56f0f5fc77a0c96aae", + "reference": "8680aa248f8e07bc8fb43f56f0f5fc77a0c96aae", + "shasum": "" + }, + "require": { + "php": "^8.0" + }, + "conflict": { + "doctrine/collections": "<1.6.8", + "doctrine/common": "<2.13.3 || >=3 <3.2.2" + }, + "require-dev": { + "doctrine/collections": "^1.6.8", + "doctrine/common": "^2.13.3 || ^3.2.2", + "phpspec/prophecy": "^1.10", + "phpunit/phpunit": "^7.5.20 || ^8.5.23 || ^9.5.13" + }, + "type": "library", + "autoload": { + "files": [ + "src/DeepCopy/deep_copy.php" + ], + "psr-4": { + "DeepCopy\\": "src/DeepCopy/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Create deep copies (clones) of your objects", + "keywords": [ + "clone", + "copy", + "duplicate", + "object", + "object graph" + ], + "support": { + "issues": "https://github.com/myclabs/DeepCopy/issues", + "source": "https://github.com/myclabs/DeepCopy/tree/1.14.0" + }, + "funding": [ + { + "url": "https://github.com/mnapoli", + "type": "github" + } + ], + "time": "2026-08-11T10:17:44+00:00" + }, + { + "name": "nikic/php-parser", + "version": "v5.9.0", + "source": { + "type": "git", + "url": "https://github.com/nikic/PHP-Parser.git", + "reference": "9e33da9553fe7786f0962b35f4e4ecf01be89def" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/9e33da9553fe7786f0962b35f4e4ecf01be89def", + "reference": "9e33da9553fe7786f0962b35f4e4ecf01be89def", + "shasum": "" + }, + "require": { + "ext-json": "*", + "ext-tokenizer": "*", + "php": ">=7.4" + }, + "require-dev": { + "ircmaxell/php-yacc": "^0.0.7", + "phpunit/phpunit": "^9.0" + }, + "bin": [ + "bin/php-parse" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "5.x-dev" + } + }, + "autoload": { + "psr-4": { + "PhpParser\\": "lib/PhpParser" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov" + } + ], + "description": "A PHP parser written in PHP", + "keywords": [ + "parser", + "php" + ], + "support": { + "issues": "https://github.com/nikic/PHP-Parser/issues", + "source": "https://github.com/nikic/PHP-Parser/tree/v5.9.0" + }, + "time": "2026-09-13T18:51:52+00:00" + }, + { + "name": "phar-io/manifest", + "version": "2.0.4", + "source": { + "type": "git", + "url": "https://github.com/phar-io/manifest.git", + "reference": "54750ef60c58e43759730615a392c31c80e23176" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phar-io/manifest/zipball/54750ef60c58e43759730615a392c31c80e23176", + "reference": "54750ef60c58e43759730615a392c31c80e23176", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-libxml": "*", + "ext-phar": "*", + "ext-xmlwriter": "*", + "phar-io/version": "^3.0.1", + "php": "^7.2 || ^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + }, + { + "name": "Sebastian Heuer", + "email": "sebastian@phpeople.de", + "role": "Developer" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "Developer" + } + ], + "description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)", + "support": { + "issues": "https://github.com/phar-io/manifest/issues", + "source": "https://github.com/phar-io/manifest/tree/2.0.4" + }, + "funding": [ + { + "url": "https://github.com/theseer", + "type": "github" + } + ], + "time": "2024-03-03T12:33:53+00:00" + }, + { + "name": "phar-io/version", + "version": "3.2.1", + "source": { + "type": "git", + "url": "https://github.com/phar-io/version.git", + "reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phar-io/version/zipball/4f7fd7836c6f332bb2933569e566a0d6c4cbed74", + "reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + }, + { + "name": "Sebastian Heuer", + "email": "sebastian@phpeople.de", + "role": "Developer" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "Developer" + } + ], + "description": "Library for handling version information and constraints", + "support": { + "issues": "https://github.com/phar-io/version/issues", + "source": "https://github.com/phar-io/version/tree/3.2.1" + }, + "time": "2022-02-21T01:04:05+00:00" + }, + { + "name": "phpstan/phpstan", + "version": "1.12.34", + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/4dd89ca7aa30fdc6760be21550d583bcc32e8476", + "reference": "4dd89ca7aa30fdc6760be21550d583bcc32e8476", + "shasum": "" + }, + "require": { + "php": "^7.2|^8.0" + }, + "conflict": { + "phpstan/phpstan-shim": "*" + }, + "bin": [ + "phpstan", + "phpstan.phar" + ], + "type": "library", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPStan - PHP Static Analysis Tool", + "keywords": [ + "dev", + "static analysis" + ], + "support": { + "docs": "https://phpstan.org/user-guide/getting-started", + "forum": "https://github.com/phpstan/phpstan/discussions", + "issues": "https://github.com/phpstan/phpstan/issues", + "security": "https://github.com/phpstan/phpstan/security/policy", + "source": "https://github.com/phpstan/phpstan-src" + }, + "funding": [ + { + "url": "https://github.com/ondrejmirtes", + "type": "github" + }, + { + "url": "https://github.com/phpstan", + "type": "github" + } + ], + "time": "2026-07-28T10:04:39+00:00" + }, + { + "name": "phpunit/php-code-coverage", + "version": "11.0.12", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-code-coverage.git", + "reference": "2c1ed04922802c15e1de5d7447b4856de949cf56" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/2c1ed04922802c15e1de5d7447b4856de949cf56", + "reference": "2c1ed04922802c15e1de5d7447b4856de949cf56", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-libxml": "*", + "ext-xmlwriter": "*", + "nikic/php-parser": "^5.7.0", + "php": ">=8.2", + "phpunit/php-file-iterator": "^5.1.0", + "phpunit/php-text-template": "^4.0.1", + "sebastian/code-unit-reverse-lookup": "^4.0.1", + "sebastian/complexity": "^4.0.1", + "sebastian/environment": "^7.2.1", + "sebastian/lines-of-code": "^3.0.1", + "sebastian/version": "^5.0.2", + "theseer/tokenizer": "^1.3.1" + }, + "require-dev": { + "phpunit/phpunit": "^11.5.46" + }, + "suggest": { + "ext-pcov": "PHP extension that provides line coverage", + "ext-xdebug": "PHP extension that provides line coverage as well as branch and path coverage" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "11.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.", + "homepage": "https://github.com/sebastianbergmann/php-code-coverage", + "keywords": [ + "coverage", + "testing", + "xunit" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues", + "security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy", + "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/11.0.12" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpunit/php-code-coverage", + "type": "tidelift" + } + ], + "time": "2025-12-24T07:01:01+00:00" + }, + { + "name": "phpunit/php-file-iterator", + "version": "5.1.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-file-iterator.git", + "reference": "2f3a64888c814fc235386b7387dd5b5ed92ad903" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/2f3a64888c814fc235386b7387dd5b5ed92ad903", + "reference": "2f3a64888c814fc235386b7387dd5b5ed92ad903", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "FilterIterator implementation that filters files based on a list of suffixes.", + "homepage": "https://github.com/sebastianbergmann/php-file-iterator/", + "keywords": [ + "filesystem", + "iterator" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-file-iterator/issues", + "security": "https://github.com/sebastianbergmann/php-file-iterator/security/policy", + "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/5.1.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpunit/php-file-iterator", + "type": "tidelift" + } + ], + "time": "2026-02-02T13:52:54+00:00" + }, + { + "name": "phpunit/php-invoker", + "version": "5.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-invoker.git", + "reference": "c1ca3814734c07492b3d4c5f794f4b0995333da2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-invoker/zipball/c1ca3814734c07492b3d4c5f794f4b0995333da2", + "reference": "c1ca3814734c07492b3d4c5f794f4b0995333da2", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "ext-pcntl": "*", + "phpunit/phpunit": "^11.0" + }, + "suggest": { + "ext-pcntl": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Invoke callables with a timeout", + "homepage": "https://github.com/sebastianbergmann/php-invoker/", + "keywords": [ + "process" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-invoker/issues", + "security": "https://github.com/sebastianbergmann/php-invoker/security/policy", + "source": "https://github.com/sebastianbergmann/php-invoker/tree/5.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T05:07:44+00:00" + }, + { + "name": "phpunit/php-text-template", + "version": "4.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-text-template.git", + "reference": "3e0404dc6b300e6bf56415467ebcb3fe4f33e964" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/3e0404dc6b300e6bf56415467ebcb3fe4f33e964", + "reference": "3e0404dc6b300e6bf56415467ebcb3fe4f33e964", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Simple template engine.", + "homepage": "https://github.com/sebastianbergmann/php-text-template/", + "keywords": [ + "template" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-text-template/issues", + "security": "https://github.com/sebastianbergmann/php-text-template/security/policy", + "source": "https://github.com/sebastianbergmann/php-text-template/tree/4.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T05:08:43+00:00" + }, + { + "name": "phpunit/php-timer", + "version": "7.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-timer.git", + "reference": "3b415def83fbcb41f991d9ebf16ae4ad8b7837b3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/3b415def83fbcb41f991d9ebf16ae4ad8b7837b3", + "reference": "3b415def83fbcb41f991d9ebf16ae4ad8b7837b3", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "7.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Utility class for timing", + "homepage": "https://github.com/sebastianbergmann/php-timer/", + "keywords": [ + "timer" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-timer/issues", + "security": "https://github.com/sebastianbergmann/php-timer/security/policy", + "source": "https://github.com/sebastianbergmann/php-timer/tree/7.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T05:09:35+00:00" + }, + { + "name": "phpunit/phpunit", + "version": "11.5.58", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phpunit.git", + "reference": "c14b3145a2fcfa5dd9b25ee999ce2ba5933adf6f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/c14b3145a2fcfa5dd9b25ee999ce2ba5933adf6f", + "reference": "c14b3145a2fcfa5dd9b25ee999ce2ba5933adf6f", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-filter": "*", + "ext-json": "*", + "ext-libxml": "*", + "ext-mbstring": "*", + "ext-xmlwriter": "*", + "myclabs/deep-copy": "^1.14.0", + "phar-io/manifest": "^2.0.4", + "phar-io/version": "^3.2.1", + "php": ">=8.2", + "phpunit/php-code-coverage": "^11.0.12", + "phpunit/php-file-iterator": "^5.1.1", + "phpunit/php-invoker": "^5.0.1", + "phpunit/php-text-template": "^4.0.1", + "phpunit/php-timer": "^7.0.1", + "sebastian/cli-parser": "^3.0.2", + "sebastian/code-unit": "^3.0.3", + "sebastian/comparator": "^6.3.3", + "sebastian/diff": "^6.0.2", + "sebastian/environment": "^7.2.1", + "sebastian/exporter": "^6.3.2", + "sebastian/global-state": "^7.0.2", + "sebastian/object-enumerator": "^6.0.1", + "sebastian/recursion-context": "^6.0.3", + "sebastian/type": "^5.1.3", + "sebastian/version": "^5.0.2", + "staabm/side-effects-detector": "^1.0.5" + }, + "suggest": { + "ext-soap": "To be able to generate mocks based on WSDL files" + }, + "bin": [ + "phpunit" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "11.5-dev" + } + }, + "autoload": { + "files": [ + "src/Framework/Assert/Functions.php" + ], + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "The PHP Unit Testing framework.", + "homepage": "https://phpunit.de/", + "keywords": [ + "phpunit", + "testing", + "xunit" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/phpunit/issues", + "security": "https://github.com/sebastianbergmann/phpunit/security/policy", + "source": "https://github.com/sebastianbergmann/phpunit/tree/11.5.58" + }, + "funding": [ + { + "url": "https://phpunit.de/sponsoring.html", + "type": "other" + } + ], + "time": "2026-11-13T11:08:08+00:00" + }, + { + "name": "revolt/event-loop", + "version": "v1.0.9", + "source": { + "type": "git", + "url": "https://github.com/revoltphp/event-loop.git", + "reference": "44061cf513e53c6200372fc935ac42271566295d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/revoltphp/event-loop/zipball/44061cf513e53c6200372fc935ac42271566295d", + "reference": "44061cf513e53c6200372fc935ac42271566295d", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "ext-json": "*", + "jetbrains/phpstorm-stubs": "^2019.3", + "phpunit/phpunit": "^9", + "psalm/phar": "6.16.*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Revolt\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Aaron Piotrowski", + "email": "aaron@trowski.com" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "ceesjank@gmail.com" + }, + { + "name": "Christian Lück", + "email": "christian@clue.engineering" + }, + { + "name": "Niklas Keller", + "email": "me@kelunik.com" + } + ], + "description": "Rock-solid event loop for concurrent PHP applications.", + "keywords": [ + "async", + "asynchronous", + "concurrency", + "event", + "event-loop", + "non-blocking", + "scheduler" + ], + "support": { + "issues": "https://github.com/revoltphp/event-loop/issues", + "source": "https://github.com/revoltphp/event-loop/tree/v1.0.9" + }, + "time": "2026-05-16T17:55:38+00:00" + }, + { + "name": "sebastian/cli-parser", + "version": "3.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/cli-parser.git", + "reference": "15c5dd40dc4f38794d383bb95465193f5e0ae180" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/15c5dd40dc4f38794d383bb95465193f5e0ae180", + "reference": "15c5dd40dc4f38794d383bb95465193f5e0ae180", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for parsing CLI options", + "homepage": "https://github.com/sebastianbergmann/cli-parser", + "support": { + "issues": "https://github.com/sebastianbergmann/cli-parser/issues", + "security": "https://github.com/sebastianbergmann/cli-parser/security/policy", + "source": "https://github.com/sebastianbergmann/cli-parser/tree/3.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:41:36+00:00" + }, + { + "name": "sebastian/code-unit", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/code-unit.git", + "reference": "54391c61e4af8078e5b276ab082b6d3c54c9ad64" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit/zipball/54391c61e4af8078e5b276ab082b6d3c54c9ad64", + "reference": "54391c61e4af8078e5b276ab082b6d3c54c9ad64", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Collection of value objects that represent the PHP code units", + "homepage": "https://github.com/sebastianbergmann/code-unit", + "support": { + "issues": "https://github.com/sebastianbergmann/code-unit/issues", + "security": "https://github.com/sebastianbergmann/code-unit/security/policy", + "source": "https://github.com/sebastianbergmann/code-unit/tree/3.0.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2025-03-19T07:56:08+00:00" + }, + { + "name": "sebastian/code-unit-reverse-lookup", + "version": "4.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git", + "reference": "183a9b2632194febd219bb9246eee421dad8d45e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/183a9b2632194febd219bb9246eee421dad8d45e", + "reference": "183a9b2632194febd219bb9246eee421dad8d45e", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Looks up which function or method a line of code belongs to", + "homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/", + "support": { + "issues": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/issues", + "security": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/security/policy", + "source": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/tree/4.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:45:54+00:00" + }, + { + "name": "sebastian/comparator", + "version": "6.3.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/comparator.git", + "reference": "2c95e1e86cb8dd41beb8d502057d1081ccc8eca9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/2c95e1e86cb8dd41beb8d502057d1081ccc8eca9", + "reference": "2c95e1e86cb8dd41beb8d502057d1081ccc8eca9", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-mbstring": "*", + "php": ">=8.2", + "sebastian/diff": "^6.0", + "sebastian/exporter": "^6.0" + }, + "require-dev": { + "phpunit/phpunit": "^11.4" + }, + "suggest": { + "ext-bcmath": "For comparing BcMath\\Number objects" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.3-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@2bepublished.at" + } + ], + "description": "Provides the functionality to compare PHP values for equality", + "homepage": "https://github.com/sebastianbergmann/comparator", + "keywords": [ + "comparator", + "compare", + "equality" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/comparator/issues", + "security": "https://github.com/sebastianbergmann/comparator/security/policy", + "source": "https://github.com/sebastianbergmann/comparator/tree/6.3.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/comparator", + "type": "tidelift" + } + ], + "time": "2026-01-24T09:26:40+00:00" + }, + { + "name": "sebastian/complexity", + "version": "4.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/complexity.git", + "reference": "ee41d384ab1906c68852636b6de493846e13e5a0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/ee41d384ab1906c68852636b6de493846e13e5a0", + "reference": "ee41d384ab1906c68852636b6de493846e13e5a0", + "shasum": "" + }, + "require": { + "nikic/php-parser": "^5.0", + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for calculating the complexity of PHP code units", + "homepage": "https://github.com/sebastianbergmann/complexity", + "support": { + "issues": "https://github.com/sebastianbergmann/complexity/issues", + "security": "https://github.com/sebastianbergmann/complexity/security/policy", + "source": "https://github.com/sebastianbergmann/complexity/tree/4.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:49:50+00:00" + }, + { + "name": "sebastian/diff", + "version": "6.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/diff.git", + "reference": "b4ccd857127db5d41a5b676f24b51371d76d8544" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/b4ccd857127db5d41a5b676f24b51371d76d8544", + "reference": "b4ccd857127db5d41a5b676f24b51371d76d8544", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0", + "symfony/process": "^4.2 || ^5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + } + ], + "description": "Diff implementation", + "homepage": "https://github.com/sebastianbergmann/diff", + "keywords": [ + "diff", + "udiff", + "unidiff", + "unified diff" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/diff/issues", + "security": "https://github.com/sebastianbergmann/diff/security/policy", + "source": "https://github.com/sebastianbergmann/diff/tree/6.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:53:05+00:00" + }, + { + "name": "sebastian/environment", + "version": "7.2.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/environment.git", + "reference": "a5c75038693ad2e8d4b6c15ba2403532647830c4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/a5c75038693ad2e8d4b6c15ba2403532647830c4", + "reference": "a5c75038693ad2e8d4b6c15ba2403532647830c4", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.3" + }, + "suggest": { + "ext-posix": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "7.2-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Provides functionality to handle HHVM/PHP environments", + "homepage": "https://github.com/sebastianbergmann/environment", + "keywords": [ + "Xdebug", + "environment", + "hhvm" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/environment/issues", + "security": "https://github.com/sebastianbergmann/environment/security/policy", + "source": "https://github.com/sebastianbergmann/environment/tree/7.2.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/environment", + "type": "tidelift" + } + ], + "time": "2025-05-21T11:55:47+00:00" + }, + { + "name": "sebastian/exporter", + "version": "6.3.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/exporter.git", + "reference": "70a298763b40b213ec087c51c739efcaa90bcd74" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/70a298763b40b213ec087c51c739efcaa90bcd74", + "reference": "70a298763b40b213ec087c51c739efcaa90bcd74", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": ">=8.2", + "sebastian/recursion-context": "^6.0" + }, + "require-dev": { + "phpunit/phpunit": "^11.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.3-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + } + ], + "description": "Provides the functionality to export PHP variables for visualization", + "homepage": "https://www.github.com/sebastianbergmann/exporter", + "keywords": [ + "export", + "exporter" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/exporter/issues", + "security": "https://github.com/sebastianbergmann/exporter/security/policy", + "source": "https://github.com/sebastianbergmann/exporter/tree/6.3.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/exporter", + "type": "tidelift" + } + ], + "time": "2025-09-24T06:12:51+00:00" + }, + { + "name": "sebastian/global-state", + "version": "7.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/global-state.git", + "reference": "3be331570a721f9a4b5917f4209773de17f747d7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/3be331570a721f9a4b5917f4209773de17f747d7", + "reference": "3be331570a721f9a4b5917f4209773de17f747d7", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "sebastian/object-reflector": "^4.0", + "sebastian/recursion-context": "^6.0" + }, + "require-dev": { + "ext-dom": "*", + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "7.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Snapshotting of global state", + "homepage": "https://www.github.com/sebastianbergmann/global-state", + "keywords": [ + "global state" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/global-state/issues", + "security": "https://github.com/sebastianbergmann/global-state/security/policy", + "source": "https://github.com/sebastianbergmann/global-state/tree/7.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:57:36+00:00" + }, + { + "name": "sebastian/lines-of-code", + "version": "3.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/lines-of-code.git", + "reference": "d36ad0d782e5756913e42ad87cb2890f4ffe467a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/d36ad0d782e5756913e42ad87cb2890f4ffe467a", + "reference": "d36ad0d782e5756913e42ad87cb2890f4ffe467a", + "shasum": "" + }, + "require": { + "nikic/php-parser": "^5.0", + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for counting the lines of code in PHP source code", + "homepage": "https://github.com/sebastianbergmann/lines-of-code", + "support": { + "issues": "https://github.com/sebastianbergmann/lines-of-code/issues", + "security": "https://github.com/sebastianbergmann/lines-of-code/security/policy", + "source": "https://github.com/sebastianbergmann/lines-of-code/tree/3.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:58:38+00:00" + }, + { + "name": "sebastian/object-enumerator", + "version": "6.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/object-enumerator.git", + "reference": "f5b498e631a74204185071eb41f33f38d64608aa" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/f5b498e631a74204185071eb41f33f38d64608aa", + "reference": "f5b498e631a74204185071eb41f33f38d64608aa", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "sebastian/object-reflector": "^4.0", + "sebastian/recursion-context": "^6.0" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Traverses array structures and object graphs to enumerate all referenced objects", + "homepage": "https://github.com/sebastianbergmann/object-enumerator/", + "support": { + "issues": "https://github.com/sebastianbergmann/object-enumerator/issues", + "security": "https://github.com/sebastianbergmann/object-enumerator/security/policy", + "source": "https://github.com/sebastianbergmann/object-enumerator/tree/6.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T05:00:13+00:00" + }, + { + "name": "sebastian/object-reflector", + "version": "4.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/object-reflector.git", + "reference": "6e1a43b411b2ad34146dee7524cb13a068bb35f9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/6e1a43b411b2ad34146dee7524cb13a068bb35f9", + "reference": "6e1a43b411b2ad34146dee7524cb13a068bb35f9", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Allows reflection of object attributes, including inherited and non-public ones", + "homepage": "https://github.com/sebastianbergmann/object-reflector/", + "support": { + "issues": "https://github.com/sebastianbergmann/object-reflector/issues", + "security": "https://github.com/sebastianbergmann/object-reflector/security/policy", + "source": "https://github.com/sebastianbergmann/object-reflector/tree/4.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T05:01:32+00:00" + }, + { + "name": "sebastian/recursion-context", + "version": "6.0.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/recursion-context.git", + "reference": "f6458abbf32a6c8174f8f26261475dc133b3d9dc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/f6458abbf32a6c8174f8f26261475dc133b3d9dc", + "reference": "f6458abbf32a6c8174f8f26261475dc133b3d9dc", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + } + ], + "description": "Provides functionality to recursively process PHP variables", + "homepage": "https://github.com/sebastianbergmann/recursion-context", + "support": { + "issues": "https://github.com/sebastianbergmann/recursion-context/issues", + "security": "https://github.com/sebastianbergmann/recursion-context/security/policy", + "source": "https://github.com/sebastianbergmann/recursion-context/tree/6.0.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/recursion-context", + "type": "tidelift" + } + ], + "time": "2025-08-13T04:42:22+00:00" + }, + { + "name": "sebastian/type", + "version": "5.1.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/type.git", + "reference": "f77d2d4e78738c98d9a68d2596fe5e8fa380f449" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/f77d2d4e78738c98d9a68d2596fe5e8fa380f449", + "reference": "f77d2d4e78738c98d9a68d2596fe5e8fa380f449", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Collection of value objects that represent the types of the PHP type system", + "homepage": "https://github.com/sebastianbergmann/type", + "support": { + "issues": "https://github.com/sebastianbergmann/type/issues", + "security": "https://github.com/sebastianbergmann/type/security/policy", + "source": "https://github.com/sebastianbergmann/type/tree/5.1.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/type", + "type": "tidelift" + } + ], + "time": "2025-08-09T06:55:48+00:00" + }, + { + "name": "sebastian/version", + "version": "5.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/version.git", + "reference": "c687e3387b99f5b03b6caa64c74b63e2936ff874" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/c687e3387b99f5b03b6caa64c74b63e2936ff874", + "reference": "c687e3387b99f5b03b6caa64c74b63e2936ff874", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that helps with managing the version number of Git-hosted PHP projects", + "homepage": "https://github.com/sebastianbergmann/version", + "support": { + "issues": "https://github.com/sebastianbergmann/version/issues", + "security": "https://github.com/sebastianbergmann/version/security/policy", + "source": "https://github.com/sebastianbergmann/version/tree/5.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-10-09T05:16:32+00:00" + }, + { + "name": "staabm/side-effects-detector", + "version": "1.0.5", + "source": { + "type": "git", + "url": "https://github.com/staabm/side-effects-detector.git", + "reference": "d8334211a140ce329c13726d4a715adbddd0a163" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/staabm/side-effects-detector/zipball/d8334211a140ce329c13726d4a715adbddd0a163", + "reference": "d8334211a140ce329c13726d4a715adbddd0a163", + "shasum": "" + }, + "require": { + "ext-tokenizer": "*", + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "phpstan/extension-installer": "^1.4.3", + "phpstan/phpstan": "^1.12.6", + "phpunit/phpunit": "^9.6.21", + "symfony/var-dumper": "^5.4.43", + "tomasvotruba/type-coverage": "1.0.0", + "tomasvotruba/unused-public": "1.0.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "lib/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A static analysis tool to detect side effects in PHP code", + "keywords": [ + "static analysis" + ], + "support": { + "issues": "https://github.com/staabm/side-effects-detector/issues", + "source": "https://github.com/staabm/side-effects-detector/tree/1.0.5" + }, + "funding": [ + { + "url": "https://github.com/staabm", + "type": "github" + } + ], + "time": "2024-10-20T05:08:20+00:00" + }, + { + "name": "theseer/tokenizer", + "version": "1.3.1", + "source": { + "type": "git", + "url": "https://github.com/theseer/tokenizer.git", + "reference": "b7489ce515e168639d17feec34b8847c326b0b3c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/theseer/tokenizer/zipball/b7489ce515e168639d17feec34b8847c326b0b3c", + "reference": "b7489ce515e168639d17feec34b8847c326b0b3c", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": "^7.2 || ^8.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + } + ], + "description": "A small library for converting tokenized PHP source code into XML and potentially other formats", + "support": { + "issues": "https://github.com/theseer/tokenizer/issues", + "source": "https://github.com/theseer/tokenizer/tree/1.3.1" + }, + "funding": [ + { + "url": "https://github.com/theseer", + "type": "github" + } + ], + "time": "2025-11-17T20:03:58+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": {}, + "prefer-stable": true, + "prefer-lowest": false, + "platform": { + "php": ">=8.3", + "ext-mbstring": "*", + "ext-pdo": "*" + }, + "platform-dev": {}, + "plugin-api-version": "2.9.0" +} diff --git a/docs/GUIA-PROGRAMADOR.md b/docs/GUIA-PROGRAMADOR.md new file mode 100644 index 0000000..3fd996f --- /dev/null +++ b/docs/GUIA-PROGRAMADOR.md @@ -0,0 +1,1099 @@ +# camelia/orm — Guía del programador + +Documentación de uso de la librería `camelia/orm`. Para el contrato de diseño completo, ver +[`especificaciones-orm.md`](especificaciones-orm.md). Para el arranque rápido, el +[`README`](README.md). + +Esta guía está organizada **por tarea**: qué quieres hacer, no qué clases existen. La referencia de +API completa está al final. + +--- + +## Índice + +1. [Instalación y arranque](#1-instalación-y-arranque) +2. [Definir un modelo](#2-definir-un-modelo) +3. [Tipos y conversiones](#3-tipos-y-conversiones) +4. [Lectura: buscar filas](#4-lectura-buscar-filas) +5. [Condiciones de filtro](#5-condiciones-de-filtro) +6. [Escritura: guardar filas](#6-escritura-guardar-filas) +7. [Validación](#7-validación) +8. [Relaciones](#8-relaciones) +9. [Paginación](#9-paginación) +10. [Transacciones](#10-transacciones) +11. [Serialización a JSON](#11-serialización-a-json) +12. [Manejo de errores](#12-manejo-de-errores) +13. [Extensiones: auditoría, logs, reloj](#13-extensiones-auditoría-logs-reloj) +14. [Testing de código que usa el ORM](#14-testing-de-código-que-usa-el-orm) +15. [Recetas frecuentes](#15-recetas-frecuentes) +16. [Trampas y errores comunes](#16-trampas-y-errores-comunes) +17. [Referencia de API](#17-referencia-de-api) + +--- + +## 1. Instalación y arranque + +```bash +composer require camelia/orm +``` + +Crea el objeto raíz una vez por proceso y pásalo donde lo necesites. Es inmutable y seguro de +compartir. + +```php +use Camelia\Orm\Orm; + +$orm = Orm::fromArray([ + 'host' => '127.0.0.1', + 'port' => 3306, + 'user' => 'app', + 'password' => 'secret', + 'database' => 'erp', +]); +``` + +### Desde variables de entorno + +```php +$orm = Orm::fromEnv(); +``` + +Lee `CAMELIA_DB_HOST`, `CAMELIA_DB_USER`, `CAMELIA_DB_NAME` y `CAMELIA_DB_PASS` (todas +obligatorias) y opcionalmente `CAMELIA_DB_PORT` (3306) y `CAMELIA_DB_CHARSET` (utf8mb4). Si falta +alguna obligatoria, el mensaje de error lista **todas** las que faltan, no solo la primera. + +### Desde un `PDO` existente + +```php +$orm = Orm::fromPdo($pdo); +``` + +El `PDO` debe estar en `ERRMODE_EXCEPTION`. Si no, se lanza `ConfigurationException`: los modos +silenciosos son incompatibles con el contrato de errores de la librería. + +### Claves de `fromArray` + +| Clave | Obligatoria | Por defecto | +|---|---|---| +| `host` | sí | — | +| `user` | sí | — | +| `database` | sí | — | +| `password` | no | `''` | +| `port` | no | `3306` | +| `charset` | no | `utf8mb4` | +| `sslCa` | no | — (ruta al certificado CA) | + +Las claves de extensión (`logger`, `auditListener`, `clock`, `slowQueryMs`) se explican en +[§13](#13-extensiones-auditoría-logs-reloj). + +> **No hay singleton.** No existe `getInstance()` ni `reset()`. Si necesitas otra conexión, crea +> otro `Orm`. + +--- + +## 2. Definir un modelo + +Un modelo es una clase que extiende `Camelia\Orm\Model` con propiedades públicas tipadas. + +```php +hydrate(['activo' => 'quizas']); // InvalidArgumentException +``` + +### Enums nativos de PHP + +```php +enum Estado: string +{ + case Pendiente = 'PENDIENTE'; + case Pagada = 'PAGADA'; +} + +#[Enum(Estado::class)] +public Estado $estado = Estado::Pendiente; +``` + +El valor viaja como su `value` escalar a la base y se valida en `validate()`. + +### `DateTimeImmutable`, no `DateTime` + +El tipo mapeado es `DateTimeImmutable`. Un `DateTime` mutable puede modificarse en cualquier punto +de un `toArray()` o de una relación, y produce bugs irreproducibles. Si tu tabla devuelve una fecha, +obtienes un inmutable. + +--- + +## 4. Lectura: buscar filas + +Todas las lecturas viven en el `Repository`, que obtienes por modelo: + +```php +$repo = $orm->repository(Usuario::class); +``` + +### Las cuatro formas de leer + +```php +// 1. Por clave primaria +$usuario = $repo->findByPk(5); // ?Usuario +$usuario = $repo->findByPkOrFail(5); // Usuario, o RecordNotFoundException + +// 2. Primera fila que cumpla criterios +$usuario = $repo->findFirst(['correo' => 'a@x']); + +// 3. Todas las filas que cumplan criterios +$usuarios = $repo->find(['activo' => true]); + +// 4. Consulta fluida (cuando necesitas más) +$usuarios = $repo->query()->where('activo', true)->orderBy('nombre')->get(); +``` + +### Ordenar y limitar + +```php +$repo->find( + criteria: ['activo' => true], + order: [['nombre', 'ASC'], ['codigo', 'DESC']], + limit: 20, + offset: 40, +); +``` + +Las columnas de `order` se validan: si no existen en el modelo, se descartan. Una dirección +inválida lanza `CriteriaException`. + +### Conteos y agregaciones + +```php +$repo->count(['activo' => true]); // int +$repo->exists(['correo' => 'a@x']); // bool +$repo->sum('total', ['estado' => 'PAGADA']); // float +$repo->avg('total'); // float +$repo->max('total'); // ?float +$repo->min('total'); // ?float +``` + +`max` y `min` devuelven `null` si no hay filas; `sum` y `avg` devuelven `0.0`. + +### Encontrar o crear + +```php +$usuario = $repo->findOrCreate( + criteria: ['correo' => 'a@x'], + values: ['nombre' => 'Ana', 'clave' => 'abc'], +); +``` + +Busca por `criteria`; si no existe, crea con `values + criteria`. **No es transaccional**: entre el +`SELECT` y el `INSERT` otra petición puede insertar la misma fila. Si eso importa, envuélvelo en +`$orm->transaction()` o apóyate en un índice único. + +--- + +## 5. Condiciones de filtro + +Un criterio es un array `['columna' => valor]` combinado con `AND`. Puedes usar el nombre de la +propiedad o el de la columna; si usas una clave que no existe, la excepción lista las válidas. + +```php +$repo->find([ + 'activo' => true, // col = ? + 'codigo' => [1, 2, 3], // col IN (?, ?, ?) + 'apodo' => null, // col IS NULL + 'nombre' => Cond::like('%ana%'), // operador explícito +]); +``` + +### Operadores disponibles — `Cond` + +```php +use Camelia\Orm\Query\Cond; + +Cond::eq($v) // col = ? +Cond::neq($v) // col <> ? +Cond::gt($v) // col > ? +Cond::gte($v) // col >= ? +Cond::lt($v) // col < ? +Cond::lte($v) // col <= ? +Cond::in([...]) // col IN (...) +Cond::notIn([...]) // col NOT IN (...) +Cond::between($a, $b) // col BETWEEN ? AND ? +Cond::notBetween($a, $b)// col NOT BETWEEN ? AND ? +Cond::like('...') // col LIKE ? +Cond::notLike('...') // col NOT LIKE ? +Cond::isNull() // col IS NULL +Cond::isNotNull() // col IS NOT NULL +Cond::raw($sql, [...]) // escape hatch: el SQL se emite literal +``` + +`Cond` es inmutable: cada método devuelve un objeto nuevo, muévelo en variables. + +### Disyunciones (`OR`) + +```php +$repo->query() + ->whereGroup(function (GroupCond $g): void { + $g->or('correo', Cond::like('%@camelia.dev')); + $g->or('zona', 3); + }) + ->get(); +// WHERE (correo LIKE ? OR zona = ?) +``` + +Puedes combinar varios grupos: + +```php +$repo->query() + ->where('activo', true) // AND con el grupo siguiente + ->whereGroup(fn (GroupCond $g) => $g->or('nombre', 'Ana')) + ->whereGroup(fn (GroupCond $g) => $g->or('zona', 1), 'OR'); +// WHERE (activo = ?) AND (nombre = ?) OR (zona = ?) +``` + +### Por qué no hay `_and()` ni `whereNot()` + +`_and(['a','b'])` generaba `col = 'a' AND col = 'b'`, que en SQL es casi siempre falso. Y +`whereNot()` no excluía `NULL` (semántica estándar de SQL), lo que sorprendía a todo el mundo. + +- Para conjunción: varias claves del mismo array **ya** son `AND`. +- Para exclusión: `Cond::neq()` o `Cond::notIn()`. +- Para excluir nulls además del valor: `Cond::isNotNull()` en el criterio y `Cond::neq()`. + +### Columnas desconocidas + +Una clave que no corresponde a ninguna propiedad ni columna lanza `CriteriaException` con la lista +de columnas válidas. Es la única regla de validación de identificadores; no hay regex de escape que +pueda colarse. + +--- + +## 6. Escritura: guardar filas + +### Las dos formas + +```php +// 1. Decides tú: save() inserta o actualiza según la PK +$repo->save($usuario); + +// 2. Afirmas que la fila existe +$repo->update($usuario); +``` + +| Método | Cuándo usarlo | Lanza si | +|---|---|---| +| `save($model)` | No sabes (o no te importa) si la fila existe | el modelo no valida | +| `update($model)` | La fila ya existe y quieres sobreescribirla | PK vacía, modelo parcial, no valida | +| `create($values)` | Crear desde un array sin instanciar | no valida | +| `patch($pk, $values)` | Actualizar **solo algunas columnas** | columnas desconocidas | +| `delete($model)` | Borrar por la PK del modelo | PK vacía | +| `remove($pk)` | Borrar por clave, sin instanciar | — | + +### Lo único que debes recordar sobre `update` + +**`update()` escribe la fila completa.** No hay *dirty tracking*: el modelo es la verdad sobre la +fila. Si hiciste `hydrate` con dos campos, los demás se escriben con su valor en memoria. + +```php +$usuario = $repo->findByPk(5); // fila completa +$usuario->nombre = 'Bea'; +$repo->update($usuario); // escribe TODAS las columnas +``` + +Para actualizar una sola columna, usa `patch`: + +```php +$repo->patch(5, ['nombre' => 'Bea']); // UPDATE usuarios SET nombre = ? WHERE codigo = ? +``` + +### Actualizar sin leer + +```php +$repo->patch(5, ['activo' => false]); +$repo->remove(5); // true si borró una fila +``` + +`patch` acepta claves por propiedad o por columna, y aplica el mismo casting que `hydrate`. + +### Insertar y obtener la clave autogenerada + +```php +$usuario = $repo->create(['nombre' => 'Ana', 'correo' => 'a@x', 'clave' => 'abc']); +$usuario->codigo; // 42, ya asignado +``` + +Si declaras `#[AutoIncrement]`, tras el `INSERT` el ORM asigna el `lastInsertId` a la propiedad PK. + +### Copiar un registro + +```php +$copia = $usuario->replicate(); // misma fila lógica, PK vacía +$repo->save($copia); // INSERT de una fila nueva +``` + +### Modelos parciales + +Si leíste con `select()` (columnas restringidas), el modelo queda marcado como parcial: + +```php +$parcial = $repo->query()->select('codigo', 'nombre')->get()[0]; +$parcial->isPartial(); // true +$repo->update($parcial); // PartialModelException +$repo->patch($parcial->codigo, ['nombre' => 'X']); // ✅ la vía correcta +``` + +Esto impide el bug clásico: escribir valores neutros en columnas que nunca leíste. + +### Hooks + +```php +final class Factura extends Model +{ + protected function beforeInsert(): void + { + $this->creadoEn = new \DateTimeImmutable('now'); + } + + protected function beforeUpdate(): void + { + $this->modificadoEn = new \DateTimeImmutable('now'); + } +} +``` + +Solo existen esas dos fases. Para lo demás (auditoría, notificaciones), usa `AuditListener` +([§13](#13-extensiones-auditoría-logs-reloj)). + +--- + +## 7. Validación + +Solo tres reglas, las que se declaran con atributos: + +```php +#[Required] +public string $nombre = ''; + +#[Enum(Estado::class)] +public Estado $estado = Estado::Pendiente; + +#[MaxLength(150)] +public string $correo = ''; +``` + +| Regla | Disparador | Mensaje | +|---|---|---| +| `#[Required]` | valor `null` o `''` | `El campo {propiedad} es requerido` | +| `#[Enum]` | valor no es instancia del enum | `El valor de {propiedad} no es válido` | +| `#[MaxLength(n)]` | `mb_strlen > n` | `El campo {propiedad} supera {n} caracteres` | + +### Comprobar sin escribir + +```php +$errores = $usuario->validate(); // ['nombre' => ['El campo nombre es requerido']] +$usuario->isValid(); // bool +``` + +### La excepción + +`save` / `update` / `create` validan y lanzan `ValidationException` con **todos** los errores +agrupados, no el primero: + +```php +try { + $repo->save($usuario); +} catch (ValidationException $e) { + $e->errors(); // array> + $e->model(); // FQCN del modelo +} +``` + +Los mensajes están en español en el código fuente. Si necesitas otro idioma, traduce en tu capa de +presentación a partir de `errors()`, que te da las claves por propiedad. + +--- + +## 8. Relaciones + +### Declaración + +```php +use Camelia\Orm\Attribute\{TableName, PrimaryKey, AutoIncrement, BelongsTo, HasMany}; + +#[TableName('facturas')] +final class Factura extends Model +{ + #[PrimaryKey, AutoIncrement] + public ?int $codigo = null; + + public int $usuarioCodigo = 0; // columna usuario_codigo + + #[BelongsTo(Usuario::class, foreignKey: 'usuarioCodigo')] + public ?Usuario $usuario = null; + + /** @var array */ + #[HasMany(Detalle::class, foreignKey: 'facturaCodigo')] + public array $detalles = []; +} +``` + +| Atributo | Dónde está la FK | Cuántos carga | +|---|---|---| +| `#[BelongsTo(Clase, foreignKey: 'prop')]` | en la tabla **actual** | 1 | +| `#[HasOne(Clase, foreignKey: 'prop')]` | en la tabla **relacionada** | 1 | +| `#[HasMany(Clase, foreignKey: 'prop')]` | en la tabla **relacionada** | N | +| `#[BelongsToMany(Clase, through: 'pivote', foreignPivotKey: 'a', relatedPivotKey: 'b')]` | tabla pivote | N | + +**La propiedad lleva el nombre del rol**, sin sufijos: `$usuario`, no `$usuarioRel`. La propiedad FK +lleva el sufijo `Codigo`: `$usuarioCodigo`, que coincide con el nombre de su columna. + +### No hay lazy loading + +```php +$factura = $repo->findByPk(1); +$factura->usuario; // null: no se cargó +``` + +La propiedad empieza con su valor inicial y **solo** cambia por carga explícita o eager loading. +Esto elimina la clase de bugs más difícil de rastrear de los ORM con proxies (`__get` mágico). + +### Cargar una relación + +```php +// En una instancia +$repo->refreshRelations($factura, ['usuario']); + +// Todas las relaciones declaradas +$repo->refreshRelations($factura); +``` + +### Eager loading (sin N+1) + +```php +// Una relación +$repo->find(with: ['usuario']); + +// Rutas anidadas +$repo->find(with: ['usuario', 'usuario.ciudad']); + +// Anidado explícito con array +$repo->find(with: ['usuario' => ['ciudad', 'zona']]); + +// Todas las relaciones de primer nivel (y solo esas) +$repo->find(with: true); +``` + +Garantías: + +- **Una consulta por relación y nivel.** Cargar `usuario` en 100 facturas hace 1 consulta extra, no + 100. +- `with: true` carga **solo** el primer nivel. No arrastra niveles profundos por sorpresa. +- Una relación declarada que no existe lanza `MetadataException`, aunque no haya filas. +- Límite duro de **3 niveles** de anidamiento; superarlo lanza `ConfigurationException`. Si + necesitas más, compón llamadas a `refreshRelations()`. + +--- + +## 9. Paginación + +```php +$page = $repo->page( + criteria: ['activo' => true], + order: [['nombre', 'ASC']], + page: 2, + perPage: 25, +); +``` + +```php +$page->items; // list +$page->page; // 2 +$page->perPage; // 25 +$page->total; // 137 +$page->totalPages; // 6 (siempre int) +$page->hasNext(); // true +$page->hasPrev(); // true +``` + +También desde una consulta fluida: + +```php +$repo->query()->where('activo', true)->page(page: 1, perPage: 50); +``` + +**Entradas fuera de rango se corrigen, no se ignoran:** `page < 1` → `1`; `perPage` se acota a +`[1, 1000]`. La librería es tolerante en la frontera y estricta en el interior. + +`$page->toArray()` devuelve claves en `snake_case` (`per_page`, `total_pages`, `has_next`), listas +para un payload HTTP. + +--- + +## 10. Transacciones + +```php +use Camelia\Orm\Orm; + +$orm->transaction(function (Orm $orm): void { + $usuarios = $orm->repository(Usuario::class); + $facturas = $orm->repository(Factura::class); + + $usuarios->save($u); + $facturas->save($f); +}); +``` + +- Se anidan con **savepoints**. +- Si el callback lanza, hace `rollBack` y **repropaga la excepción original** (no la envuelve). +- Devuelve lo que devuelva el callback. + +```php +$id = $orm->transaction(fn () => $orm->repository(Usuario::class)->create([...])->codigo); +``` + +Las operaciones de la librería **no** abren transacciones por su cuenta. `findOrCreate` no es +transaccional: si lo necesitas, envuélvelo. + +--- + +## 11. Serialización a JSON + +```php +$usuario->toArray(); // columnas escribibles + relaciones cargadas +$usuario->toJson(); // JSON con pretty-print y sin escapar unicode ni slashes +$usuario->toJson(JSON_THROW_ON_ERROR); // flags extra para json_encode + +$page->toArray(); // payload de paginación, snake_case +$page->toJson(); +``` + +Reglas de conversión: + +| Tipo | En JSON | +|---|---| +| `DateTimeImmutable` | string `DATE_ATOM` (`2024-01-15T00:00:00+00:00`) | +| `BackedEnum` | su `value` escalar | +| `BigDecimal` | string (no objeto: `json_encode` fallaría o truncaría) | +| Relación cargada | objeto anidado o array de objetos | +| Relación no cargada | `null` / `[]` | + +Solo se serializan **columnas escribibles** y relaciones. La PK no está en `toArray()`; si necesitas +exponerla, añádela con `array_merge(['codigo' => $u->codigo], $u->toArray())` o serializa a mano. + +--- + +## 12. Manejo de errores + +**Ninguna lectura devuelve `[]` ante un fallo.** Todo error de base lanza. La regla anterior +("las lecturas degradan") convertía un fallo de conexión en un resultado vacío indistinguible de +"no hay filas". + +``` +OrmException (extends RuntimeException) +├── ConfigurationException configuración o entorno inválido +├── MetadataException modelo mal declarado +├── CriteriaException columna desconocida / operando inválido +├── ValidationException validate() no vacío → errors(), model() +├── PartialModelException escritura sobre modelo parcial +├── RecordNotFoundException findByPkOrFail / firstOrFail +└── DatabaseException todo fallo SQL → sql(), params(), context() + ├── DuplicateKeyException clave única o PK duplicada + ├── ForeignKeyViolationException FK rota + └── LockTimeoutException deadlock o lock wait timeout +``` + +### Capturar por intención + +```php +use Camelia\Orm\Exception\{DatabaseException, DuplicateKeyException}; + +try { + $repo->save($usuario); +} catch (DuplicateKeyException) { + return response()->json(['error' => 'correo duplicado'], 409); +} catch (DatabaseException $e) { + $logger->error('fallo de BD', ['sql' => $e->sql(), 'params' => $e->params()]); + throw $e; +} +``` + +### Degradar a propósito + +Si de verdad quieres tolerar un fallo en una lectura concreta, hazlo explícito en **tu** capa: + +```php +try { + $lista = $repo->find(['activo' => true]); +} catch (DatabaseException) { + $lista = []; +} +``` + +`DatabaseException` expone `sql()`, `params()` y `context()` (`'read'` o `'write'`) para logging. + +--- + +## 13. Extensiones: auditoría, logs, reloj + +Todas son interfaces que tú implementas. La librería no trae ninguna implementación concreta. + +### Auditoría + +```php +use Camelia\Orm\Persistence\AuditListener; + +final class Auditoria implements AuditListener +{ + public function onWrite( + string $table, + int|string $pk, + string $action, // 'insert' | 'update' | 'delete' + ?array $before, // null en insert + array $after, // [] en delete + ): void { + // escribe donde tú decidas + } +} + +$orm = Orm::fromArray([... , 'auditListener' => new Auditoria()]); +``` + +Se invoca **tras** un `save`/`update`/`delete` exitoso. El `$before` solo se consulta si hay +listener registrado, así que sin auditoría no cuesta una consulta extra. + +### Logging (PSR-3) + +```php +$orm = Orm::fromArray([... , 'logger' => $psrLogger, 'slowQueryMs' => 200]); +``` + +> **Estado actual: no implementado.** `logger` y `slowQueryMs` se aceptan y se exponen por +> `Orm::logger()` / `Orm::slowQueryMs()`, pero **ningún componente los lee todavía**: no hay logging +> automático de SQL lento ni de errores. La librería nunca llama a `error_log()` global, así que sin +> logger simplemente no hay logs. Instrumenta en tu capa si lo necesitas hoy; los parámetros están +> reservados para cuando el soporte se implemente, sin romper la firma de `fromArray`. + +### Reloj + +```php +use Camelia\Orm\Support\Clock; + +$orm = Orm::fromArray([... , 'clock' => $miReloj]); +``` + +> **Estado actual:** igual que el logger, `clock` se almacena y `Orm::clock()` lo expone, pero el +> ORM no lo usa internamente (no hay timestamps automáticos). Úsalo en tus propios hooks +> (`beforeInsert`) pasando el reloj al modelo, o inyéctalo en tu código de dominio. + +--- + +## 14. Testing de código que usa el ORM + +### Tests de modelos sin base de datos + +```php +$usuario = (new Usuario())->hydrate(['nombre' => 'Ana', 'clave' => 'abc']); + +self::assertSame('Ana', $usuario->nombre); +self::assertTrue($usuario->isValid()); +``` + +`Model` **no** importa `Query` ni `Connection`. Puedes construir y validar un modelo sin conexión. + +### Tests de repositorio con doble de conexión + +Implementa `Camelia\Orm\Connection\Connection` y registra lo que llega: + +```php +use Camelia\Orm\Connection\Connection; + +final class FakeConnection implements Connection +{ + public array $executed = []; + public array $rows = []; + + public function execute(string $sql, array $params = []): int + { + $this->executed[] = ['sql' => $sql, 'params' => $params]; + + return 1; + } + + public function select(string $sql, array $params = []): array + { + return $this->rows; + } + + public function scalar(string $sql, array $params = []): mixed { return null; } + public function lastInsertId(): string { return '1'; } + public function begin(): void {} + public function commit(): void {} + public function rollBack(): void {} + public function inTransaction(): bool { return false; } + public function driver(): string { return 'fake'; } +} + +$repo = new Camelia\Orm\Repository(new FakeConnection(), Usuario::class); +``` + +### Aserciones sobre SQL + +Para verificar que una consulta se construye bien, no ejecutes; compara `toSql()`: + +```php +$sql = $repo->query()->where('activo', true)->orderByDesc('nombre')->toSql(); + +self::assertSame('SELECT `codigo`, ... FROM `usuarios` WHERE (`activo` = ?) ORDER BY ... DESC', $sql['sql']); +self::assertSame([true], $sql['params']); +``` + +Es la única forma de probar un compilador SQL sin base de datos. + +### Limpiar la caché de metadatos + +Los metadatos se leen una vez por proceso. Si un test declara un modelo distinto con la misma clase: + +```php +Model::clearMetadataCache(); +``` + +--- + +## 15. Recetas frecuentes + +### Consulta con búsqueda y paginación desde HTTP + +```php +$criteria = ['activo' => true]; + +if ($buscar = $request->get('q')) { + $criteria['nombre'] = Cond::like('%' . $buscar . '%'); +} + +$page = $orm->repository(Usuario::class)->page( + criteria: $criteria, + order: [['nombre', 'ASC']], + page: (int) ($request->get('page') ?? 1), + perPage: 25, +); + +return response()->json($page->toArray()); +``` + +### Crear desde un payload HTTP respetando campos protegidos + +```php +$usuario = $repo->create($request->all()); // #[Guarded] se ignora automáticamente +``` + +Si quieres que un campo protegido en el payload sea un error en lugar de ignorarse: + +```php +$usuario = new Usuario(); +$usuario->hydrateStrict($payload); // InvalidArgumentException si viene un #[Guarded] +$repo->save($usuario); +``` + +### Listado con sus relaciones en una sola pasada + +```php +$facturas = $repo->find( + criteria: ['usuarioCodigo' => $id], + with: ['detalles'], +); +``` + +### Borrado protegido por transacción + +```php +$orm->transaction(function (Orm $orm) use ($usuario): void { + $orm->repository(Factura::class)->remove($usuario->codigo); + $orm->repository(Usuario::class)->delete($usuario); +}); +``` + +--- + +## 16. Trampas y errores comunes + +| Síntoma | Causa | Solución | +|---|---|---| +| `MetadataException [M3]` | Ninguna o varias propiedades con `#[PrimaryKey]` | Declara exactamente una | +| `MetadataException [M2]` | Falta `#[TableName]` | Añádelo, no hay fallback | +| `MetadataException [M7]` | Dos propiedades a la misma columna | Renombra una con `#[Column]` | +| `CriteriaException: Unknown column` | Clave de criterio que no existe | Revisa el mensaje: lista las válidas | +| `PartialModelException` | `update`/`save` sobre un modelo de `select()` | Usa `patch()` | +| Columna sobrescrita con valor vacío | `update()` escribe la fila completa | Usa `patch()` para cambios puntuales | +| `ConfigurationException: ERRMODE` | `PDO` con modo silencioso | Usa `ERRMODE_EXCEPTION` | +| Relación siempre `null` | No hay lazy loading | Carga con `with:` o `refreshRelations()` | +| Relación llega sin datos pero la fila existe | FK apuntando a la propiedad equivocada | `foreignKey` debe ser el **nombre de la propiedad** | +| `ConfigurationException: depth` | Más de 3 niveles en `with` | Compón `refreshRelations()` | +| `ValidationException` con varios errores | Varias reglas fallando | Es intencional: `errors()` los agrupa | + +### Diferencias con otros ORM + +Si vienes de Laravel/Eloquent o de Doctrine, estos puntos te van a sorprender: + +| Eloquent | camelia/orm | +|---|---| +| `find()` busca por PK | `find()` busca por criterios; por PK es `findByPk()` | +| `save()` hace dirty tracking | No hay dirty tracking: `update()` escribe la fila completa | +| Relaciones lazy por defecto | Sin lazy: carga explícita o `with:` | +| `->update()` sin instanciar | `patch($pk, $values)` | +| Errores a veces silenciosos | Todo lanza | +| `Model::create()` estático | `$repo->create()` | + +--- + +## 17. Referencia de API + +### `Orm` + +| Método | Devuelve | +|---|---| +| `fromArray(array $options): self` | Conexión PDO nueva | +| `fromEnv(): self` | Conexión desde `CAMELIA_DB_*` | +| `fromPdo(PDO $pdo): self` | Envuelve un PDO existente | +| `fromConnection(Connection $c, array $o = []): self` | Inyecta transporte | +| `repository(string $class): Repository` | Repositorio memoizado por clase | +| `transaction(callable $cb): mixed` | Ejecuta en transacción (anidable) | +| `connection(): Connection` | Transporte | +| `dialect(): Dialect` | Dialecto SQL | +| `clock(): Clock` | Reloj | +| `logger(): ?LoggerInterface` | Logger o `null` | +| `slowQueryMs(): int` | Umbral de SQL lento | + +### `Repository` + +Lecturas: + +| Método | Devuelve | +|---|---| +| `find(array $criteria = [], array $order = [], ?int $limit = null, ?int $offset = null, bool\|array $with = false)` | `list` | +| `findFirst(array $criteria = [], array $order = [], bool\|array $with = false)` | `?Model` | +| `findByPk(int\|string $pk, bool\|array $with = false)` | `?Model` | +| `findByPkOrFail(int\|string $pk, bool\|array $with = false)` | `Model` | +| `findOrCreate(array $criteria, array $values = [])` | `Model` | +| `count(array $criteria = [])` | `int` | +| `exists(array $criteria = [])` | `bool` | +| `sum/avg(string $column, array $criteria = [])` | `float` | +| `max/min(string $column, array $criteria = [])` | `?float` | +| `page(array $criteria = [], array $order = [], int $page = 1, int $perPage = 20)` | `Page` | +| `query()` | `Query` | +| `metadata()` | `ClassMetadata` | +| `refreshRelations(Model $model, array $only = [])` | `void` | + +Escrituras: + +| Método | Devuelve | +|---|---| +| `save(Model $model)` | `int\|string` (PK) | +| `create(array $values = [])` | `Model` | +| `update(Model $model)` | `void` | +| `delete(Model $model)` | `void` | +| `patch(int\|string $pk, array $values)` | `void` | +| `remove(int\|string $pk)` | `bool` | + +### `Query` (inmutable) + +Constructor: `$repo->query()`. + +| Grupo | Métodos | +|---|---| +| Filtros | `where`, `whereIn`, `whereNotIn`, `whereNull`, `whereNotNull`, `whereGroup` | +| Orden | `orderBy`, `orderByDesc` | +| Límites | `limit`, `offset` | +| Proyección | `select(string ...$columns)` | +| Relaciones | `with(bool\|string\|array ...$relations)` | +| Terminales | `get`, `first`, `firstOrFail`, `count`, `exists`, `sum`, `avg`, `max`, `min`, `pluck`, `page`, `toSql` | + +`toSql()` devuelve `['sql' => string, 'params' => list]`. + +### `Model` + +| Método | Devuelve | +|---|---| +| `hydrate(array $data)` | `static` | +| `hydrateStrict(array $data)` | `static` (lanza si viene un `#[Guarded]`) | +| `toArray(?array $only = null)` | `array` | +| `toJson(int $flags = 0)` | `string` | +| `validate()` | `array>` | +| `isValid()` | `bool` | +| `isPartial()` / `markPartial(bool = true)` | `bool` / `void` | +| `replicate()` | `static` | +| `get(string $property)` / `set(string $property, mixed $value)` | `mixed` / `static` | +| `metadata()` (estático) | `ClassMetadata` | +| `clearMetadataCache()` (estático) | `void` | + +Hooks sobreescribibles: `beforeInsert()`, `beforeUpdate()` (ambos `protected`). + +### `Cond` + +`eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `in`, `notIn`, `between`, `notBetween`, `like`, `notLike`, +`isNull`, `isNotNull`, `raw($sql, array $params = [])`. + +### `Page` + +Propiedades: `items`, `page`, `perPage`, `total`, `totalPages`. +Métodos: `hasNext()`, `hasPrev()`, `toArray()`, `toJson()`. +Constantes: `MIN_PER_PAGE = 1`, `MAX_PER_PAGE = 1000`. + +### Atributos + +| Atributo | Target | Efecto | +|---|---|---| +| `#[TableName(string)]` | clase | Tabla destino (obligatorio) | +| `#[PrimaryKey]` | prop | Marca la PK (obligatorio, exactamente uno) | +| `#[AutoIncrement]` | prop | PK generada por la BD | +| `#[Column(string)]` | prop | Nombre de columna explícito | +| `#[Guarded]` | prop | Excluida de `hydrate()` | +| `#[Ignore]` | prop | Excluida de persistencia y de `hydrate()` | +| `#[Required]` | prop | Validación de no vacío | +| `#[Enum(BackedEnum::class)]` | prop | Casting y validación contra el enum | +| `#[Nullable]` | prop | Fuerza nulabilidad cuando el tipo no la expresa | +| `#[MaxLength(int)]` | prop | Validación de longitud | +| `#[Length(int)]` | prop | **Sin efecto**: reservado para generación de DDL (no implementada) | +| `#[Precision(int, int)]` | prop | **Sin efecto**: reservado para DDL | +| `#[Unique]` / `#[UniqueGroup(string)]` | prop | **Sin efecto**: reservado para DDL | +| `#[Index(string $order = 'ASC')]` | prop | Marcado como indexado en metadatos; **no** genera DDL | +| `#[BelongsTo / HasOne / HasMany / BelongsToMany]` | prop | Relación | + +### `ClassMetadata` + +`table()`, `primaryKey()`, `primaryKeyColumn()`, `column(string)`, `property(string)`, +`hasProperty(string)`, `hasColumn(string)`, `propertyMetadata(string)`, `properties()`, +`relations()`, `indexed()`, `writable()`, `resolveProperty(string)`, `knownKeys()`. + +`PropertyMetadata` expone: `name`, `column`, `type`, `enumClass`, `relation`, `declaringClass`, +`nullable`, `ignored`, `guarded`, `primaryKey`, `autoIncrement`, `required`, `indexed`, `maxLength`. +Métodos: `isWritable()`, `isRelation()`. + +### `Connection` + +`execute(string $sql, array $params = []): int`, `select(...): array`, +`scalar(...): mixed`, `lastInsertId(): string`, `begin()`, `commit()`, `rollBack()`, +`inTransaction(): bool`, `driver(): string`. + +--- + +## Apéndice: por dónde seguir + +| Documento | Contenido | +|---|---| +| [`README.md`](README.md) | Arranque mínimo y comandos de desarrollo | +| [`docs/GUIA-PROGRAMADOR.md`](docs/GUIA-PROGRAMADOR.md) | Guía completa por tareas, recetas y referencia de API | +| [`especificaciones-orm.md`](especificaciones-orm.md) | Contrato de diseño completo, glosario normativo | +| [`CHANGELOG.md`](CHANGELOG.md) | Cambios por versión | +| [`AGENTS.md`](AGENTS.md) | Convenciones para contribuir al código de la librería | diff --git a/especificaciones-orm.md b/especificaciones-orm.md new file mode 100644 index 0000000..8492c3f --- /dev/null +++ b/especificaciones-orm.md @@ -0,0 +1,1082 @@ +# Especificaciones de `camelia-orm` — librería ORM independiente + +Documento normativo y **autosuficiente** para construir una librería PHP 8.2+ autónoma, sin +dependencia de la aplicación que la consume. Todo lo necesario para implementarla, probarla y +publicarla está aquí; no se asume ningún otro documento. + +> Este documento **define** el contrato. No describe código preexistente. Cuando una decisión de +> diseño tenga más de una salida razonable, se explica la elegida y por qué. + +--- + +## 0. Nomenclatura canónica + +**Este glosario es normativo.** Todo nombre de clase, método, parámetro y atributo del documento +proviene de esta tabla. Si algo no está aquí, no existe en la librería. + +Regla de formación: **el nombre dice qué es, no qué hace de dónde viene.** + +- **Clases**: sustantivo singular en `PascalCase`. `Model`, no `BaseBean`. `Page`, no `PaginadorResultado`. +- **Interfaces**: capacidad, sin prefijo `I` ni sufijo `Interface` cuando el sustantivo ya es un rol. + `Clock`, `Dialect`, `Listener`. La excepción es `Connection` (§0.3): ver la nota. +- **Métodos de lectura/escritura**: verbo en infinitivo o 3ª persona, nunca gerundio. `find`, no `finding`. + Las consultas usan el **prefijo `find`**; las escrituras usan el **verbo SQL directo**. +- **Colecciones**: plural. `items`, no `itemList`. `properties()`, no `getPropertyArr()`. +- **Booleanos**: predicado afirmativo, `is`/`has`/`can`. `isPartial()`, `hasNext()`. +- **Parámetros**: `$criteria` (filtro), `$order` (orden), `$with` (relaciones eager), `$pk` (clave), + `$page`/`$perPage` (paginación). **Un nombre, un significado en toda la API.** +- **Sin abreviaturas**: `Configuration`, no `Config`; `Metadata`, no `Meta`; `Repository`, no `Repo`. + Excepto en **nombres de variable locales de ejemplo** (`$repo`), donde la brevedad del snippet gana. + +### 0.1 Cambios de nombre respecto a versiones anteriores del documento + +| Antes | Ahora | Razón | +|---|---|---| +| `SqlDialect` (interface) | `Dialect` | El namespace ya es `Query`; `Sql` era redundante | +| `CriterionCompiler` | `CriteriaCompiler` | Concierta con el parámetro `$criteria` | +| `OrderCompiler` | — (absorbido por `QueryBuilder`) | No hay parámetro `$order` que justifique una clase | +| `FluentQuery` | `Query` | Es *la* consulta fluida; el adjetivo no aportaba | +| `Repository::findOne()` | `Repository::findFirst()` | `first`/`findFirst` es simbólico; `One` era genérico | +| `Repository::find()` (por PK) | `Repository::findByPk()` | `find()` sin argumento mental es ambiguo | +| `Repository::findOrFail()` | `Repository::findByPkOrFail()` | Dice **qué** falla: el PK no existe | +| `Repository::findAll()` | `Repository::find()` | Es la lectura canónica; `All` sobra | +| `Repository::insert/update/delete/save` | `save()` unifica insert/update; `patch`/`remove` van por clave | `insert` era `save` restringido; cuatro métodos para dos operaciones | +| `updateByPk` / `deleteByPk` | `patch()` / `remove()` | El sufijo `ByPk` decía *cómo* se identifica, no *qué* hace; y `update` quedaba sobrecargada | +| `Model::fill()` | `Model::hydrate()` | `fill` no dice de dónde | + +### 0.2 Glosario de términos + +| Término | Significado exacto en este documento | +|---|---| +| **Modelo** | Instancia de una clase que extiende `Model`. Solo estado + reglas de forma. | +| **Entidad** | Sinónimo de modelo. Se usa indistintamente; no hay dos conceptos. | +| **Repositorio** | Objeto `Repository` que ejecuta lectura/escritura para **un** modelo. | +| **Criterio** | Array `['columna' => valor\|Cond]`. | +| **Cond** | Objeto inmutable que representa un operador SQL sobre una columna. | +| **GroupCond** | Acumulador mutable de condiciones dentro de `Query::whereGroup()`; solo existe en ese scope. | +| **Query** | Consulta fluida inmutable. Antes llamada `FluentQuery`. | +| **Page** | Resultado paginado inmutable. | +| **Metadata** | Descripción estática de un modelo derivada por reflexión. | +| **Dialect** | Traductor de una operación abstracta a SQL de un motor. | +| **Connection** | Abstracción de transporte SQL. Ver §0.3. | +| **Persister** | Componente interno que ejecuta escrituras. No es API pública. | +| **Parcial** | Modelo hidratado con `select()`: no todas sus columnas fueron leídas. | + +### 0.3 Convenciones de sufijos que **no** se usan + +| Sufijo | Por qué no | +|---|---| +| `Interface` | El tipo ya lo dice. `Connection` es el caso límite: se conserva el nombre de rol y la interfaz es `Connection`, mientras que la implementación PDO se llama `PdoConnection`. **La implementación lleva el prefijo del driver; la interfaz, el nombre del rol.** | +| `Exception` | Excepción obvia por contexto. Se conserva solo donde el nombre sin sufijo sería ambiguo (`MetadataException`). | +| `Dto`, `ValueObject`, `Data` | Ruido. | +| `Service`, `Manager`, `Handler`, `Helper` | Nombres que no dicen nada. Si lo necesita, está mal dividido. | +| `Base` | El prefijo `Base` apunta a herencia para reutilizar código. Aquí se usa composición. | + +### 0.4 Nombres prohibidos (aparecen en el legado, no aquí) + +`SimpleModelBase` · `SimpleModelBaseQueries` · `Conexion` · `EDatabase` · `FilterExpr` · +`TraitAuditoriaCambios` · `AuditoriaCambios` · `_in` · `_or` · `_and` · `whereNot` · `getRelated` · +`getRelatedMany` · `loadRelations` · `buildData` · `initializeProperties`. + +--- + +## 1. Resumen ejecutivo + +`camelia-orm` es un ORM ligero de *Active Record* sobre PDO para MariaDB/MySQL, mapeado con atributos +PHP. Su objetivo es ser **pequeño de leer, predecible de usar y trivial de mockear**. + +- **Nombre del paquete:** `camelia/orm` · **autor:** Dr2g Sistemas · **namespace raíz:** `Camelia\Orm` +- **PHP:** `>=8.2` · **Extensión:** `pdo_mysql` (obligatoria), `mbstring` (obligatoria) +- **Dependencias de runtime:** `psr/log ^3.0` (PSR-3, uso opcional). `brick/math` es `suggest`. +- **Dependencias de desarrollo:** `carthage-software/mago ^1.60` (formatter, linter, analyzer), + `phpunit/phpunit ^10|^11`, `phpstan/phpstan ^1.11` (nivel 8) +- **PSR:** `PSR-4` (`Camelia\Orm\` → `src/`) y `PSR-3` (logging opcional) + +### Principios rectores (aplican a cada sección) + +| Principio | Cómo se materializa en esta librería | +|---|---| +| **SoC** | Metadatos (reflexión) ⟂ SQL (compilación) ⟂ Ejecución (PDO) ⟂ Estado (entidad) ⟂ Presentación (`toArray`). Ningún componente hace dos de estas cosas. | +| **SOLID** | El compilador SQL depende de `Dialect` (interface), no de MySQL. Cada clase tiene una única razón de cambio: `MetadataCache` cachea, `MetadataFactory` reflexiona. Inyectar `Connection` permite sustituir PDO en tests. | +| **KISS** | Una sola forma canónica de hacer cada cosa. No existen dos métodos con el mismo nombre y semánticas distintas, ni dos nombres para la misma operación dentro del mismo objeto. | +| **DRY** | Un único `CriteriaCompiler` produce `WHERE`+params para criterios; lo usan `find`, `count`, `page` y `Query`. Un único `MetadataCache`. | + +### Decisiones de diseño que corrigen el legado + +Si vienes de la especificación anterior del ORM del ERP, estos cambios son **intencionales**: + +1. **Se elimina la duplicación `SimpleModelBase` ↔ `SimpleModelBaseQueries`.** Una sola clase, + `Camelia\Orm\Model`, delegando en `Repository` (composición, no herencia de implementaciones). +2. **Se eliminan los helpers globales `_in()`, `_or()`, etc.** Colisionan con el consumidor y violan + autosuficiencia. Se reemplazan por una clase estática `Cond` con métodos encadenables. +3. **`manyToMany` funciona o no existe.** La spec de referencia lo documentaba roto. Aquí es un + contrato real con tabla pivote declarativa. +4. **No hay "lecturas que degradan".** Silenciar errores SQL es el mayor defecto del diseño previo: + un fallo de base se convierte en `[]` y el bug aparece 3 capas arriba. Aquí **todo** error + lanza. Para degradar intencionalmente, el consumidor captura. `getOrNull()` está disponible + como azúcar explícita para el caso legítimo. +5. **Coherencia de tipos en la salida.** `Page::$totalPages` es `int` siempre. +6. **Se elimina `#[Timestamp]`, `#[OnInsert]`, `#[OnUpdate]`, `#[Description]`, `#[Comment]`, + `#[Check]`.** Eran declarativos sin efecto en runtime; su lugar está en el `CREATE TABLE` de la + migración, no en atributos PHP que fingen hacer algo. La generación de DDL queda fuera de la + librería (§12). + +### Fuera de alcance (explícito, no ambiguo) + +Contenedor DI · migraciones automáticas · lazy loading por proxy · unit of work / identity map · +herencia de tabla · soft deletes automáticos · eventos observables · consultas no-SQL · +multitenancy · auditoría de cambios (se ofrece como `listener` opcional, §10.3). + +Si algo de esto se necesita, se implementa **fuera** de la librería, sobre sus hooks públicos. + +--- + +## 2. Mapa de la librería + +``` +src/ +├── Connection/ +│ ├── Connection.php ← interface: rol de transporte SQL +│ ├── PdoConnection.php ← implementación PDO +│ └── ConnectionFactory.php ← desde array de config o entorno +├── Attribute/ ← atributos sin lógica (§4) +├── Metadata/ +│ ├── ClassMetadata.php ← DTO inmutable +│ ├── PropertyMetadata.php ← DTO inmutable +│ ├── RelationMetadata.php ← DTO inmutable de relación +│ ├── MetadataFactory.php ← reflexión → ClassMetadata +│ └── MetadataCache.php ← memo por clase +├── Query/ +│ ├── Cond.php ← constructores de condiciones (§6.3) +│ ├── CriteriaCompiler.php ← (Cond|array) → [sql, params] +│ ├── Dialect.php ← interface +│ ├── MySqlDialect.php ← única implementación +│ ├── QueryBuilder.php ← SELECT/UPDATE/DELETE compilado +│ └── Query.php ← consulta fluida inmutable +├── Repository.php ← API pública de lectura y escritura +├── Model.php ← estado + hydrate/toArray/validate +├── Persistence/ +│ ├── Persister.php ← INSERT/UPDATE/DELETE (interno) +│ ├── AuditListener.php ← interface, sin implementación por defecto +│ └── Validator.php ← reglas derivadas de atributos (interno) +├── Pagination/ +│ └── Page.php ← resultado paginado inmutable +├── Exception/ ← jerarquía tipada (§11) +└── Support/ ← TypeCaster, NameConverter, Clock +``` + +> El directorio `Schema/` de versiones anteriores del documento **no existe**: la generación de DDL +> está fuera de alcance (§12). + +**Regla de dependencia (verificable con PHPStan):** + +``` +Model ──► Metadata (DTO) +Model ──► Support +Repository ──► Query, Metadata, Persistence, Pagination +Persistence ──► Query, Metadata, Connection +Query ──► Connection, Metadata, Support +Metadata, Support, Attribute ──► (nada interno) +Exception ──► (nada) +``` + +`Model` **no** importa `Query` ni `Connection`. La persistencia se invoca vía `Repository`, que el +consumidor obtiene de `Orm::repository(ModelX::class)`. Esto es lo que hace la entidad testeable +sin base de datos. + +**Regla de visibilidad:** `Persister`, `Validator`, `CriteriaCompiler`, `QueryBuilder` y +`MetadataFactory` son `@internal`. El consumidor toca `Orm`, `Repository`, `Query`, `Page`, `Cond`, +`Model`, los atributos y las excepciones. Todo lo demás es implementación. + +--- + +## 3. Arranque: `Orm` + +Un único objeto raíz. Inmutable, seguro de pasar por constructor. + +```php +use Camelia\Orm\Orm; + +$orm = Orm::fromArray([ + 'host' => '127.0.0.1', + 'port' => 3306, + 'user' => 'app', + 'password' => '...', + 'database' => 'erp', + 'charset' => 'utf8mb4', // opcional + 'sslCa' => '/ruta/ca.pem', // opcional +]); + +$repo = $orm->repository(ModelUsuario::class); // Camelia\Orm\Repository +$user = $repo->findFirst(['codigo' => 1]); +``` + +También existe `Orm::fromPdo(PDO $pdo)` y `Orm::fromEnv(): self` (lee `CAMELIA_DB_*`, ver §3.1). +Todas convergen en el mismo constructor privado. No hay singleton ni estado estático global. + +### 3.1 Variables de entorno (`fromEnv`) + +| Variable | Obligatoria | +|---|---| +| `CAMELIA_DB_HOST` | sí | +| `CAMELIA_DB_USER` | sí | +| `CAMELIA_DB_NAME` | sí | +| `CAMELIA_DB_PASS` | sí (puede ser cadena vacía) | +| `CAMELIA_DB_PORT` | no (default `3306`) | +| `CAMELIA_DB_CHARSET` | no (default `utf8mb4`) | + +Si falta una obligatoria: `ConfigurationException` con la lista de las que faltan (todas, no la +primera). + +### 3.2 Configuración de PDO esperada + +`PdoConnection` impone, sin excepción, `ERRMODE_EXCEPTION`, `FETCH_ASSOC`, +`ATTR_EMULATE_PREPARES = false`, `MYSQL_ATTR_SSL_CA` si se pasa en config. Si el `PDO` entregado +vía `fromPdo` no está en `ERRMODE_EXCEPTION`, `PdoConnection` falla con `ConfigurationException`: +los modos silenciosos son incompatibles con el contrato de §11. + +--- + +## 3. Definir un modelo + +```php + **Cambio respecto al legado:** `DateTime` se reemplaza por `DateTimeImmutable` como tipo mapeado. +> Mutar un `DateTime` inside `toArray()` o desde fuera produce bugs no reproducibles. + +--- + +## 4. Metadatos + +`MetadataFactory::forClass(string $class): ClassMetadata`, memoizado en `MetadataCache` +(`WeakMap` interno, tamaño ilimitado: la JVM ya no es el motivo del límite de 100). + +```php +final class ClassMetadata +{ + public function table(): string; + public function primaryKey(): string; // nombre de PROPIEDAD + public function primaryKeyColumn(): string; // nombre de COLUMNA + /** @return array indexado por PROPIEDAD */ + public function properties(): array; + public function column(string $property): string; + public function property(string $column): ?string; + public function hasProperty(string $property): bool; + public function hasColumn(string $column): bool; + /** @return list */ + public function relations(): array; + /** @return list */ + public function indexed(): array; + /** @return list propiedades escribibles (no ignoradas, no PK) */ + public function writable(): array; +} + +final class PropertyMetadata +{ + public string $name; // propiedad PHP + public string $column; // columna SQL + public string $type; // string|int|float|bool|array|DateTimeImmutable|BackedEnum|BigDecimal|mixed + public bool $nullable; + public bool $ignored; + public bool $guarded; + public bool $primaryKey; + public bool $autoIncrement; + public ?string $enumClass; // BackedEnum::class si se declara + public ?RelationMetadata $relation; +} + +final class RelationMetadata +{ + public string $kind; // 'belongsTo'|'hasOne'|'hasMany'|'belongsToMany' + public string $relatedClass; // FQCN resuelto + public string $foreignKey; // PROPIEDAD del modelo dueño de la FK + public ?string $through; // solo belongsToMany: tabla pivote + public ?string $foreignPivotKey; + public ?string $relatedPivotKey; +} +``` + +**Convención `primaryKey()` vs `primaryKeyColumn()`**: se repite en toda la librería. Un método +que dice `...Column()` devuelve columna SQL; sin sufijo devuelve propiedad PHP. Nunca se mezclan. + +`MetadataCache::clear()` existe **solo** para tests. En producción los metadatos son inmutables +por proceso; si los atributos cambian en caliente, hace falta reiniciar. + +--- + +## 5. Atributos + +Se declaran en `Camelia\Orm\Attribute\*`, todos `#[Attribute(Attribute::TARGET_*) final readonly]` y +sin lógica. Un atributo que no se lee en runtime no existe en esta librería. + +| Atributo | Target | Efecto runtime | +|---|---|---| +| `#[TableName(string)]` | clase | Nombre de tabla (obligatorio) | +| `#[PrimaryKey]` | prop | Marca PK (obligatorio, exactamente uno) | +| `#[AutoIncrement]` | prop | Tras `INSERT`, PK se toma de `lastInsertId` | +| `#[Column(string)]` | prop | Sustituye la conversión snake_case | +| `#[Guarded]` | prop | Excluida de `hydrate()`; **no** de escritura directa | +| `#[Ignore]` | prop | Excluida de SELECT/INSERT/UPDATE y de `hydrate()`; la relación se declara con su atributo de §8 | + +**Nota sobre relaciones:** una propiedad de relación se excluye de la persistencia por llevar su +atributo `#[BelongsTo]`/`#[HasOne]`/`#[HasMany]`/`#[BelongsToMany]`, no por `#[Ignore]`. Exigir +ambos era redundante y permitía un estado incoherente (relación declarada sin excluir). +| `#[Required]` | prop | `validate()` rechaza `null` y `''` | +| `#[Enum(BackedEnum::class)]` | prop | Casting + validación contra el enum nativo | +| `#[Nullable]` | prop | Fuerza `nullable = true` cuando el tipo PHP no lo expresa (p. ej. `string`) | +| `#[Length(int)]` | prop | **Sin efecto** (reservado para DDL no implementado) | +| `#[Precision(int, int)]` | prop | **Sin efecto** (reservado para DDL) | +| `#[Unique]`, `#[UniqueGroup(string)]` | prop | **Sin efecto** (reservado para DDL) | +| `#[Index(string $order = 'ASC')]` | prop | Solo marca `PropertyMetadata::$indexed`; no genera DDL | +| `#[MaxLength(int)]` | prop | `validate()` rechaza strings más largos | + +**Se elimina deliberadamente:** `#[Timestamp]`, `#[OnInsert]`, `#[OnUpdate]`, `#[Description]`, +`#[Comment]`, `#[ForeignKey]`, `#[DefaultValue]`, `#[Check]`. La DDL se genera desde tipo PHP + +`#[Length]`/`#[Precision]`; lo que un atributo no puede garantizar en runtime no se declara como +si lo hiciera. `#[ForeignKey]` se sustituye por el atributo de relación de §8, que sí se usa. + +--- + +## 6. Lectura + +### 6.1 API de `Repository` + +**Regla única:** las lecturas usan el prefijo `find`; las escrituras usan el verbo de destino +(`save`, `update`, `delete`, `create`). Un método llamado `find*` nunca escribe. + +Todas las lecturas toman `array $criteria` (§6.2), o `$pk` cuando el nombre lo dice (`findByPk`). + +```php +final class Repository +{ + /** @param array $criteria */ + public function find(array $criteria = [], array $order = [], ?int $limit = null, ?int $offset = null, bool|array $with = false): array; + public function findFirst(array $criteria = [], array $order = [], bool|array $with = false): ?Model; + public function findByPk(int|string $pk, bool|array $with = false): ?Model; + public function findByPkOrFail(int|string $pk, bool|array $with = false): Model; + public function findOrCreate(array $criteria, array $values = []): Model; + + public function count(array $criteria = []): int; + public function exists(array $criteria = []): bool; + public function sum(string $column, array $criteria = []): float; + public function avg(string $column, array $criteria = []): float; + public function max(string $column, array $criteria = []): ?float; + public function min(string $column, array $criteria = []): ?float; + + public function page(array $criteria = [], array $order = [], int $page = 1, int $perPage = 20): Page; + + public function query(): Query; +} +``` + +**Por qué `find` y no `findAll`.** `find()` es la lectura canónica; "todas las que cumplan el +criterio" es lo que ya implica. `findAll` con `$limit = 10` era contradictorio: el nombre prometía +todas y la firma limitaba. Un nombre, una promesa. + +**Por qué `findFirst` y no `findOne`.** `first` describe posición; `one` describe cantidad. Con +`$order`, "el primero" es exacto. + +**Por qué `findByPk` existe además de `find`.** `find(['codigo' => 5])` y `findByPk(5)` producirían +el mismo SQL, y eso es **DRY por la vía correcta**: `findByPk` es azúcar documentada sobre `find` +con el criterio de PK, porque leer por clave es la operación más frecuente y merece nombre propio. +No son dos implementaciones: `findByPk` construye un criterio y delega. + +Ninguno de estos métodos captura `PDOException`. Ver §11. + +### 6.2 Criterios + +Forma: `['propiedad_o_columna' => valor]`, combinados con `AND`. + +| Valor | SQL | +|---|---| +| escalar | `col = ?` | +| `array` | `col IN (?, ?, ...)`; array vacío → `1 = 0` (nunca se ignora en silencio) | +| `null` | `col IS NULL` | +| `Cond` | según su operador (§6.3) | + +**Validación de identificadores**: la clave debe existir como propiedad o columna declarada en +`ClassMetadata`. Si no, `CriteriaException::unknownColumn($model, $key)` con la lista de +columnas válidas en el mensaje. No hay regex de escape como criterio de aceptación: +la pertenencia al metadata es la única regla y es más estricta que cualquier regex. + +### 6.3 Condiciones — `Cond` + +Clase estática, **sin funciones globales**. Cada método devuelve un objeto `Cond` inmutable. + +```php +use Camelia\Orm\Query\Cond; + +$repo->find([ + 'activo' => true, + 'codigo' => Cond::in([1, 2, 3]), + 'creadoEn' => Cond::between('2024-01-01', '2024-12-31'), + 'nombre' => Cond::like('%ana%'), + 'eliminado' => Cond::isNull(), +]); + +// Grupos (solo en Query, §6.4): +$q->whereGroup(function (GroupCond $group) { + $group->or('correo', Cond::like('%@camelia.dev')); + $group->or('zona', 3); +}); +``` + +`GroupCond` es **la única entrada mutable** de la API, y por diseño: acumula condiciones mientras se +ejecuta el closure. Vive solo dentro de la llamada; nunca se expone fuera de ella. + +| Método | SQL | +|---|---| +| `Cond::eq($v)` | `col = ?` *(explícito; por defecto un escalar ya lo hace)* | +| `Cond::neq($v)` | `col <> ?` | +| `Cond::gt/gte/lt/lte($v)` | `col > >= < <= ?` | +| `Cond::in(array $v)` | `col IN (...)` | +| `Cond::notIn(array $v)` | `col NOT IN (...)` | +| `Cond::between($a, $b)` | `col BETWEEN ? AND ?` | +| `Cond::notBetween($a, $b)` | `col NOT BETWEEN ? AND ?` | +| `Cond::like(string $v)` | `col LIKE ?` | +| `Cond::notLike(string $v)` | `col NOT LIKE ?` | +| `Cond::isNull()` | `col IS NULL` | +| `Cond::isNotNull()` | `col IS NOT NULL` | +| `Cond::raw(string $sql, array $params)` | `()` — **escape hatch documentado**, el identificador no se valida | + +**Se eliminan `_and` y `_or` de la spec anterior.** `_and(['a','b'])` generaba +`col = 'a' AND col = 'b'` (siempre falso), violación directa de KISS: existía una API cuyo +comportamiento nadie podía predecir. Para disyunciones, `whereGroup`/`or`. Para conjunciones, +varias claves del mismo array ya son `AND`. + +**`whereNot` también se elimina como atajo.** `NOT (col = ?)` excluía `NULL` por semántica SQL, lo +que sorprendía a todo el mundo. La forma explícita es `Cond::neq()` o `Cond::notIn()`; quien quiera +excluir nulls lo escribe (`Cond::isNotNull()` + `neq`, o `raw`). + +### 6.4 `Query` + +```php +$q = $repo->query(); + +$q->where('activo', true) // igual que el array de criterios + ->whereIn('zona', [1, 2]) + ->whereGroup(fn(GroupCond $g) => $g->or(...)->and(...)) + ->orderBy('nombre') + ->orderByDesc('creadoEn') + ->limit(20)->offset(40) + ->with('empresa', 'empresa.ciudad') // §8.3 + ->get(); // Model[] + +$q->first(); // ?Model +$q->count(); // int +$q->exists(); // bool +$q->page(page: 2, perPage: 50); // Page +$q->pluck('nombre'); // list +$q->select('codigo', 'nombre')->get(); // hidrata solo esas columnas +$q->toSql(); // ['sql' => ..., 'params' => ...] para debug +``` + +**Terminales y su correspondencia con `Repository`** — mismo nombre para la misma operación, sin +excepción: + +| `Query` | `Repository` | Retorno | +|---|---|---| +| `get()` | `find()` | `Model[]` | +| `first()` | `findFirst()` | `?Model` | +| `firstOrFail()` | `findByPkOrFail()` (solo por PK) | `Model` | +| `count()` | `count()` | `int` | +| `exists()` | `exists()` | `bool` | +| `sum()`/`avg()`/`max()`/`min()` | idem | `float`/`?float` | +| `page()` | `page()` | `Page` | +| `pluck()` | — | `list` | +| `toSql()` | — | `array{sql:string, params:array}` | + +`get`/`first` son los nombres del *builder* (`get` = "dame lo construido"); `find`/`findFirst` los +del *repositorio*. La diferencia es de rol, no de semántica: no hay dos comportamientos, hay dos +superficies. Lo que **no** existe es un mismo nombre con dos comportamientos, ni dos nombres para +un mismo comportamiento en el mismo objeto. + +**No hay doble camino.** `find`, `findFirst`, `count`, `page` construyen un `Query` internamente y +lo ejecutan. La especificación anterior describía un "enrutamiento" entre ruta avanzada y +`Repository` según qué método se llamara; esa distinción desaparece porque existe un solo +compilador. + +`Query` es **inmutable**: cada método devuelve una copia. Esto evita que un query se contamine al +reutilizarlo en tests, que era el bug más caro de depurar en el legado mutable. + +`select()` restringe columnas: las propiedades no seleccionadas quedan con su valor neutro (§4.2) +y `isPartial()` devuelve `true`. Persistir un modelo parcial lanza `PartialModelException` +(evita sobrescribir columnas no leídas con valores neutros). + +### 6.5 `Page` + +```php +final readonly class Page +{ + /** @param list $items */ + public function __construct( + public array $items, + public int $page, // >= 1 + public int $perPage, // 1..1000 + public int $total, + public int $totalPages, // int, siempre + ) {} + + public function hasNext(): bool; + public function hasPrev(): bool; + public function toArray(): array; // items, page, per_page, total, total_pages, has_next, has_prev +} +``` + +`perPage` fuera de rango se **corrige a los límites**, no se ignora en silencio: es una entrada de +usuario y la librería debe ser tolerante en frontera y estricta en interior. `page < 1` → `1`. + +`toArray()` usa `snake_case` porque es el formato de **salida** (payload HTTP); las propiedades PHP +usan `camelCase`. La frontera de serialización es explícita y única: `toArray()` en `Page` y en +`Model`. + +### 6.6 Rendimiento + +- Un `SELECT` por terminal. Sin N+1 en eager loading (§8.3). +- Prepared statements: `Connection` mantiene un caché de `PDOStatement` por `(sql)` con límite + 200 y LRU; siempre se reutiliza vía `execute(array)`. La librería **nunca** usa `bindParam`. + Esto es un invariante de `Connection` y está cubierto por test. +- `QueryBuilder` produce SQL idéntico entre llamadas con la misma firma (cacheable por el motor de + la base y por un opcional `QueryCache` del consumidor). + +--- + +## 7. Escritura + +Todas las escrituras viven en `Persistence\Persister`, invocadas desde `Repository`. `Model` no +conoce la base de datos. Es deliberado (SoC): una entidad puede construirse y verificarse sin +conexión. + +**Regla:** toda escritura recibe **un modelo** (`save`, `update`, `delete`) o **una PK + array** +(`patch`, `remove`). No existe ninguna firma que acepte ambas formas. + +```php +// Modelo completo +$repo->save($usuario); // INSERT si PK vacía, UPDATE si PK presente +$repo->create(['nombre' => 'Ana']); // new + hydrate + save; devuelve el Model +$repo->update($usuario); // UPDATE de todas las columnas (PK obligatoria) +$repo->delete($usuario); // DELETE por PK del modelo + +// Por clave, sin hidratar +$repo->patch(int|string $pk, array $values): bool; // UPDATE parcial +$repo->remove(int|string $pk): bool; // DELETE por clave +``` + +| Método | Argumento | SQL | Detalle | +|---|---|---|---| +| `save` | `Model` | `INSERT` o `UPDATE` | Decide por PK vacía/presente. **Única** entrada de "guardar sin pensar". | +| `update` | `Model` | `UPDATE ... WHERE pk = ?` | Valida; escribe **todas** las columnas escribibles (§7.1). Lanza si parcial. | +| `delete` | `Model` | `DELETE ... WHERE pk = ?` | Lanza si PK vacía. | +| `create` | `array $values` | `INSERT` | `new` + `hydrate($values)` + `save`. Devuelve `Model`. | +| `patch` | `$pk`, `array $values` | `UPDATE SET col = ?, ...` | Solo las claves pasadas. | +| `remove` | `$pk` | `DELETE WHERE pk = ?` | `true` si borró 1 fila. | + +`findOrCreate()` (§6.1) no está en esta tabla porque **lee primero**: es `findFirst` + `create` en una +sola llamada, y su nombre lo dice. Vive en la sección de lectura por esa razón. + +**Por qué `save` y `update` coexisten.** `save` responde "persiste este modelo, decidas tú". `update` +responde "esta fila ya existe, escribe lo que tengo". La primera es convenientemente honesta sobre +su ambigüedad; la segunda es una afirmación del llamante. Ninguna sustituye a la otra, y el nombre +de cada una dice cuál es. `insert` **se elimina** como método público: era `save` restringido sin +aportar nada. + +**Por qué `patch`/`remove` y no `updateByPk`/`deleteByPk`.** El sufijo `ByPk` decía *cómo* se +identifica la fila, que es ruido: toda escritura por clave lo es. `patch`/`remove` dicen *qué +hacen*: modificación parcial y borrado por identidad. Además evita que `update(PK, values)` y +`update(Model)` compartan nombre, que es el defecto exacto de nomenclatura que esta sección elimina. + +### 7.1 Semántica de `update` + +`update()` escribe **todas** las columnas escribibles del modelo. No hay dirty tracking: el +modelo se considera la verdad sobre la fila. Frases como "actualiza solo lo que cambió" no +aplican. Para actualizaciones parciales existe `patch()`. + +Si el modelo proviene de `select()` parcial (`isPartial() === true`), `update()` y `save()` lanzan +`PartialModelException`. Esto es la garantía de DRY aplicada al peligro real del legado: el ORM +anterior no distinguía un modelo completo de uno parcial y sobreescribía la fila con valores neutros. + +### 7.2 Validación + +`Model::validate(): array` devuelve `[propiedad => mensaje]`. Se compone en `Persistence\Validator`, +con reglas **solo** las declaradas: + +| Regla | Disparador | Mensaje | +|---|---|---| +| Requerido | `#[Required]`, valor `null` o `''` | `"El campo {nombre} es requerido"` | +| Enum | `#[Enum(E::class)]`, valor no instancia `E` | `"El valor de {nombre} no es válido"` | +| Longitud | `#[MaxLength(n)]`, `strlen > n` | `"El campo {nombre} supera {n} caracteres"` | + +`isValid(): bool` = `validate() === []`. + +`save`/`update` llaman a `validate()` y lanzan `ValidationException` agrupando **todos** los +errores (el legado concatenaba strings; aquí el mensaje es un array accesible por propiedad). + +**Se elimina** la validación de tipo `Text`/`BigInt`/`Json` del legado: el tipo PHP ya garantiza +lo que prometía y una regla de runtime que duplica al motor de tipos es ruido. + +### 7.3 Hooks + +Único par soportado, en `Model`, `protected`, vacíos por defecto: + +```php +protected function beforeInsert(): void {} +protected function beforeUpdate(): void {} +``` + +`Persister` los invoca justo antes de construir el SQL. No hay `afterInsert`, `beforeDelete` ni +observadores: para cross-cutting (auditoría, timestamps, notificaciones) existe `AuditListener` +(§10.3). Un hook por fase muere en el tercer caso de uso. + +### 7.4 Casting de entrada + +`Model::hydrate(array $data)`: +- Acepta claves por **propiedad o por columna**. Si ambas existen, gana la propiedad + (determinista, documentado, testeado). +- Aplica el cast de §7.5. Un valor no casteable **no** se convierte en `null` silenciosamente: + se lanza `InvalidArgumentException` con el nombre del campo y el valor recibido. El legado hacía + `(int)` si era numérico y `null` si no, lo que producía filas con ceros que nadie escribió. +- Ignora claves desconocidas (compatibilidad con payloads HTTP). +- Respeta `#[Guarded]`; las guardadas **se omiten** (no se lanza) salvo `hydrate($data, strict: true)`. + +### 7.5 Tabla de casting + +| Tipo declarado | Entrada aceptada | Resultado | +|---|---|---| +| `int` | `int`, `numeric string`, `bool` | `int`; resto excepción | +| `float` | `float`, `numeric string`, `bool` | `float`; resto excepción | +| `bool` | `bool`, `0/1`, `'0'/'1'`, `'true'/'false'` | `bool`; resto excepción | +| `string` | escalar, `Stringable` | `string`; `null` si nulable | +| `array` | `array`, JSON string (si `#[Ignore]`) | `array` | +| `DateTimeImmutable` | `DateTimeInterface`, string ISO/`Y-m-d` | `DateTimeImmutable`; inválido excepción | +| `BackedEnum` | instancia o valor del enum | instancia | +| `BigDecimal` | `BigDecimal`, numérico, string numérica | `BigDecimal` | +| `json` (columna JSON) | array/objeto/JSON string | array asociativo; inválido excepción | + +### 7.6 Serialización y construcción + +`Model::toArray(?array $only = null): array` → columnas escribibles + relaciones cargadas. +`DateTimeImmutable` → `DATE_ATOM`. `BigDecimal` → `string` (json_encode falla con objetos de +`brick/math`; el legado los exponía como objeto, lo que truncaba la respuesta JSON). + +`Model::toJson(int $flags = 0): string`. + +**Simetría `hydrate` / `toArray`**: son la única pareja entrada/salida de datos del modelo. +`fromArray`/`fromObject` **se eliminan**: son `hydrate()` con un paso previo trivial, y tener dos +nombres para lo mismo es exactamente lo que esta sección elimina. + +```php +$modelo = new Usuario(); +$modelo->hydrate($payload); // array asociativo +$modelo->hydrate(get_object_vars($dto)); // objeto → array explícito en el llamante +``` + +`Model::refresh(Repository): static` — relee por PK y devuelve **una copia** (inmutable en la +práctica; el legado mutaba la instancia y devolvía `bool`, ambigüedad innecesaria). + +`Model::replicate(): static` — copia con PK vacía, lista para `save`. + +--- + +## 8. Relaciones + +### 8.1 Declaración + +```php +use Camelia\Orm\Attribute\{TableName, PrimaryKey, AutoIncrement, Guarded}; +use Camelia\Orm\Relation\{BelongsTo, HasMany, HasOne, BelongsToMany}; +use Camelia\Orm\Model; + +#[TableName('facturaciones')] +final class Facturacion extends Model +{ + #[PrimaryKey, AutoIncrement] + public ?int $codigo = null; + + public int $clienteCodigo = 0; // → columna cliente_codigo + + #[BelongsTo(Cliente::class, foreignKey: 'clienteCodigo')] + public ?Cliente $cliente = null; + + #[HasMany(Detalle::class, foreignKey: 'facturaCodigo')] + public array $detalles = []; +} +``` + +Atributos de relación, todos `Attribute::TARGET_PROPERTY`: + +| Atributo | FK | Cardinalidad cargada | +|---|---|---| +| `#[BelongsTo(Class, foreignKey: string)]` | En la tabla **actual** | 1 modelo | +| `#[HasOne(Class, foreignKey: string)]` | En la tabla **relacionada** | 1 modelo | +| `#[HasMany(Class, foreignKey: string)]` | En la tabla **relacionada** | `array` de modelos | +| `#[BelongsToMany(Class, through: 'pivote', foreignPivotKey: 'x', relatedPivotKey: 'y')]` | Tabla pivote explícita | `array` de modelos | + +**La propiedad de relación lleva el nombre del rol**, sin sufijo: `$cliente`, no `$clienteRel`. +`Rel` no significaba nada y obligaba a inventar sufijos cuando coexistían FK y relación. La +propiedad de FK usa el mismo sustantivo con sufijo `Codigo` (`$clienteCodigo`), que es exactamente +el nombre de la columna. + +**`BelongsToMany` funciona** porque los metadatos de pivote son obligatorios en el atributo, no +inferidos de una clave `$config['tableName']` que nunca existió. Es la corrección directa del bug +#2 del legado. + +Clase relacionada: `class_exists()` sobre el valor recibido; si es un string no-FQCN, se resuelve +bajo el namespace de la clase declarante. No existe `models\{$name}` hardcodeado: eso acoplaba el ORM +a la aplicación consumidora (violación de autosuficiencia). + +### 8.2 Carga explícita + +```php +$cliente = $factura->cliente; // null si no se cargó (no lazy) +$repo->refreshRelations($factura, ['cliente']); // carga en la instancia +$repo->refreshRelations($factura); // todas las declaradas +``` + +`refreshRelations()` reemplaza a `loadRelations()` por simetría con `Model::refresh()`: ambos +refrescan estado desde la base. `load` sugería construir algo nuevo; aquí se puebla una instancia. + +No hay lazy loading por proxy. La propiedad empieza en `null`/`[]` y solo cambia por carga +explícita o eager loading. Esto es una consecuencia directa de KISS: los proxies mágicos con +`__get` son la principal fuente de bugs irrastreables de los ORM grandes. + +### 8.3 Eager loading + +```php +$repo->find(with: ['cliente', 'cliente.ciudad']); // lista de rutas +$repo->find(with: true); // todas, 1 nivel +$repo->find(with: ['cliente' => ['ciudad', 'zona']]); // anidado explícito +``` + +Reglas: + +1. **Una consulta por relación y nivel.** Sin N+1. +2. La profundidad **no** es un entero opaco: se declara en la lista de relaciones. + `with: true` = todas las relaciones de primer nivel, **y solo esas**. El legado propagaba + `only = []` en niveles anidados, lo que cargaba *todas* las relaciones de tercer nivel sin + que el llamante lo pidiera; coste imprevisible. +3. Relación declarada inexistente → `MetadataException` (nunca se ignora). +4. Relación no cargable por falta de fila → la propiedad queda en `null`/`[]` (su valor inicial). +5. Hay un límite duro de 3 niveles; superarlo lanza `ConfigurationException` (evita el producto + cartesiano accidental). + +Si el consumidor necesita un grafo mayor, compone llamadas a `refreshRelations()`. + +--- + +## 9. Conexión y transacciones + +```php +$orm->transaction(function () use ($orm) { + $orm->repository(Usuario::class)->save($u); + $orm->repository(Factura::class)->save($f); +}); +``` + +`Orm::transaction(callable): mixed` envuelve begin/commit/rollBack, **anida** con savepoints y +propaga la excepción original. El legado dejaba que el caller gestionara el `PDO`: correcto en +teoría, en práctica cada controlador repetía `try/catch/rollBack` con omisiones. + +`Connection` expone `begin()`, `commit()`, `rollBack()` y `pdo()`. El `PDO` crudo queda accesible +para casos que la librería no cubre, sin que el resto del código lo use. + +--- + +## 10. Cross-cutting opcional + +Todas son **interfaces** que la librería define y el consumidor implementa. La librería aporta +cero implementaciones concretas salvo la indicada. + +### 10.1 Logging (PSR-3) + +`Orm::fromArray([... 'logger' => $psrLogger])`. Se loguean: SQL lento (> `slowQueryMs`, default +500), y errores SQL antes de relanzarlos. Sin logger, no hay logs (no `error_log()` global). + +### 10.2 Reloj + +`Support\Clock` (interface). Implementación por defecto `SystemClock`. Necesario para testear +`beforeInsert` que asigna `creadoEn`. + +### 10.3 Auditoría + +```php +interface AuditListener +{ + /** @param array|null $before null en INSERT */ + public function onWrite(string $table, string|int $pk, string $action, ?array $before, array $after): void; +} +``` + +`Orm::fromArray(['auditListener' => new MiAuditoria()])`. Se invoca tras commit exitoso de +`save`/`update`/`delete`. El valor de `$action` es uno de `'insert'`, `'update'`, `'delete'` +(minúsculas, mismo vocabulario que los métodos públicos). **No** hay tabla de auditoría en la +librería: la implementación la decide el consumidor (la spec de referencia asumía una clase y una +tabla concretas, acoplándola al ERP). + +--- + +## 11. Errores + +Todas las excepciones heredan de `Camelia\Orm\Exception\OrmException` (extends `\RuntimeException`). +El sufijo `Exception` se mantiene en todos por coherencia y porque el descubrimiento por nombre +es parte de la API: `catch (DuplicateKeyException)` debe leerse sin ambigüedad. + +``` +OrmException +├── ConfigurationException ← config/entorno inválida +├── MetadataException ← modelo mal declarado (mensaje con clase + regla M#) +├── CriteriaException ← columna desconocida / operador inválido +├── ValidationException ← validate() no vacío; errors(): array> +├── PartialModelException ← save/update sobre modelo parcial +├── RecordNotFoundException ← findByPkOrFail/firstOrFail +└── DatabaseException ← envoltorio de PDOException + ├── DuplicateKeyException + ├── ForeignKeyViolationException + └── LockTimeoutException +``` + +`DatabaseException::fromPdoException(PDOException $e, string $context): self` mapea por +`SQLSTATE`: + +| SQLSTATE | Subclase | +|---|---| +| `23000` + errores `1062`/`1555`/`1586` | `DuplicateKeyException` | +| `23000` + `1451`/`1452` | `ForeignKeyViolationException` | +| `HY000` + `1205`/`1213` | `LockTimeoutException` | +| otro | `DatabaseException` con `previous` | + +**No hay degradación.** La regla del legado ("las lecturas degradan, las escrituras fallan") se +elimina: un fallo de lectura que retorna `[]` es indistinguible de "no hay filas" y convierte +cualquier bug de conexión en un bug de negocio fantasma. Quien quiera degradar: + +```php +try { $lista = $repo->find([...]); } catch (DatabaseException) { $lista = []; } +``` +y decide qué hacer, en su capa. + +`DatabaseException` expone `sql()`, `params()` y `context()` para logging y depuración. + +--- + +## 12. Generación de DDL — **no implementada** + +> **Estado: pendiente.** Esta sección describe un componente que **no existe** en la implementación +> actual. No hay `SchemaGenerator` ni `SchemaInspector`, y `#[Length]`, `#[Precision]`, `#[Unique]`, +> `#[UniqueGroup]` no los lee ningún componente. `#[Index]` solo marca `PropertyMetadata::$indexed`. +> +> El DDL se gestiona **fuera** de la librería: la aplicación aplica su propio SQL con su herramienta +> de migraciones. Cuando el generador se implemente, el contrato previsto es: + +```php +$ddl = (new SchemaGenerator())->createTable(Usuario::class); +// CREATE TABLE `usuarios` (...) +``` + +Leería `ClassMetadata` + `#[Length]`/`#[Precision]`/`#[Unique]`/`#[Index]`, devolvería `string`, no +ejecutaría nada y se probaría con golden files. + +--- + +## 13. Contrato de calidad + +| Requisito | Umbral | +|---|---| +| Cobertura de líneas | ≥ 90 % (requiere `xdebug` o `pcov`) | +| PHPStan | nivel 8, `phpVersion: 80200`, sin `ignoreErrors` | +| Mago formatter | `mago fmt --check` limpio, `php-version = "8.2"` fijado en `mago.toml` | +| Mago linter | `mago lint` sin hallazgos (umbrales de métricas y reglas desactivadas documentados en `mago.toml`) | +| Mago analyzer | `mago analyze` sin hallazgos; `mago-baseline.toml` acepta solo los `mixed` de PDO | +| Tests sin base de datos real | obligatorios: `Connection` se sustituye por un `FakeConnection` que registra SQL+params | +| Tests con base real | integración en `tests/Integration/`, requieren `CAMELIA_TEST_DSN`; se saltan (no fallan) si no existe | +| Semver | `@api` en PHPDoc para clases estables; lo no marcado puede cambiar en menor | + +### 13.1 Estructura de tests + +``` +tests/ +├── Unit/ ← todo lo que no toca PDO +│ ├── Metadata/ +│ ├── Query/ ← golden SQL (assert de sql+params, no de resultado) +│ ├── Persistence/ +│ └── Support/ +└── Integration/ ← fixtures SQL, skip si no hay DSN +``` + +Para SQL, la aserción es sobre `toSql()` (string + params), no sobre filas. Es la única forma de +probar un compilador sin la base. Un test de integración solo verifica que el SQL compilado +**ejecuta** contra MariaDB, no qué ejecuta. + +--- + +## 14. Guía de desarrollo de la librería + +Uso normal: + +```bash +composer install +composer fmt # aplica mago fmt +composer fmt:check # CI: formateo limpio +composer lint # CI: mago lint +composer analyze # CI: mago analyze +composer phpstan # CI: PHPStan nivel 8 +composer test # CI: PHPUnit (unit) +composer check # encadena los cinco gates, en orden +composer test:integration # + MariaDB, requiere CAMELIA_TEST_DSN +``` + +Orden obligatorio del gate: `fmt:check` → `lint` → `analyze` → `phpstan` → `test`. Un commit a +`main` requiere los cinco verdes. `composer check` los encadena; no se acepta PR con uno en rojo. + +### 14.1 Nueva funcionalidad: checklist + +- [ ] ¿Cambia la API pública? → entrada en `CHANGELOG.md` + `@api` o no. +- [ ] ¿Genera SQL? → test golden en `tests/Unit/Query/`. +- [ ] ¿Lee atributos? → añadir la regla a la tabla de §5 y a `MetadataFactory`. +- [ ] ¿Toca `Connection`? → mantener el invariante `execute(array)`, nunca `bindParam`. +- [ ] ¿Añade un error? → subclase concreta de §11, no `OrmException` genérica. + +### 14.2 Anti-patrones prohibidos (con el principio que protegen) + +| Anti-patrón | Principio | +|---|---| +| Retornar valor vacío ante excepción SQL | SoC: el ORM ejecuta; el consumidor decide | +| Estado estático (singletons, caches globales fuera de `MetadataCache`) | SOLID: sustituibilidad y tests | +| Puerta de entrada duplicada para la misma operación | KISS | +| Helpers globales (`functions.php`) | autosuficiencia: no contaminar el consumidor | +| Comportamiento distinto entre dos APIs equivalentes | DRY | +| Atributos sin efecto runtime | KISS: no mentir | + +--- + +## 15. Ejemplo integrador + +```php +// 1. Arranque +$orm = Orm::fromEnv(); + +// 2. Lectura +$repo = $orm->repository(Facturacion::class); + +$pendientes = $repo->query() + ->where('estado', 'PENDIENTE') + ->where('fecha', Cond::between('2024-01-01', '2024-12-31')) + ->orderByDesc('fecha') + ->with(['cliente.ciudad']) + ->page(page: 1, perPage: 25); + +// 3. Escritura transaccional +$orm->transaction(function () use ($orm, $pendientes) { + foreach ($pendientes->items as $factura) { + $factura->estado = 'PAGADA'; + $orm->repository(Facturacion::class)->update($factura); + } +}); + +// 4. Serialización +$json = $pendientes->items[0]->toJson(); +``` + +--- + +## 16. Glosario de decisiones + +| Tema | Decisión | Alternativa descartada | +|---|---|---| +| Estado de entidad | Propiedades públicas + `hydrate()` | Setters mágicos, `ArrayAccess` | +| Persistencia | `Repository` explícito | `$model->save()` (acopla entidad a BD) | +| Guardar | `save()` para ambos casos, `update()` para afirmar existencia | `insert()`/`update()` separados y elegidos por el llamante | +| Actualización parcial | `patch($pk, $values)` | `update($pk, $values)` sobrecargada | +| Lectura | Prefijo `find` (`find`, `findFirst`, `findByPk`) | `findAll`/`findOne`/`find` mezclados | +| Relaciones | Carga explícita / eager declarativo | Lazy por proxy (`__get`) | +| Nombre de propiedad de relación | Nombre del rol (`$cliente`) | Sufijo `Rel` (`$clienteRel`) | +| Errores de lectura | Lanzar | Degradar a `[]` | +| Transacciones | `Orm::transaction(callable)` | Gestión manual del PDO | +| Query | Inmutable | Mutable (fuga de estado entre tests) | +| Auditoría | `AuditListener` opcional | Tabla hardcodeada | +| Filtros | `Cond` estático | Funciones globales `_in()`, `_or()` | +| Nombres de columna | `#[Column]` o `camelToSnake` | Sin convención; siempre explícito | +| Interfaz vs implementación | `Connection` (rol) / `PdoConnection` (driver) | Sufijo `Interface` en todas | + +--- + +## 17. Checklist de nomenclatura (aplicar en cada PR) + +Un PR que introduce un nombre nuevo debe responder: + +- [ ] ¿Está el término en el glosario de §0.2? Si no, ¿debería estarlo? +- [ ] ¿La clase dice **qué es** y no **qué hace por dentro**? (`CriteriaCompiler` sí; `QueryHelper` no) +- [ ] ¿El método sigue la regla `find*` (lectura) / verbo de destino (escritura)? +- [ ] ¿El parámetro reusa un nombre canónico (`$criteria`, `$order`, `$with`, `$pk`, `$page`, `$perPage`)? +- [ ] ¿`...Column()` devuelve columna y su versión sin sufijo devuelve propiedad? +- [ ] ¿El booleano empieza por `is`/`has`/`can`? +- [ ] ¿Introduce un sufijo de §0.3 o un nombre de §0.4? Entonces no. +- [ ] Si es `@internal`, ¿está marcado en el PHPDoc? diff --git a/mago-baseline.toml b/mago-baseline.toml new file mode 100644 index 0000000..70238c0 --- /dev/null +++ b/mago-baseline.toml @@ -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`." +count = 1 + +[[issues]] +file = "src/Connection/ConnectionFactory.php" +code = "possibly-undefined-string-array-index" +message = "Possibly undefined array key `string('host')` accessed on `array`." +count = 1 + +[[issues]] +file = "src/Connection/ConnectionFactory.php" +code = "possibly-undefined-string-array-index" +message = "Possibly undefined array key `string('user')` accessed on `array`." +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`, but provided type `ReflectionClass` 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`) is already known to be `class-string`.' +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>`, but got `non-empty-array|string, Camelia\Orm\Repository<('T.camelia\orm\orm::repository() extends Camelia\Orm\Model)>|Camelia\Orm\Repository>`.''' +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`." +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|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`, 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`, 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}>`, 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|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|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`, 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`.' +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 diff --git a/mago.toml b/mago.toml new file mode 100644 index 0000000..c72b3ea --- /dev/null +++ b/mago.toml @@ -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 diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..301f186 --- /dev/null +++ b/phpstan.neon @@ -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 diff --git a/phpunit.integration.xml.dist b/phpunit.integration.xml.dist new file mode 100644 index 0000000..a09c88f --- /dev/null +++ b/phpunit.integration.xml.dist @@ -0,0 +1,17 @@ + + + + + tests/Integration + + + + + + diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..f62925e --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,20 @@ + + + + + tests/Unit + + + + + src + + + diff --git a/src/Attribute/AutoIncrement.php b/src/Attribute/AutoIncrement.php new file mode 100644 index 0000000..b380e92 --- /dev/null +++ b/src/Attribute/AutoIncrement.php @@ -0,0 +1,11 @@ + $related + */ + public function __construct( + public string $related, + public string $foreignKey, + ) {} +} diff --git a/src/Attribute/BelongsToMany.php b/src/Attribute/BelongsToMany.php new file mode 100644 index 0000000..0dceef0 --- /dev/null +++ b/src/Attribute/BelongsToMany.php @@ -0,0 +1,22 @@ + $related + */ + public function __construct( + public string $related, + public string $through, + public string $foreignPivotKey, + public string $relatedPivotKey, + ) {} +} diff --git a/src/Attribute/Column.php b/src/Attribute/Column.php new file mode 100644 index 0000000..18e11e9 --- /dev/null +++ b/src/Attribute/Column.php @@ -0,0 +1,16 @@ + $class */ + public function __construct( + public string $class, + ) {} +} diff --git a/src/Attribute/Guarded.php b/src/Attribute/Guarded.php new file mode 100644 index 0000000..4ab3566 --- /dev/null +++ b/src/Attribute/Guarded.php @@ -0,0 +1,11 @@ + $related + */ + public function __construct( + public string $related, + public string $foreignKey, + ) {} +} diff --git a/src/Attribute/HasOne.php b/src/Attribute/HasOne.php new file mode 100644 index 0000000..f541b01 --- /dev/null +++ b/src/Attribute/HasOne.php @@ -0,0 +1,20 @@ + $related + */ + public function __construct( + public string $related, + public string $foreignKey, + ) {} +} diff --git a/src/Attribute/Ignore.php b/src/Attribute/Ignore.php new file mode 100644 index 0000000..20dd6bf --- /dev/null +++ b/src/Attribute/Ignore.php @@ -0,0 +1,13 @@ + $params + */ + public function execute(string $sql, array $params = []): int; + + /** + * Executes a statement and returns every row. + * + * @param list $params + * @return list> + */ + public function select(string $sql, array $params = []): array; + + /** + * Runs one statement and returns the first column of the first row. + * + * @param list $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; +} diff --git a/src/Connection/ConnectionFactory.php b/src/Connection/ConnectionFactory.php new file mode 100644 index 0000000..ba9f778 --- /dev/null +++ b/src/Connection/ConnectionFactory.php @@ -0,0 +1,117 @@ + $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; + } +} diff --git a/src/Connection/PdoConnection.php b/src/Connection/PdoConnection.php new file mode 100644 index 0000000..8b7835c --- /dev/null +++ b/src/Connection/PdoConnection.php @@ -0,0 +1,213 @@ + */ + private array $statements = []; + + /** @var list LRU order, most recent last */ + private array $lru = []; + + /** @var list 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> $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]); + } + } +} diff --git a/src/Exception/ConfigurationException.php b/src/Exception/ConfigurationException.php new file mode 100644 index 0000000..5b897b6 --- /dev/null +++ b/src/Exception/ConfigurationException.php @@ -0,0 +1,41 @@ + $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, + )); + } +} diff --git a/src/Exception/CriteriaException.php b/src/Exception/CriteriaException.php new file mode 100644 index 0000000..4bd9596 --- /dev/null +++ b/src/Exception/CriteriaException.php @@ -0,0 +1,34 @@ + $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)); + } +} diff --git a/src/Exception/DatabaseException.php b/src/Exception/DatabaseException.php new file mode 100644 index 0000000..921d6ed --- /dev/null +++ b/src/Exception/DatabaseException.php @@ -0,0 +1,72 @@ + $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 $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 */ + public function params(): array + { + return $this->params; + } + + public function context(): string + { + return $this->context; + } +} diff --git a/src/Exception/DuplicateKeyException.php b/src/Exception/DuplicateKeyException.php new file mode 100644 index 0000000..bbc7715 --- /dev/null +++ b/src/Exception/DuplicateKeyException.php @@ -0,0 +1,10 @@ +> $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> */ + public function errors(): array + { + return $this->errors; + } + + public function model(): string + { + return $this->model; + } +} diff --git a/src/Metadata/ClassMetadata.php b/src/Metadata/ClassMetadata.php new file mode 100644 index 0000000..f7a4869 --- /dev/null +++ b/src/Metadata/ClassMetadata.php @@ -0,0 +1,151 @@ + keyed by property name */ + private array $properties; + + /** @var array column => property */ + private array $propertyByColumn = []; + + /** @var list */ + private array $writable; + + /** + * @param class-string<\Camelia\Orm\Model> $class + * @param array $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 */ + 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 */ + public function relations(): array + { + return array_values(array_filter( + $this->properties, + static fn(PropertyMetadata $p): bool => $p->relation !== null, + )); + } + + /** @return list */ + public function indexed(): array + { + return array_values(array_filter( + $this->properties, + static fn(PropertyMetadata $p): bool => $p->indexed, + )); + } + + /** @return list */ + 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 */ + public function knownKeys(): array + { + return array_values(array_unique(array_merge( + array_keys($this->properties), + array_keys($this->propertyByColumn), + ))); + } +} diff --git a/src/Metadata/Constraint.php b/src/Metadata/Constraint.php new file mode 100644 index 0000000..f08784a --- /dev/null +++ b/src/Metadata/Constraint.php @@ -0,0 +1,24 @@ + */ + 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 = []; + } +} diff --git a/src/Metadata/MetadataFactory.php b/src/Metadata/MetadataFactory.php new file mode 100644 index 0000000..600d5ea --- /dev/null +++ b/src/Metadata/MetadataFactory.php @@ -0,0 +1,286 @@ + $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 $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 $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 $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); + } + } +} diff --git a/src/Metadata/PropertyMetadata.php b/src/Metadata/PropertyMetadata.php new file mode 100644 index 0000000..e5bc4ce --- /dev/null +++ b/src/Metadata/PropertyMetadata.php @@ -0,0 +1,60 @@ + $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; + } +} diff --git a/src/Metadata/RelationMetadata.php b/src/Metadata/RelationMetadata.php new file mode 100644 index 0000000..0f2a0b5 --- /dev/null +++ b/src/Metadata/RelationMetadata.php @@ -0,0 +1,33 @@ + $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; + } +} diff --git a/src/Model.php b/src/Model.php new file mode 100644 index 0000000..8c9c934 --- /dev/null +++ b/src/Model.php @@ -0,0 +1,380 @@ +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 $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 $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 $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|null $only property names to include + * @return array + */ + 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> 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; + } +} diff --git a/src/Orm.php b/src/Orm.php new file mode 100644 index 0000000..431d916 --- /dev/null +++ b/src/Orm.php @@ -0,0 +1,153 @@ +> */ + 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 $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 $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 $class + * @return Repository + */ + public function repository(string $class): Repository + { + /** @var Repository $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, + ); + } +} diff --git a/src/Pagination/Page.php b/src/Pagination/Page.php new file mode 100644 index 0000000..511fe61 --- /dev/null +++ b/src/Pagination/Page.php @@ -0,0 +1,92 @@ + $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 $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>, + * 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, + ); + } +} diff --git a/src/Persistence/AuditListener.php b/src/Persistence/AuditListener.php new file mode 100644 index 0000000..440f905 --- /dev/null +++ b/src/Persistence/AuditListener.php @@ -0,0 +1,27 @@ +|null $before null on insert + * @param array $after + */ + public function onWrite( + string $table, + int|string $pk, + string $action, + ?array $before, + array $after, + ): void; +} diff --git a/src/Persistence/Persister.php b/src/Persistence/Persister.php new file mode 100644 index 0000000..9647bbf --- /dev/null +++ b/src/Persistence/Persister.php @@ -0,0 +1,312 @@ +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 $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 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|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 + */ + 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|null $before + * @param array $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); + } + } +} diff --git a/src/Persistence/Validator.php b/src/Persistence/Validator.php new file mode 100644 index 0000000..c2a5e9a --- /dev/null +++ b/src/Persistence/Validator.php @@ -0,0 +1,63 @@ +> 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; + } +} diff --git a/src/Query/Cond.php b/src/Query/Cond.php new file mode 100644 index 0000000..60ad407 --- /dev/null +++ b/src/Query/Cond.php @@ -0,0 +1,122 @@ + $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 $values */ + public static function in(array $values): self + { + return new self(self::OP_IN, array_values($values)); + } + + /** @param list $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 $params + */ + public static function raw(string $sql, array $params = []): self + { + return new self(self::OP_RAW, array_values($params), $sql); + } +} diff --git a/src/Query/CriteriaCompiler.php b/src/Query/CriteriaCompiler.php new file mode 100644 index 0000000..71273c0 --- /dev/null +++ b/src/Query/CriteriaCompiler.php @@ -0,0 +1,103 @@ + $criteria + * @return array{0: string, 1: list} 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} + */ + 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) + ); + } +} diff --git a/src/Query/Dialect.php b/src/Query/Dialect.php new file mode 100644 index 0000000..a9f813c --- /dev/null +++ b/src/Query/Dialect.php @@ -0,0 +1,25 @@ +} + */ + public function renderCondition(string $quotedColumn, Cond $cond): array; + + /** @param list $values */ + public function placeholders(array $values): string; + + public function limitClause(?int $limit, ?int $offset): string; +} diff --git a/src/Query/GroupCond.php b/src/Query/GroupCond.php new file mode 100644 index 0000000..7c5ffb1 --- /dev/null +++ b/src/Query/GroupCond.php @@ -0,0 +1,44 @@ + */ + 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 + */ + public function parts(): array + { + return $this->parts; + } + + public function isEmpty(): bool + { + return $this->parts === []; + } +} diff --git a/src/Query/MySqlDialect.php b/src/Query/MySqlDialect.php new file mode 100644 index 0000000..d3d36a1 --- /dev/null +++ b/src/Query/MySqlDialect.php @@ -0,0 +1,96 @@ +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 $values + * @return array{0: string, 1: list} + */ + 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 $values + * @return array{0: string, 1: list} + */ + 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]; + } +} diff --git a/src/Query/Query.php b/src/Query/Query.php new file mode 100644 index 0000000..98da89d --- /dev/null +++ b/src/Query/Query.php @@ -0,0 +1,403 @@ + $repository + */ + private function __construct( + private readonly Repository $repository, + private readonly Connection $connection, + private readonly QueryBuilder $builder, + private readonly QueryState $state, + ) {} + + /** + * @param Repository $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 $values + */ + public function whereIn(string $column, array $values): self + { + return $this->where($column, Cond::in($values)); + } + + /** + * @param list $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 ...$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 + */ + 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 + */ + 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} + */ + 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} + */ + 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} + */ + 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 + */ + 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); + } +} diff --git a/src/Query/QueryBuilder.php b/src/Query/QueryBuilder.php new file mode 100644 index 0000000..43679db --- /dev/null +++ b/src/Query/QueryBuilder.php @@ -0,0 +1,260 @@ + $criteria + * @param list $order + * @param list|null $columns properties to select + * @return array{sql: string, params: list} + */ + 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 $criteria + * @return array{sql: string, params: list} + */ + 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 $criteria + * @return array{sql: string, params: list} + */ + 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 $values keyed by PROPERTY + * @return array{sql: string, params: list} + */ + 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 $values keyed by PROPERTY + * @return array{sql: string, params: list} + */ + 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} + */ + 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|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 $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); + } +} diff --git a/src/Query/QueryState.php b/src/Query/QueryState.php new file mode 100644 index 0000000..1159d2a --- /dev/null +++ b/src/Query/QueryState.php @@ -0,0 +1,103 @@ + $criteria + * @param list $order + * @param list}> $groups + * @param list|null $columns + * @param true|array|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 $criteria + */ + public function withCriteria(array $criteria): self + { + return $this->with(['criteria' => $criteria]); + } + + /** + * @param list $order + */ + public function withOrder(array $order): self + { + return $this->with(['order' => $order]); + } + + /** + * @param list}> $groups + */ + public function withGroups(array $groups): self + { + return $this->with(['groups' => $groups]); + } + + /** + * @param list $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 $with + */ + public function withRelations(bool|array $with): self + { + return $this->with(['with' => $with]); + } + + /** + * @param array $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, + ); + } +} diff --git a/src/Repository.php b/src/Repository.php new file mode 100644 index 0000000..f521aaa --- /dev/null +++ b/src/Repository.php @@ -0,0 +1,783 @@ + $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 $criteria + * @param list $order + * @param true|array|false $with + * @return list + */ + 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 $criteria + * @param list $order + * @param true|array|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|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|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 $criteria + * @param array $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 $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 $criteria + */ + public function exists(array $criteria = []): bool + { + return $this->count($criteria) > 0; + } + + /** + * @param array $criteria + */ + public function sum(string $column, array $criteria = []): float + { + return (float) ($this->aggregate('SUM', $column, $criteria) ?? 0.0); + } + + /** + * @param array $criteria + */ + public function avg(string $column, array $criteria = []): float + { + return (float) ($this->aggregate('AVG', $column, $criteria) ?? 0.0); + } + + /** + * @param array $criteria + */ + public function max(string $column, array $criteria = []): ?float + { + return $this->aggregate('MAX', $column, $criteria); + } + + /** + * @param array $criteria + */ + public function min(string $column, array $criteria = []): ?float + { + return $this->aggregate('MIN', $column, $criteria); + } + + /** + * @param array $criteria + * @param list $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 $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 $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 $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> $rows + * @param list|null $columns properties actually selected + * @param true|array|false $with + * @return list + */ + 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> $rows + * @return list + */ + 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 $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 $models + * @param true|array|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 $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 $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 $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 $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|list $with + * @return list|array}> + */ + 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|list $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 $class + * @return Repository + */ + private function relatedRepository(string $class): self + { + return new self($this->connection, $class, $this->dialect, $this->persister); + } + + /** + * @internal + */ + public function connection(): Connection + { + return $this->connection; + } +} diff --git a/src/Support/Clock.php b/src/Support/Clock.php new file mode 100644 index 0000000..81e5e44 --- /dev/null +++ b/src/Support/Clock.php @@ -0,0 +1,15 @@ + 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); + } +} diff --git a/src/Support/SystemClock.php b/src/Support/SystemClock.php new file mode 100644 index 0000000..c152ccf --- /dev/null +++ b/src/Support/SystemClock.php @@ -0,0 +1,18 @@ + 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 + */ + 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); + } +} diff --git a/tests/Fixture/Articulo.php b/tests/Fixture/Articulo.php new file mode 100644 index 0000000..b06e848 --- /dev/null +++ b/tests/Fixture/Articulo.php @@ -0,0 +1,29 @@ + */ + #[BelongsToMany( + related: Etiqueta::class, + through: 'articulo_etiqueta', + foreignPivotKey: 'articulo_codigo', + relatedPivotKey: 'etiqueta_codigo', + )] + public array $etiquetas = []; +} diff --git a/tests/Fixture/ConHooks.php b/tests/Fixture/ConHooks.php new file mode 100644 index 0000000..b59afdb --- /dev/null +++ b/tests/Fixture/ConHooks.php @@ -0,0 +1,31 @@ +creadoPorHook = 'insert'; + } + + protected function beforeUpdate(): void + { + $this->creadoPorHook = 'update'; + } +} diff --git a/tests/Fixture/Detalle.php b/tests/Fixture/Detalle.php new file mode 100644 index 0000000..3c7e241 --- /dev/null +++ b/tests/Fixture/Detalle.php @@ -0,0 +1,21 @@ + Etiqueta -> Factura -> Usuario. + */ +#[TableName('etiquetas')] +final class Etiqueta extends Model +{ + #[PrimaryKey] + #[AutoIncrement] + public ?int $codigo = null; + + public string $nombre = ''; + + /** @var array */ + #[BelongsToMany( + related: Factura::class, + through: 'etiqueta_factura', + foreignPivotKey: 'etiqueta_codigo', + relatedPivotKey: 'factura_codigo', + )] + public array $facturas = []; +} diff --git a/tests/Fixture/Factura.php b/tests/Fixture/Factura.php new file mode 100644 index 0000000..e362966 --- /dev/null +++ b/tests/Fixture/Factura.php @@ -0,0 +1,32 @@ + */ + #[HasMany(Detalle::class, foreignKey: 'facturaCodigo')] + public array $detalles = []; +} diff --git a/tests/Fixture/Invalid/ColumnaDuplicada.php b/tests/Fixture/Invalid/ColumnaDuplicada.php new file mode 100644 index 0000000..41a7761 --- /dev/null +++ b/tests/Fixture/Invalid/ColumnaDuplicada.php @@ -0,0 +1,22 @@ +}> */ + public array $executed = []; + + /** @var list}> */ + public array $selected = []; + + /** @var list> rows returned by select() */ + public array $rows = []; + + /** @var list>> sequential responses; when set, consumed before $rows */ + public array $rowBatches = []; + + /** @var list 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 */ + public function lastParams(): array + { + $entries = $this->selected === [] ? $this->executed : $this->selected; + + if ($entries === []) { + return []; + } + + return $entries[count($entries) - 1]['params']; + } +} diff --git a/tests/Unit/EagerLoadingTest.php b/tests/Unit/EagerLoadingTest.php new file mode 100644 index 0000000..4f1960f --- /dev/null +++ b/tests/Unit/EagerLoadingTest.php @@ -0,0 +1,205 @@ +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 + */ + private function facturaRow(int $codigo, int $usuarioCodigo): array + { + return [ + 'codigo' => (string) $codigo, + 'usuario_codigo' => (string) $usuarioCodigo, + 'importe_total' => '10.5', + ]; + } + + /** + * @return array + */ + private function usuarioRow(int $codigo, string $nombre): array + { + return [ + 'codigo' => (string) $codigo, + 'nombre' => $nombre, + 'correo' => 'a@x', + 'password_hash' => '', + 'activo' => '1', + 'apodo' => null, + 'clave' => '', + ]; + } +} diff --git a/tests/Unit/Metadata/MetadataFactoryTest.php b/tests/Unit/Metadata/MetadataFactoryTest.php new file mode 100644 index 0000000..8a7bb72 --- /dev/null +++ b/tests/Unit/Metadata/MetadataFactoryTest.php @@ -0,0 +1,139 @@ +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); + } +} diff --git a/tests/Unit/ModelTest.php b/tests/Unit/ModelTest.php new file mode 100644 index 0000000..b1f4fc1 --- /dev/null +++ b/tests/Unit/ModelTest.php @@ -0,0 +1,166 @@ +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()); + } +} diff --git a/tests/Unit/OrmTest.php b/tests/Unit/OrmTest.php new file mode 100644 index 0000000..6820053 --- /dev/null +++ b/tests/Unit/OrmTest.php @@ -0,0 +1,70 @@ +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()); + } +} diff --git a/tests/Unit/PageTest.php b/tests/Unit/PageTest.php new file mode 100644 index 0000000..25522af --- /dev/null +++ b/tests/Unit/PageTest.php @@ -0,0 +1,59 @@ +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']); + } +} diff --git a/tests/Unit/PersisterTest.php b/tests/Unit/PersisterTest.php new file mode 100644 index 0000000..ca1128f --- /dev/null +++ b/tests/Unit/PersisterTest.php @@ -0,0 +1,177 @@ +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 */ + 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); + } +} diff --git a/tests/Unit/Query/CriteriaCompilerTest.php b/tests/Unit/Query/CriteriaCompilerTest.php new file mode 100644 index 0000000..cedb0e6 --- /dev/null +++ b/tests/Unit/Query/CriteriaCompilerTest.php @@ -0,0 +1,148 @@ +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); + } +} diff --git a/tests/Unit/Query/QueryBuilderTest.php b/tests/Unit/Query/QueryBuilderTest.php new file mode 100644 index 0000000..a18789f --- /dev/null +++ b/tests/Unit/Query/QueryBuilderTest.php @@ -0,0 +1,161 @@ +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); + } +} diff --git a/tests/Unit/QueryTest.php b/tests/Unit/QueryTest.php new file mode 100644 index 0000000..31c97f9 --- /dev/null +++ b/tests/Unit/QueryTest.php @@ -0,0 +1,176 @@ +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); + } +} diff --git a/tests/Unit/RepositoryTest.php b/tests/Unit/RepositoryTest.php new file mode 100644 index 0000000..a7742c0 --- /dev/null +++ b/tests/Unit/RepositoryTest.php @@ -0,0 +1,234 @@ +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 + */ + private function usuarioRow(int $codigo, string $nombre): array + { + return [ + 'codigo' => (string) $codigo, + 'nombre' => $nombre, + 'correo' => 'a@x', + 'password_hash' => '', + 'activo' => '1', + 'apodo' => null, + 'clave' => '', + ]; + } +} diff --git a/tests/Unit/Support/NameConverterTest.php b/tests/Unit/Support/NameConverterTest.php new file mode 100644 index 0000000..961241f --- /dev/null +++ b/tests/Unit/Support/NameConverterTest.php @@ -0,0 +1,33 @@ + 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 + */ + 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')), + ), + ); + } +}