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

+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* Invalid configuration or environment.
*/
final class ConfigurationException extends OrmException
{
/** @param list<string> $missing */
public static function missingEnvironment(array $missing): self
{
return new self(sprintf('Missing required environment variable(s): %s.', implode(
', ',
$missing,
)));
}
public static function invalidErrorMode(): self
{
return new self(
'The supplied PDO instance must use ERRMODE_EXCEPTION; silent modes are '
. 'incompatible with the library error contract.',
);
}
public static function unknownConnectionOption(string $option): self
{
return new self(sprintf('Unknown connection option "%s".', $option));
}
public static function relationDepthExceeded(int $max): self
{
return new self(sprintf(
'Eager loading is limited to %d nesting levels to avoid accidental cartesian products.',
$max,
));
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* A criteria key is not a declared property or column, or uses an invalid operator.
*/
final class CriteriaException extends OrmException
{
/** @param list<string> $valid */
public static function unknownColumn(string $model, string $key, array $valid): self
{
return new self(sprintf(
'Unknown column "%s" in criteria for "%s". Valid columns: %s.',
$key,
$model,
$valid === [] ? '(none)' : implode(', ', $valid),
));
}
public static function emptyIn(): self
{
return new self(
'Cond::in() requires at least one value; use an empty criterion list instead.',
);
}
public static function invalidOrderDirection(string $direction): self
{
return new self(sprintf('Order direction must be ASC or DESC, got "%s".', $direction));
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
use PDOException;
/**
* Wraps a PDO failure and preserves the SQL and parameters that produced it.
*/
class DatabaseException extends OrmException
{
/**
* @param list<mixed> $params
*/
public function __construct(
string $message,
private readonly string $sql = '',
private readonly array $params = [],
private readonly string $context = '',
?\Throwable $previous = null,
) {
parent::__construct($message, 0, $previous);
}
/**
* Maps a PDOException to the narrowest exception type the SQLSTATE allows.
*
* @param list<mixed> $params
*/
public static function fromPdoException(
PDOException $exception,
string $context,
string $sql = '',
array $params = [],
): self {
$sqlState = (string) $exception->getCode();
$driverCode = (int) ($exception->errorInfo[1] ?? 0);
$message = sprintf('Database error during %s: %s', $context, $exception->getMessage());
if ($sqlState === '23000' && in_array($driverCode, [1062, 1555, 1586], true)) {
return new DuplicateKeyException($message, $sql, $params, $context, $exception);
}
if ($sqlState === '23000' && in_array($driverCode, [1451, 1452], true)) {
return new ForeignKeyViolationException($message, $sql, $params, $context, $exception);
}
if ($sqlState === 'HY000' && in_array($driverCode, [1205, 1213], true)) {
return new LockTimeoutException($message, $sql, $params, $context, $exception);
}
return new self($message, $sql, $params, $context, $exception);
}
public function sql(): string
{
return $this->sql;
}
/** @return list<mixed> */
public function params(): array
{
return $this->params;
}
public function context(): string
{
return $this->context;
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* A unique or primary key constraint was violated.
*/
final class DuplicateKeyException extends DatabaseException {}
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* A foreign key constraint was violated.
*/
final class ForeignKeyViolationException extends DatabaseException {}
+10
View File
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* A lock wait timeout or deadlock aborted the statement.
*/
final class LockTimeoutException extends DatabaseException {}
+110
View File
@@ -0,0 +1,110 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* The model class is not declared according to the metadata rules (M1-M7).
*/
final class MetadataException extends OrmException
{
public static function notAModel(string $class): self
{
return new self(sprintf('[M1] "%s" must extend %s.', $class, \Camelia\Orm\Model::class));
}
public static function missingTableName(string $class): self
{
return new self(sprintf('[M2] "%s" must declare a non-empty #[TableName].', $class));
}
public static function primaryKeyCount(string $class, int $found): self
{
return new self(sprintf(
'[M3] "%s" must declare exactly one #[PrimaryKey]; found %d.',
$class,
$found,
));
}
public static function notPublic(string $class, string $property): self
{
return new self(sprintf('[M4] "%s::$%s" must be public to be mapped.', $class, $property));
}
public static function missingType(string $class, string $property): self
{
return new self(sprintf('[M4] "%s::$%s" must declare a type.', $class, $property));
}
public static function nonAsciiColumn(string $class, string $property, string $column): self
{
return new self(sprintf(
'Column "%s" of "%s::$%s" must be ASCII.',
$column,
$class,
$property,
));
}
public static function invalidRelationProperty(string $class, string $property): self
{
return new self(sprintf(
'[M5] Relationship "%s::$%s" must be nullable (?Model) or an array.',
$class,
$property,
));
}
public static function unknownRelatedClass(
string $class,
string $property,
string $related,
): self {
return new self(sprintf(
'Relationship "%s::$%s" points to unknown class "%s".',
$class,
$property,
$related,
));
}
public static function missingForeignKey(
string $class,
string $property,
string $foreignKey,
): self {
return new self(sprintf(
'Relationship "%s::$%s" declares unknown foreign key property "%s".',
$class,
$property,
$foreignKey,
));
}
public static function duplicateColumn(
string $class,
string $column,
string $first,
string $second,
): self {
return new self(sprintf(
'[M7] "%s" maps properties "%s" and "%s" to the same column "%s".',
$class,
$first,
$second,
$column,
));
}
public static function unknownRelation(string $class, string $property): self
{
return new self(sprintf('"%s::$%s" is not a declared relationship.', $class, $property));
}
public static function unknownProperty(string $class, string $property): self
{
return new self(sprintf('"%s::$%s" is not a mapped property.', $class, $property));
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* Base type of every exception raised by the library.
*/
class OrmException extends \RuntimeException {}
+21
View File
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* A partial model (hydrated through select()) was handed to a write operation.
*/
final class PartialModelException extends OrmException
{
public static function onWrite(string $class, string $operation): self
{
return new self(sprintf(
'Cannot %s a partial "%s": it was hydrated with select() and not all columns are loaded. '
. 'Use patch() for partial updates.',
$operation,
$class,
));
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* A required record could not be found.
*/
final class RecordNotFoundException extends OrmException
{
public static function byPrimaryKey(string $class, int|string $pk): self
{
return new self(sprintf('No "%s" found with primary key "%s".', $class, (string) $pk));
}
public static function first(string $class): self
{
return new self(sprintf('No "%s" matched the given criteria.', $class));
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Camelia\Orm\Exception;
/**
* Model validation failed. Carries every error grouped by property.
*/
final class ValidationException extends OrmException
{
/** @param array<string, list<string>> $errors */
public function __construct(
private readonly array $errors,
private readonly string $model,
) {
$flattened = [];
foreach ($errors as $property => $messages) {
foreach ($messages as $message) {
$flattened[] = $property . ': ' . $message;
}
}
parent::__construct(sprintf(
'Validation failed for "%s": %s',
$model,
implode('; ', $flattened),
));
}
/** @return array<string, list<string>> */
public function errors(): array
{
return $this->errors;
}
public function model(): string
{
return $this->model;
}
}