feat: initial commit of camelia/orm

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

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

No files matched your search

+783
View File
@@ -0,0 +1,783 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm;
use Camelia\Orm\Connection\Connection;
use Camelia\Orm\Exception\ConfigurationException;
use Camelia\Orm\Exception\MetadataException;
use Camelia\Orm\Exception\RecordNotFoundException;
use Camelia\Orm\Metadata\ClassMetadata;
use Camelia\Orm\Metadata\PropertyMetadata;
use Camelia\Orm\Metadata\RelationMetadata;
use Camelia\Orm\Pagination\Page;
use Camelia\Orm\Persistence\Persister;
use Camelia\Orm\Query\Cond;
use Camelia\Orm\Query\Dialect;
use Camelia\Orm\Query\MySqlDialect;
use Camelia\Orm\Query\Query;
use Camelia\Orm\Query\QueryBuilder;
use Camelia\Orm\Query\QueryState;
use Camelia\Orm\Support\TypeCaster;
/**
* Public read and write API for one model class.
*
* @api
* @template T of Model
*/
final class Repository
{
private const MAX_RELATION_DEPTH = 3;
private readonly QueryBuilder $builder;
/**
* @param class-string<T> $class
*/
public function __construct(
private readonly Connection $connection,
private readonly string $class,
private readonly Dialect $dialect = new MySqlDialect(),
private readonly ?Persister $persister = null,
) {
$this->builder = new QueryBuilder($this->dialect);
$this->metadata();
}
public function metadata(): ClassMetadata
{
return Model::metadataFor($this->class);
}
/**
* @param array<string, mixed|Cond> $criteria
* @param list<array{0: string, 1: 'ASC'|'DESC'}> $order
* @param true|array<int|string, mixed>|false $with
* @return list<T>
*/
public function find(
array $criteria = [],
array $order = [],
?int $limit = null,
?int $offset = null,
bool|array $with = false,
): array {
$compiled = $this->builder->select($this->metadata(), $criteria, $order, $limit, $offset);
$rows = $this->connection->select($compiled['sql'], $compiled['params']);
return $this->hydrateRows($rows, null, $with === false ? false : $with);
}
/**
* @param array<string, mixed|Cond> $criteria
* @param list<array{0: string, 1: 'ASC'|'DESC'}> $order
* @param true|array<int|string, mixed>|false $with
* @return T|null
*/
public function findFirst(
array $criteria = [],
array $order = [],
bool|array $with = false,
): ?Model {
$rows = $this->find($criteria, $order, 1, null, $with);
return $rows[0] ?? null;
}
/**
* @param true|array<int|string, mixed>|false $with
* @return T|null
*/
public function findByPk(int|string $pk, bool|array $with = false): ?Model
{
return $this->findFirst([$this->metadata()->primaryKey() => $pk], [], $with);
}
/**
* @param true|array<int|string, mixed>|false $with
* @return T
*/
public function findByPkOrFail(int|string $pk, bool|array $with = false): Model
{
$model = $this->findByPk($pk, $with);
if ($model === null) {
throw RecordNotFoundException::byPrimaryKey($this->class, $pk);
}
return $model;
}
/**
* @param array<string, mixed|Cond> $criteria
* @param array<string, mixed> $values
* @return T
*/
public function findOrCreate(array $criteria, array $values = []): Model
{
$found = $this->findFirst($criteria);
if ($found !== null) {
return $found;
}
return $this->create($values + $criteria);
}
/**
* @param array<string, mixed|Cond> $criteria
*/
public function count(array $criteria = []): int
{
$compiled = $this->builder->count($this->metadata(), $criteria);
return (int) $this->connection->scalar($compiled['sql'], $compiled['params']);
}
/**
* @param array<string, mixed|Cond> $criteria
*/
public function exists(array $criteria = []): bool
{
return $this->count($criteria) > 0;
}
/**
* @param array<string, mixed|Cond> $criteria
*/
public function sum(string $column, array $criteria = []): float
{
return (float) ($this->aggregate('SUM', $column, $criteria) ?? 0.0);
}
/**
* @param array<string, mixed|Cond> $criteria
*/
public function avg(string $column, array $criteria = []): float
{
return (float) ($this->aggregate('AVG', $column, $criteria) ?? 0.0);
}
/**
* @param array<string, mixed|Cond> $criteria
*/
public function max(string $column, array $criteria = []): ?float
{
return $this->aggregate('MAX', $column, $criteria);
}
/**
* @param array<string, mixed|Cond> $criteria
*/
public function min(string $column, array $criteria = []): ?float
{
return $this->aggregate('MIN', $column, $criteria);
}
/**
* @param array<string, mixed|Cond> $criteria
* @param list<array{0: string, 1: 'ASC'|'DESC'}> $order
*/
public function page(
array $criteria = [],
array $order = [],
int $page = 1,
int $perPage = 20,
): Page {
$query = $this->query();
foreach ($criteria as $column => $value) {
$query = $query->where((string) $column, $value);
}
foreach ($order as [$column, $direction]) {
$query = $query->orderBy($column, $direction);
}
return $query->page($page, $perPage);
}
public function query(): Query
{
return Query::start(
$this,
new QueryState($this->metadata()),
$this->connection,
$this->builder,
);
}
/**
* @return int|string
*/
public function save(Model $model): int|string
{
return $this->persister()->save($model);
}
/**
* @param array<string, mixed> $values
* @return T
*/
public function create(array $values = []): Model
{
/** @var T $model */
$model = new $this->class();
$model->hydrate($values);
$this->persister()->insert($model);
return $model;
}
public function update(Model $model): void
{
$this->persister()->update($model);
}
public function delete(Model $model): void
{
$this->persister()->delete($model);
}
/**
* @param array<string, mixed> $values keyed by property or column
*/
public function patch(int|string $pk, array $values): void
{
$this->persister()->patch($this->instance(), $pk, $values);
}
public function remove(int|string $pk): bool
{
return $this->persister()->remove($this->instance(), $pk);
}
/**
* Loads the declared relationships of an already hydrated model into the instance.
*
* @param list<string> $only empty means every declared relationship
*/
public function refreshRelations(Model $model, array $only = []): void
{
$this->loadRelationsInto([$model], $only === [] ? true : $only, 0);
}
/**
* Hydrates database rows into models and applies eager loading.
*
* @internal used by Query
* @param list<array<string, mixed>> $rows
* @param list<string>|null $columns properties actually selected
* @param true|array<int|string, mixed>|false $with
* @return list<T>
*/
public function hydrateRows(array $rows, ?array $columns, bool|array $with): array
{
$models = $this->hydrate($rows);
if ($columns !== null && $columns !== []) {
foreach ($models as $model) {
$model->markPartial();
}
}
if ($with !== false && $with !== []) {
$this->loadRelationsInto($models, $with, 0);
}
return $models;
}
/**
* @internal
* @param list<array<string, mixed>> $rows
* @return list<T>
*/
public function hydrate(array $rows): array
{
$metadata = $this->metadata();
$models = [];
foreach ($rows as $row) {
/** @var T $model */
$model = new $this->class();
foreach ($row as $column => $value) {
$property = $metadata->property((string) $column);
if ($property === null) {
continue;
}
$model->set($property, $this->castDatabaseValue(
$metadata->properties()[$property],
$value,
));
}
$models[] = $model;
}
return $models;
}
private function castDatabaseValue(PropertyMetadata $definition, mixed $value): mixed
{
if ($value === null) {
return null;
}
return TypeCaster::cast($value, $definition->type, true, $definition->name);
}
/**
* @param array<string, mixed|Cond> $criteria
*/
private function aggregate(string $function, string $column, array $criteria): ?float
{
$compiled = $this->builder->aggregate($this->metadata(), $column, $function, $criteria);
$value = $this->connection->scalar($compiled['sql'], $compiled['params']);
return $value === null ? null : (float) $value;
}
private function persister(): Persister
{
if ($this->persister !== null) {
return $this->persister;
}
return new Persister($this->connection, $this->builder);
}
private function instance(): Model
{
/** @var T $model */
$model = new $this->class();
return $model;
}
/**
* @param list<Model> $models
* @param true|array<int|string, mixed>|false $with
*/
private function loadRelationsInto(array $models, bool|array $with, int $depth): void
{
if ($with === false) {
return;
}
$metadata = $this->metadata();
$requested = $this->resolveRequestedRelations($metadata, $with);
// Validate every requested path up front: a typo must fail even when no rows matched.
foreach ($requested as $request) {
$this->validateRelationPath(
$metadata,
$request['name'],
$request['nested'],
$depth + 1,
);
}
if ($models === []) {
return;
}
if (($depth + 1) > self::MAX_RELATION_DEPTH) {
throw ConfigurationException::relationDepthExceeded(self::MAX_RELATION_DEPTH);
}
foreach ($requested as $requested) {
$relation = $this->relationMetadata($requested['name']);
$nested = $requested['nested'];
$this->loadOneRelation($models, $relation, $metadata);
if ($nested === []) {
continue;
}
$loaded = [];
foreach ($models as $model) {
/** @var mixed $value */
$value = $model->get($relation->name);
if ($value instanceof Model) {
$loaded[] = $value;
}
if (is_array($value)) {
foreach ($value as $related) {
if (!$related instanceof Model) {
continue;
}
$loaded[] = $related;
}
}
}
$relatedMeta = $relation->relation;
if ($relatedMeta === null) {
continue;
}
$relatedRepository = $this->relatedRepository($relatedMeta->relatedClass);
$relatedRepository->loadRelationsInto($loaded, $nested, $depth + 1);
}
}
/**
* @param list<Model> $models
*/
private function loadOneRelation(
array $models,
PropertyMetadata $property,
ClassMetadata $metadata,
): void {
$relation = $property->relation;
if ($relation === null) {
return;
}
if ($relation->kind === RelationMetadata::KIND_BELONGS_TO_MANY) {
$this->loadBelongsToMany($models, $property);
return;
}
if ($relation->kind === RelationMetadata::KIND_BELONGS_TO) {
$this->loadBelongsTo($models, $property, $metadata);
return;
}
$this->loadHasManyOrOne($models, $property);
}
/**
* @param list<Model> $models
*/
private function loadBelongsTo(
array $models,
PropertyMetadata $property,
ClassMetadata $metadata,
): void {
$relation = $property->relation;
\assert($relation !== null);
$foreignProperty = $metadata->resolveProperty($relation->foreignKey);
if ($foreignProperty === null) {
throw MetadataException::missingForeignKey(
$metadata->class,
$property->name,
$relation->foreignKey,
);
}
$keys = [];
foreach ($models as $model) {
$value = $model->get($foreignProperty);
if ($value !== null && $value !== '') {
$keys[(string) $value] = $value;
}
}
$relatedRepository = $this->relatedRepository($relation->relatedClass);
$relatedMetadata = $relatedRepository->metadata();
$found = [];
if ($keys !== []) {
$records = $relatedRepository->find([
$relatedMetadata->primaryKey() => array_values($keys),
]);
foreach ($records as $record) {
$found[(string) $record->get($relatedMetadata->primaryKey())] = $record;
}
}
foreach ($models as $model) {
$value = $model->get($foreignProperty);
if ($value === null || $value === '') {
continue;
}
$model->set($property->name, $found[(string) $value] ?? null);
}
}
/**
* @param list<Model> $models
*/
private function loadHasManyOrOne(array $models, PropertyMetadata $property): void
{
$relation = $property->relation;
\assert($relation !== null);
$metadata = $this->metadata();
$ownerKey = $metadata->primaryKey();
$keys = [];
foreach ($models as $model) {
$value = $model->get($ownerKey);
if ($value !== null && $value !== '') {
$keys[(string) $value] = $value;
}
}
$relatedRepository = $this->relatedRepository($relation->relatedClass);
$relatedMetadata = $relatedRepository->metadata();
$grouped = [];
if ($keys !== []) {
$records = $relatedRepository->find([
$relation->foreignKey => array_values($keys),
]);
foreach ($records as $record) {
$grouped[(string) $record->get($relation->foreignKey)][] = $record;
}
}
foreach ($models as $model) {
$key = (string) $model->get($ownerKey);
$matches = $grouped[$key] ?? [];
if ($relation->isToMany()) {
$model->set($property->name, $matches);
continue;
}
$model->set($property->name, $matches[0] ?? null);
}
}
/**
* @param list<Model> $models
*/
private function loadBelongsToMany(array $models, PropertyMetadata $property): void
{
$relation = $property->relation;
\assert($relation !== null);
\assert($relation->through !== null);
\assert($relation->foreignPivotKey !== null);
\assert($relation->relatedPivotKey !== null);
$metadata = $this->metadata();
$ownerKey = $metadata->primaryKey();
$keys = [];
foreach ($models as $model) {
$value = $model->get($ownerKey);
if ($value !== null && $value !== '') {
$keys[(string) $value] = $value;
}
}
if ($keys === []) {
foreach ($models as $model) {
$model->set($property->name, []);
}
return;
}
$pivot = $this->dialect->quoteIdentifier($relation->through);
$foreignPivot = $this->dialect->quoteIdentifier($relation->foreignPivotKey);
$relatedPivot = $this->dialect->quoteIdentifier($relation->relatedPivotKey);
$placeholders = implode(', ', array_fill(0, count($keys), '?'));
$sql =
'SELECT '
. $foreignPivot
. ' AS pivot_owner, '
. $relatedPivot
. ' AS pivot_related'
. ' FROM '
. $pivot
. ' WHERE '
. $foreignPivot
. ' IN ('
. $placeholders
. ')';
$rows = $this->connection->select($sql, array_values($keys));
$relatedRepository = $this->relatedRepository($relation->relatedClass);
$relatedMetadata = $relatedRepository->metadata();
$grouped = [];
$relatedKeys = [];
foreach ($rows as $row) {
if (!isset($row['pivot_owner'], $row['pivot_related'])) {
continue;
}
$ownerId = (string) $row['pivot_owner'];
$relatedId = (string) $row['pivot_related'];
$grouped[$ownerId][] = $relatedId;
$relatedKeys[$relatedId] = $row['pivot_related'];
}
$records = [];
if ($relatedKeys !== []) {
foreach ($relatedRepository->find([
$relatedMetadata->primaryKey() => array_values($relatedKeys),
]) as $record) {
$records[(string) $record->get($relatedMetadata->primaryKey())] = $record;
}
}
foreach ($models as $model) {
$ownerId = (string) $model->get($ownerKey);
$related = [];
foreach ($grouped[$ownerId] ?? [] as $relatedId) {
if (!isset($records[$relatedId])) {
continue;
}
$related[] = $records[$relatedId];
}
$model->set($property->name, $related);
}
}
/**
* @param true|array<int|string, mixed>|list<string> $with
* @return list<array{name: string, nested: true|list<string>|array<int|string, mixed>}>
*/
private function resolveRequestedRelations(ClassMetadata $metadata, bool|array $with): array
{
$requested = [];
if ($with === true) {
foreach ($metadata->relations() as $relation) {
$requested[] = ['name' => $relation->name, 'nested' => []];
}
return $requested;
}
foreach ($with as $key => $value) {
if (is_int($key)) {
$path = (string) $value;
$segments = explode('.', $path);
$name = $segments[0];
$nested = array_slice($segments, 1);
// Remaining segments are one nested path, not sibling relations.
$requested[] = [
'name' => $name,
'nested' => $nested === [] ? [] : [implode('.', $nested)],
];
continue;
}
$nestedValue = $value === true || is_array($value) ? $value : [];
$requested[] = ['name' => (string) $key, 'nested' => $nestedValue];
}
return $requested;
}
private function relationMetadata(string $name): PropertyMetadata
{
$metadata = $this->metadata();
if (!$metadata->hasProperty($name) || $metadata->properties()[$name]->relation === null) {
throw MetadataException::unknownRelation($this->class, $name);
}
return $metadata->properties()[$name];
}
/**
* Walks a requested path, validating every hop and enforcing the depth limit.
*
* @param true|array<int|string, mixed>|list<string> $nested
*/
private function validateRelationPath(
ClassMetadata $metadata,
string $name,
bool|array $nested,
int $depth,
): void {
if ($depth > self::MAX_RELATION_DEPTH) {
throw ConfigurationException::relationDepthExceeded(self::MAX_RELATION_DEPTH);
}
if (!$metadata->hasProperty($name) || $metadata->properties()[$name]->relation === null) {
throw MetadataException::unknownRelation($metadata->class, $name);
}
if ($nested === true) {
return;
}
$relation = $metadata->properties()[$name]->relation;
if ($relation === null) {
return;
}
$next = $this->relatedRepository($relation->relatedClass)->metadata();
foreach ($nested as $key => $value) {
if (is_int($key)) {
$segments = explode('.', (string) $value);
$this->validateRelationPath(
$next,
$segments[0],
array_slice($segments, 1),
$depth + 1,
);
continue;
}
$this->validateRelationPath(
$next,
(string) $key,
is_array($value) ? $value : true,
$depth + 1,
);
}
}
/**
* @param class-string<Model> $class
* @return Repository<Model>
*/
private function relatedRepository(string $class): self
{
return new self($this->connection, $class, $this->dialect, $this->persister);
}
/**
* @internal
*/
public function connection(): Connection
{
return $this->connection;
}
}