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:
commit
66e93e3070
97 files changed
+12188
No files matched your search
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* The primary key is assigned by the database on insert (AUTO_INCREMENT).
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class AutoIncrement {}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* The related row lives in the current table: this model holds the foreign key.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class BelongsTo
|
||||
{
|
||||
/**
|
||||
* @param class-string<\Camelia\Orm\Model> $related
|
||||
*/
|
||||
public function __construct(
|
||||
public string $related,
|
||||
public string $foreignKey,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* Many-to-many relation resolved through an explicit pivot table.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class BelongsToMany
|
||||
{
|
||||
/**
|
||||
* @param class-string<\Camelia\Orm\Model> $related
|
||||
*/
|
||||
public function __construct(
|
||||
public string $related,
|
||||
public string $through,
|
||||
public string $foreignPivotKey,
|
||||
public string $relatedPivotKey,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* Overrides the snake_case column name derived from the property name.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class Column
|
||||
{
|
||||
public function __construct(
|
||||
public string $name,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* Declares the backed enum a property must hold. Drives casting and validation.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class Enum
|
||||
{
|
||||
/** @param class-string<\BackedEnum> $class */
|
||||
public function __construct(
|
||||
public string $class,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* Excludes the property from hydrate() mass assignment. Direct writes still work.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class Guarded {}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* The related rows live in the related table and point back at this model.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class HasMany
|
||||
{
|
||||
/**
|
||||
* @param class-string<\Camelia\Orm\Model> $related
|
||||
*/
|
||||
public function __construct(
|
||||
public string $related,
|
||||
public string $foreignKey,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* The related row lives in the related table and points back at this model with one row.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class HasOne
|
||||
{
|
||||
/**
|
||||
* @param class-string<\Camelia\Orm\Model> $related
|
||||
*/
|
||||
public function __construct(
|
||||
public string $related,
|
||||
public string $foreignKey,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* Excludes the property from persistence and from hydrate().
|
||||
*
|
||||
* Relationships are excluded by their relation attribute instead, not by this one.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class Ignore {}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* Secondary index. Consumed by SchemaGenerator only.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class Index
|
||||
{
|
||||
public function __construct(
|
||||
public string $order = 'ASC',
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* Column length. Consumed by SchemaGenerator only.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class Length
|
||||
{
|
||||
public function __construct(
|
||||
public int $value,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* validate() rejects strings longer than this many bytes.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class MaxLength
|
||||
{
|
||||
public function __construct(
|
||||
public int $value,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* Forces the column to be nullable when the PHP type cannot express it (e.g. string).
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class Nullable {}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* Decimal precision and scale. Consumed by SchemaGenerator only.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class Precision
|
||||
{
|
||||
public function __construct(
|
||||
public int $precision,
|
||||
public int $scale,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* Marks the single primary key property of a model.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class PrimaryKey {}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* validate() rejects null and '' for this property.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class Required {}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* Declares the table a model maps to. Required for every model.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_CLASS)]
|
||||
final readonly class TableName
|
||||
{
|
||||
public function __construct(
|
||||
public string $name,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* Single-column unique constraint. Consumed by SchemaGenerator only.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class Unique {}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Attribute;
|
||||
|
||||
/**
|
||||
* Multi-column unique constraint grouped by name. Consumed by SchemaGenerator only.
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
||||
final readonly class UniqueGroup
|
||||
{
|
||||
public function __construct(
|
||||
public string $name,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Connection;
|
||||
|
||||
/**
|
||||
* SQL transport. Implementations must never bind by reference.
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
interface Connection
|
||||
{
|
||||
/**
|
||||
* Executes a statement and returns the affected row count.
|
||||
*
|
||||
* @param list<mixed> $params
|
||||
*/
|
||||
public function execute(string $sql, array $params = []): int;
|
||||
|
||||
/**
|
||||
* Executes a statement and returns every row.
|
||||
*
|
||||
* @param list<mixed> $params
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function select(string $sql, array $params = []): array;
|
||||
|
||||
/**
|
||||
* Runs one statement and returns the first column of the first row.
|
||||
*
|
||||
* @param list<mixed> $params
|
||||
*/
|
||||
public function scalar(string $sql, array $params = []): mixed;
|
||||
|
||||
public function lastInsertId(): string;
|
||||
|
||||
public function begin(): void;
|
||||
|
||||
public function commit(): void;
|
||||
|
||||
public function rollBack(): void;
|
||||
|
||||
public function inTransaction(): bool;
|
||||
|
||||
public function driver(): string;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Connection;
|
||||
|
||||
use Camelia\Orm\Exception\ConfigurationException;
|
||||
use PDO;
|
||||
|
||||
/**
|
||||
* Builds connections from an options array, environment variables or an existing PDO.
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
final class ConnectionFactory
|
||||
{
|
||||
private const REQUIRED_ENVIRONMENT = [
|
||||
'CAMELIA_DB_HOST',
|
||||
'CAMELIA_DB_USER',
|
||||
'CAMELIA_DB_NAME',
|
||||
'CAMELIA_DB_PASS',
|
||||
];
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $options
|
||||
*/
|
||||
public static function fromArray(array $options): Connection
|
||||
{
|
||||
foreach (['host', 'user', 'database'] as $required) {
|
||||
if (!isset($options[$required]) || trim((string) $options[$required]) === '') {
|
||||
throw new ConfigurationException(sprintf(
|
||||
'Connection option "%s" is required.',
|
||||
$required,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
$charset = isset($options['charset']) ? (string) $options['charset'] : 'utf8mb4';
|
||||
$port = isset($options['port']) ? (int) $options['port'] : 3306;
|
||||
|
||||
$dsn = sprintf(
|
||||
'mysql:host=%s;port=%d;dbname=%s;charset=%s',
|
||||
(string) $options['host'],
|
||||
$port,
|
||||
(string) $options['database'],
|
||||
$charset,
|
||||
);
|
||||
|
||||
$pdoOptions = [
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||||
PDO::ATTR_EMULATE_PREPARES => false,
|
||||
];
|
||||
|
||||
if (isset($options['sslCa'])) {
|
||||
$pdoOptions[PDO::MYSQL_ATTR_SSL_CA] = (string) $options['sslCa'];
|
||||
}
|
||||
|
||||
$pdo = new PDO(
|
||||
$dsn,
|
||||
(string) $options['user'],
|
||||
(string) ($options['password'] ?? ''),
|
||||
$pdoOptions,
|
||||
);
|
||||
|
||||
return new PdoConnection($pdo);
|
||||
}
|
||||
|
||||
public static function fromEnvironment(): Connection
|
||||
{
|
||||
$values = [];
|
||||
$missing = [];
|
||||
|
||||
foreach (self::REQUIRED_ENVIRONMENT as $name) {
|
||||
$value = self::readEnvironment($name);
|
||||
|
||||
if ($value === null) {
|
||||
$missing[] = $name;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$values[$name] = $value;
|
||||
}
|
||||
|
||||
if ($missing !== []) {
|
||||
throw ConfigurationException::missingEnvironment($missing);
|
||||
}
|
||||
|
||||
return self::fromArray([
|
||||
'host' => $values['CAMELIA_DB_HOST'],
|
||||
'user' => $values['CAMELIA_DB_USER'],
|
||||
'database' => $values['CAMELIA_DB_NAME'],
|
||||
'password' => $values['CAMELIA_DB_PASS'],
|
||||
'port' => self::readEnvironment('CAMELIA_DB_PORT') ?? 3306,
|
||||
'charset' => self::readEnvironment('CAMELIA_DB_CHARSET') ?? 'utf8mb4',
|
||||
]);
|
||||
}
|
||||
|
||||
public static function fromPdo(PDO $pdo): Connection
|
||||
{
|
||||
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
|
||||
|
||||
return new PdoConnection($pdo);
|
||||
}
|
||||
|
||||
private static function readEnvironment(string $name): ?string
|
||||
{
|
||||
$value = getenv($name);
|
||||
|
||||
if ($value === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Connection;
|
||||
|
||||
use Camelia\Orm\Exception\ConfigurationException;
|
||||
use Camelia\Orm\Exception\DatabaseException;
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use PDOStatement;
|
||||
|
||||
/**
|
||||
* PDO-backed transport with a bounded LRU statement cache.
|
||||
*
|
||||
* Invariant: statements are always executed with execute(array). bindParam is never used,
|
||||
* because cached statements are shared across calls.
|
||||
*/
|
||||
final class PdoConnection implements Connection
|
||||
{
|
||||
private const MAX_CACHED_STATEMENTS = 200;
|
||||
|
||||
/** @var array<string, PDOStatement> */
|
||||
private array $statements = [];
|
||||
|
||||
/** @var list<string> LRU order, most recent last */
|
||||
private array $lru = [];
|
||||
|
||||
/** @var list<string> savepoint names for nested transactions */
|
||||
private array $savepoints = [];
|
||||
|
||||
public function __construct(
|
||||
private readonly PDO $pdo,
|
||||
) {
|
||||
if ($pdo->getAttribute(PDO::ATTR_ERRMODE) !== PDO::ERRMODE_EXCEPTION) {
|
||||
throw ConfigurationException::invalidErrorMode();
|
||||
}
|
||||
}
|
||||
|
||||
public function execute(string $sql, array $params = []): int
|
||||
{
|
||||
$statement = $this->prepare($sql);
|
||||
|
||||
try {
|
||||
$statement->execute($params);
|
||||
} catch (PDOException $exception) {
|
||||
throw DatabaseException::fromPdoException($exception, 'write', $sql, $params);
|
||||
}
|
||||
|
||||
return $statement->rowCount();
|
||||
}
|
||||
|
||||
public function select(string $sql, array $params = []): array
|
||||
{
|
||||
$statement = $this->prepare($sql);
|
||||
|
||||
try {
|
||||
$statement->execute($params);
|
||||
$rows = $statement->fetchAll();
|
||||
} catch (PDOException $exception) {
|
||||
throw DatabaseException::fromPdoException($exception, 'read', $sql, $params);
|
||||
}
|
||||
|
||||
/** @var list<array<string, mixed>> $rows */
|
||||
return $rows;
|
||||
}
|
||||
|
||||
public function scalar(string $sql, array $params = []): mixed
|
||||
{
|
||||
$statement = $this->prepare($sql);
|
||||
|
||||
try {
|
||||
$statement->execute($params);
|
||||
$value = $statement->fetchColumn();
|
||||
} catch (PDOException $exception) {
|
||||
throw DatabaseException::fromPdoException($exception, 'read', $sql, $params);
|
||||
}
|
||||
|
||||
$statement->closeCursor();
|
||||
|
||||
return $value === false ? null : $value;
|
||||
}
|
||||
|
||||
public function lastInsertId(): string
|
||||
{
|
||||
$id = $this->pdo->lastInsertId();
|
||||
|
||||
return $id === false ? '0' : $id;
|
||||
}
|
||||
|
||||
public function begin(): void
|
||||
{
|
||||
if ($this->pdo->inTransaction()) {
|
||||
$name = 'camelia_sp_' . count($this->savepoints);
|
||||
$this->pdo->exec('SAVEPOINT ' . $name);
|
||||
$this->savepoints[] = $name;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->pdo->beginTransaction();
|
||||
}
|
||||
|
||||
public function commit(): void
|
||||
{
|
||||
if ($this->savepoints !== []) {
|
||||
$name = array_pop($this->savepoints);
|
||||
$this->pdo->exec('RELEASE SAVEPOINT ' . $name);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->pdo->inTransaction()) {
|
||||
$this->pdo->commit();
|
||||
}
|
||||
}
|
||||
|
||||
public function rollBack(): void
|
||||
{
|
||||
if ($this->savepoints !== []) {
|
||||
$name = array_pop($this->savepoints);
|
||||
$this->pdo->exec('ROLLBACK TO SAVEPOINT ' . $name);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->pdo->inTransaction()) {
|
||||
$this->pdo->rollBack();
|
||||
}
|
||||
}
|
||||
|
||||
public function inTransaction(): bool
|
||||
{
|
||||
return $this->pdo->inTransaction();
|
||||
}
|
||||
|
||||
public function driver(): string
|
||||
{
|
||||
return (string) $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw PDO handle for cases the library does not cover.
|
||||
*/
|
||||
public function pdo(): PDO
|
||||
{
|
||||
return $this->pdo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the statement cache. Tests only.
|
||||
*/
|
||||
public function clearStatementCache(): void
|
||||
{
|
||||
$this->statements = [];
|
||||
$this->lru = [];
|
||||
}
|
||||
|
||||
public function statementCacheSize(): int
|
||||
{
|
||||
return count($this->statements);
|
||||
}
|
||||
|
||||
private function prepare(string $sql): PDOStatement
|
||||
{
|
||||
$key = md5($sql);
|
||||
$cached = $this->statements[$key] ?? null;
|
||||
|
||||
if ($cached instanceof PDOStatement) {
|
||||
$this->touch($key);
|
||||
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$statement = $this->pdo->prepare($sql);
|
||||
|
||||
if (!$statement instanceof PDOStatement) {
|
||||
throw new DatabaseException(sprintf('Unable to prepare statement: %s', $sql), $sql);
|
||||
}
|
||||
|
||||
$this->statements[$key] = $statement;
|
||||
$this->lru[] = $key;
|
||||
|
||||
$this->evict();
|
||||
|
||||
return $statement;
|
||||
}
|
||||
|
||||
private function touch(string $key): void
|
||||
{
|
||||
$position = array_search($key, $this->lru, true);
|
||||
|
||||
if ($position !== false) {
|
||||
unset($this->lru[$position]);
|
||||
$this->lru = array_values($this->lru);
|
||||
}
|
||||
|
||||
$this->lru[] = $key;
|
||||
}
|
||||
|
||||
private function evict(): void
|
||||
{
|
||||
while (count($this->statements) > self::MAX_CACHED_STATEMENTS) {
|
||||
$oldest = array_shift($this->lru);
|
||||
|
||||
if ($oldest === null) {
|
||||
break;
|
||||
}
|
||||
|
||||
unset($this->statements[$oldest]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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 {}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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,
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Metadata;
|
||||
|
||||
/**
|
||||
* Immutable description of a model class.
|
||||
*
|
||||
* Every lookup is cached at construction: metadata is read once per class and process.
|
||||
*/
|
||||
final class ClassMetadata
|
||||
{
|
||||
/** @var array<string, PropertyMetadata> keyed by property name */
|
||||
private array $properties;
|
||||
|
||||
/** @var array<string, string> column => property */
|
||||
private array $propertyByColumn = [];
|
||||
|
||||
/** @var list<string> */
|
||||
private array $writable;
|
||||
|
||||
/**
|
||||
* @param class-string<\Camelia\Orm\Model> $class
|
||||
* @param array<string, PropertyMetadata> $properties
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $class,
|
||||
private readonly string $table,
|
||||
private readonly string $primaryKey,
|
||||
private readonly string $primaryKeyColumn,
|
||||
array $properties,
|
||||
) {
|
||||
$this->properties = $properties;
|
||||
|
||||
$writable = [];
|
||||
|
||||
foreach ($properties as $property) {
|
||||
$this->propertyByColumn[$property->column] = $property->name;
|
||||
|
||||
if ($property->isWritable()) {
|
||||
$writable[] = $property->name;
|
||||
}
|
||||
}
|
||||
|
||||
$this->writable = $writable;
|
||||
}
|
||||
|
||||
public function table(): string
|
||||
{
|
||||
return $this->table;
|
||||
}
|
||||
|
||||
public function primaryKey(): string
|
||||
{
|
||||
return $this->primaryKey;
|
||||
}
|
||||
|
||||
public function primaryKeyColumn(): string
|
||||
{
|
||||
return $this->primaryKeyColumn;
|
||||
}
|
||||
|
||||
/** @return array<string, PropertyMetadata> */
|
||||
public function properties(): array
|
||||
{
|
||||
return $this->properties;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws \Camelia\Orm\Exception\MetadataException when the property is not mapped
|
||||
*/
|
||||
public function column(string $property): string
|
||||
{
|
||||
return $this->propertyMetadata($property)->column;
|
||||
}
|
||||
|
||||
public function property(string $column): ?string
|
||||
{
|
||||
return $this->propertyByColumn[$column] ?? null;
|
||||
}
|
||||
|
||||
public function hasProperty(string $property): bool
|
||||
{
|
||||
return isset($this->properties[$property]);
|
||||
}
|
||||
|
||||
public function hasColumn(string $column): bool
|
||||
{
|
||||
return isset($this->propertyByColumn[$column]);
|
||||
}
|
||||
|
||||
public function propertyMetadata(string $property): PropertyMetadata
|
||||
{
|
||||
$metadata = $this->properties[$property] ?? null;
|
||||
|
||||
if ($metadata === null) {
|
||||
throw \Camelia\Orm\Exception\MetadataException::unknownProperty(
|
||||
$this->class,
|
||||
$property,
|
||||
);
|
||||
}
|
||||
|
||||
return $metadata;
|
||||
}
|
||||
|
||||
/** @return list<PropertyMetadata> */
|
||||
public function relations(): array
|
||||
{
|
||||
return array_values(array_filter(
|
||||
$this->properties,
|
||||
static fn(PropertyMetadata $p): bool => $p->relation !== null,
|
||||
));
|
||||
}
|
||||
|
||||
/** @return list<PropertyMetadata> */
|
||||
public function indexed(): array
|
||||
{
|
||||
return array_values(array_filter(
|
||||
$this->properties,
|
||||
static fn(PropertyMetadata $p): bool => $p->indexed,
|
||||
));
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function writable(): array
|
||||
{
|
||||
return $this->writable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a criteria key to a property name, accepting either form.
|
||||
*/
|
||||
public function resolveProperty(string $key): ?string
|
||||
{
|
||||
if (isset($this->properties[$key])) {
|
||||
return $key;
|
||||
}
|
||||
|
||||
return $this->propertyByColumn[$key] ?? null;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function knownKeys(): array
|
||||
{
|
||||
return array_values(array_unique(array_merge(
|
||||
array_keys($this->properties),
|
||||
array_keys($this->propertyByColumn),
|
||||
)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Metadata;
|
||||
|
||||
/**
|
||||
* Declarative constraints of one mapped property.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final readonly class Constraint
|
||||
{
|
||||
public function __construct(
|
||||
public bool $nullable = false,
|
||||
public bool $ignored = false,
|
||||
public bool $guarded = false,
|
||||
public bool $primaryKey = false,
|
||||
public bool $autoIncrement = false,
|
||||
public bool $required = false,
|
||||
public bool $indexed = false,
|
||||
public ?int $maxLength = null,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Metadata;
|
||||
|
||||
/**
|
||||
* Memoizes ClassMetadata per class for the lifetime of the process.
|
||||
*
|
||||
* Metadata never changes once built; clear() exists for tests only.
|
||||
*/
|
||||
final class MetadataCache
|
||||
{
|
||||
/** @var array<string, ClassMetadata> */
|
||||
private array $byName = [];
|
||||
|
||||
public function __construct(
|
||||
private readonly MetadataFactory $factory,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param class-string<\Camelia\Orm\Model> $class
|
||||
*/
|
||||
public function forClass(string $class): ClassMetadata
|
||||
{
|
||||
return $this->byName[$class] ??= $this->factory->forClass($class);
|
||||
}
|
||||
|
||||
public function clear(): void
|
||||
{
|
||||
$this->byName = [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Metadata;
|
||||
|
||||
use Camelia\Orm\Attribute\AutoIncrement;
|
||||
use Camelia\Orm\Attribute\BelongsTo;
|
||||
use Camelia\Orm\Attribute\BelongsToMany;
|
||||
use Camelia\Orm\Attribute\Column;
|
||||
use Camelia\Orm\Attribute\Enum;
|
||||
use Camelia\Orm\Attribute\Guarded;
|
||||
use Camelia\Orm\Attribute\HasMany;
|
||||
use Camelia\Orm\Attribute\HasOne;
|
||||
use Camelia\Orm\Attribute\Ignore;
|
||||
use Camelia\Orm\Attribute\Index;
|
||||
use Camelia\Orm\Attribute\MaxLength;
|
||||
use Camelia\Orm\Attribute\Nullable;
|
||||
use Camelia\Orm\Attribute\PrimaryKey;
|
||||
use Camelia\Orm\Attribute\Required;
|
||||
use Camelia\Orm\Attribute\TableName;
|
||||
use Camelia\Orm\Exception\MetadataException;
|
||||
use Camelia\Orm\Model;
|
||||
use Camelia\Orm\Support\NameConverter;
|
||||
use ReflectionClass;
|
||||
use ReflectionNamedType;
|
||||
use ReflectionProperty;
|
||||
|
||||
/**
|
||||
* Builds ClassMetadata from a model class through reflection.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class MetadataFactory
|
||||
{
|
||||
/**
|
||||
* @param class-string<\Camelia\Orm\Model> $class
|
||||
*/
|
||||
public function forClass(string $class): ClassMetadata
|
||||
{
|
||||
if (!class_exists($class) || !is_subclass_of($class, Model::class)) {
|
||||
throw MetadataException::notAModel($class);
|
||||
}
|
||||
|
||||
$reflection = new ReflectionClass($class);
|
||||
|
||||
$tableName = $reflection->getAttributes(TableName::class)[0] ?? null;
|
||||
|
||||
if ($tableName === null) {
|
||||
throw MetadataException::missingTableName($class);
|
||||
}
|
||||
|
||||
/** @var TableName $table */
|
||||
$table = $tableName->newInstance();
|
||||
|
||||
if (trim($table->name) === '') {
|
||||
throw MetadataException::missingTableName($class);
|
||||
}
|
||||
|
||||
$properties = [];
|
||||
$primaryKeys = [];
|
||||
$columnOwners = [];
|
||||
|
||||
foreach ($reflection->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
|
||||
if ($property->isStatic()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$declaring = $property->getDeclaringClass()->getName();
|
||||
|
||||
if ($declaring !== $class && $declaring === Model::class) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$metadata = $this->buildProperty($class, $reflection, $property);
|
||||
|
||||
if (isset($columnOwners[$metadata->column])) {
|
||||
throw MetadataException::duplicateColumn(
|
||||
$class,
|
||||
$metadata->column,
|
||||
$columnOwners[$metadata->column],
|
||||
$metadata->name,
|
||||
);
|
||||
}
|
||||
|
||||
$columnOwners[$metadata->column] = $metadata->name;
|
||||
$properties[$metadata->name] = $metadata;
|
||||
|
||||
if ($metadata->primaryKey) {
|
||||
$primaryKeys[] = $metadata->name;
|
||||
}
|
||||
}
|
||||
|
||||
if (count($primaryKeys) !== 1) {
|
||||
throw MetadataException::primaryKeyCount($class, count($primaryKeys));
|
||||
}
|
||||
|
||||
$primaryKey = $primaryKeys[0];
|
||||
$primaryKeyProperty = $properties[$primaryKey] ?? null;
|
||||
|
||||
if ($primaryKeyProperty === null) {
|
||||
throw MetadataException::unknownProperty($class, $primaryKey);
|
||||
}
|
||||
|
||||
return new ClassMetadata(
|
||||
$class,
|
||||
$table->name,
|
||||
$primaryKey,
|
||||
$primaryKeyProperty->column,
|
||||
$properties,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param class-string<\Camelia\Orm\Model> $class
|
||||
* @param ReflectionClass<object> $reflection
|
||||
*/
|
||||
private function buildProperty(
|
||||
string $class,
|
||||
ReflectionClass $reflection,
|
||||
ReflectionProperty $property,
|
||||
): PropertyMetadata {
|
||||
$name = $property->getName();
|
||||
$type = $property->getType();
|
||||
|
||||
if (!$type instanceof ReflectionNamedType) {
|
||||
throw MetadataException::missingType($class, $name);
|
||||
}
|
||||
|
||||
$relation = $this->buildRelation($class, $reflection, $property);
|
||||
|
||||
$columnAttribute = $property->getAttributes(Column::class)[0] ?? null;
|
||||
$column = $columnAttribute !== null
|
||||
? $columnAttribute->newInstance()->name
|
||||
: NameConverter::camelToSnake($name);
|
||||
|
||||
if (preg_match('/[^\x20-\x7E]/', $column) === 1) {
|
||||
throw MetadataException::nonAsciiColumn($class, $name, $column);
|
||||
}
|
||||
|
||||
$enumAttribute = $property->getAttributes(Enum::class)[0] ?? null;
|
||||
$enumClass = $enumAttribute !== null ? $enumAttribute->newInstance()->class : null;
|
||||
|
||||
if ($relation !== null) {
|
||||
$this->assertRelationShape($class, $property, $relation);
|
||||
}
|
||||
|
||||
$maxLength = $property->getAttributes(MaxLength::class)[0] ?? null;
|
||||
|
||||
return new PropertyMetadata(
|
||||
name: $name,
|
||||
column: $column,
|
||||
type: $enumClass ?? $type->getName(),
|
||||
enumClass: $enumClass,
|
||||
relation: $relation,
|
||||
declaringClass: $class,
|
||||
constraint: new Constraint(
|
||||
nullable: $type->allowsNull() || $property->getAttributes(Nullable::class) !== [],
|
||||
ignored: $property->getAttributes(Ignore::class) !== [] || $relation !== null,
|
||||
guarded: $property->getAttributes(Guarded::class) !== [],
|
||||
primaryKey: $property->getAttributes(PrimaryKey::class) !== [],
|
||||
autoIncrement: $property->getAttributes(AutoIncrement::class) !== [],
|
||||
required: $property->getAttributes(Required::class) !== [],
|
||||
indexed: $property->getAttributes(Index::class) !== [],
|
||||
maxLength: $maxLength !== null ? $maxLength->newInstance()->value : null,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param class-string<\Camelia\Orm\Model> $class
|
||||
* @param ReflectionClass<object> $reflection
|
||||
*/
|
||||
private function buildRelation(
|
||||
string $class,
|
||||
ReflectionClass $reflection,
|
||||
ReflectionProperty $property,
|
||||
): ?RelationMetadata {
|
||||
$name = $property->getName();
|
||||
|
||||
$belongsTo = $property->getAttributes(BelongsTo::class)[0] ?? null;
|
||||
|
||||
if ($belongsTo !== null) {
|
||||
/** @var BelongsTo $attribute */
|
||||
$attribute = $belongsTo->newInstance();
|
||||
|
||||
return new RelationMetadata(
|
||||
RelationMetadata::KIND_BELONGS_TO,
|
||||
$this->resolveRelatedClass($class, $reflection, $attribute->related, $name),
|
||||
$attribute->foreignKey,
|
||||
);
|
||||
}
|
||||
|
||||
$hasOne = $property->getAttributes(HasOne::class)[0] ?? null;
|
||||
|
||||
if ($hasOne !== null) {
|
||||
/** @var HasOne $attribute */
|
||||
$attribute = $hasOne->newInstance();
|
||||
|
||||
return new RelationMetadata(
|
||||
RelationMetadata::KIND_HAS_ONE,
|
||||
$this->resolveRelatedClass($class, $reflection, $attribute->related, $name),
|
||||
$attribute->foreignKey,
|
||||
);
|
||||
}
|
||||
|
||||
$hasMany = $property->getAttributes(HasMany::class)[0] ?? null;
|
||||
|
||||
if ($hasMany !== null) {
|
||||
/** @var HasMany $attribute */
|
||||
$attribute = $hasMany->newInstance();
|
||||
|
||||
return new RelationMetadata(
|
||||
RelationMetadata::KIND_HAS_MANY,
|
||||
$this->resolveRelatedClass($class, $reflection, $attribute->related, $name),
|
||||
$attribute->foreignKey,
|
||||
);
|
||||
}
|
||||
|
||||
$belongsToMany = $property->getAttributes(BelongsToMany::class)[0] ?? null;
|
||||
|
||||
if ($belongsToMany !== null) {
|
||||
/** @var BelongsToMany $attribute */
|
||||
$attribute = $belongsToMany->newInstance();
|
||||
|
||||
return new RelationMetadata(
|
||||
RelationMetadata::KIND_BELONGS_TO_MANY,
|
||||
$this->resolveRelatedClass($class, $reflection, $attribute->related, $name),
|
||||
'',
|
||||
$attribute->through,
|
||||
$attribute->foreignPivotKey,
|
||||
$attribute->relatedPivotKey,
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param class-string<\Camelia\Orm\Model> $class
|
||||
* @param ReflectionClass<object> $reflection
|
||||
* @return class-string<\Camelia\Orm\Model>
|
||||
*/
|
||||
private function resolveRelatedClass(
|
||||
string $class,
|
||||
ReflectionClass $reflection,
|
||||
string $related,
|
||||
string $property,
|
||||
): string {
|
||||
if (class_exists($related) && is_subclass_of($related, Model::class)) {
|
||||
return $related;
|
||||
}
|
||||
|
||||
$namespace = $reflection->getNamespaceName();
|
||||
$candidate = $namespace === '' ? $related : $namespace . '\\' . $related;
|
||||
|
||||
if (class_exists($candidate) && is_subclass_of($candidate, Model::class)) {
|
||||
return $candidate;
|
||||
}
|
||||
|
||||
throw MetadataException::unknownRelatedClass($class, $property, $related);
|
||||
}
|
||||
|
||||
private function assertRelationShape(
|
||||
string $class,
|
||||
ReflectionProperty $property,
|
||||
RelationMetadata $relation,
|
||||
): void {
|
||||
$name = $property->getName();
|
||||
$type = $property->getType();
|
||||
|
||||
if (!$type instanceof ReflectionNamedType) {
|
||||
throw MetadataException::invalidRelationProperty($class, $name);
|
||||
}
|
||||
|
||||
$isArray = $type->getName() === 'array';
|
||||
|
||||
if ($relation->isToMany() && !$isArray) {
|
||||
throw MetadataException::invalidRelationProperty($class, $name);
|
||||
}
|
||||
|
||||
if (!$relation->isToMany() && (!$type->allowsNull() || $isArray)) {
|
||||
throw MetadataException::invalidRelationProperty($class, $name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Metadata;
|
||||
|
||||
/**
|
||||
* Immutable description of one mapped property.
|
||||
*
|
||||
* The boolean flags are grouped into Constraint in the constructor signature to keep the
|
||||
* parameter list readable; they are re-exposed here as flat, named properties because every
|
||||
* consumer reads them individually.
|
||||
*/
|
||||
final readonly class PropertyMetadata
|
||||
{
|
||||
public bool $nullable;
|
||||
public bool $ignored;
|
||||
public bool $guarded;
|
||||
public bool $primaryKey;
|
||||
public bool $autoIncrement;
|
||||
public bool $required;
|
||||
public bool $indexed;
|
||||
public ?int $maxLength;
|
||||
|
||||
/**
|
||||
* @param class-string<\Camelia\Orm\Model> $declaringClass
|
||||
* @param class-string<\BackedEnum>|null $enumClass
|
||||
*/
|
||||
public function __construct(
|
||||
public string $name,
|
||||
public string $column,
|
||||
public string $type,
|
||||
public ?string $enumClass,
|
||||
public ?RelationMetadata $relation,
|
||||
public string $declaringClass,
|
||||
Constraint $constraint,
|
||||
) {
|
||||
$this->nullable = $constraint->nullable;
|
||||
$this->ignored = $constraint->ignored;
|
||||
$this->guarded = $constraint->guarded;
|
||||
$this->primaryKey = $constraint->primaryKey;
|
||||
$this->autoIncrement = $constraint->autoIncrement;
|
||||
$this->required = $constraint->required;
|
||||
$this->indexed = $constraint->indexed;
|
||||
$this->maxLength = $constraint->maxLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the property participates in INSERT/UPDATE.
|
||||
*/
|
||||
public function isWritable(): bool
|
||||
{
|
||||
return !$this->ignored && !$this->primaryKey && $this->relation === null;
|
||||
}
|
||||
|
||||
public function isRelation(): bool
|
||||
{
|
||||
return $this->relation !== null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Metadata;
|
||||
|
||||
/**
|
||||
* Immutable description of a declared relationship.
|
||||
*/
|
||||
final readonly class RelationMetadata
|
||||
{
|
||||
public const KIND_BELONGS_TO = 'belongsTo';
|
||||
public const KIND_HAS_ONE = 'hasOne';
|
||||
public const KIND_HAS_MANY = 'hasMany';
|
||||
public const KIND_BELONGS_TO_MANY = 'belongsToMany';
|
||||
|
||||
/**
|
||||
* @param class-string<\Camelia\Orm\Model> $relatedClass
|
||||
*/
|
||||
public function __construct(
|
||||
public string $kind,
|
||||
public string $relatedClass,
|
||||
public string $foreignKey,
|
||||
public ?string $through = null,
|
||||
public ?string $foreignPivotKey = null,
|
||||
public ?string $relatedPivotKey = null,
|
||||
) {}
|
||||
|
||||
public function isToMany(): bool
|
||||
{
|
||||
return $this->kind === self::KIND_HAS_MANY || $this->kind === self::KIND_BELONGS_TO_MANY;
|
||||
}
|
||||
}
|
||||
+380
@@ -0,0 +1,380 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm;
|
||||
|
||||
use Camelia\Orm\Exception\ValidationException;
|
||||
use Camelia\Orm\Metadata\ClassMetadata;
|
||||
use Camelia\Orm\Metadata\MetadataCache;
|
||||
use Camelia\Orm\Metadata\MetadataFactory;
|
||||
use Camelia\Orm\Metadata\PropertyMetadata;
|
||||
use Camelia\Orm\Persistence\Validator;
|
||||
use Camelia\Orm\Support\TypeCaster;
|
||||
use DateTimeImmutable;
|
||||
use ReflectionClass;
|
||||
use ReflectionNamedType;
|
||||
use ReflectionProperty;
|
||||
|
||||
/**
|
||||
* State holder for one row.
|
||||
*
|
||||
* A model never talks to the database: reading and writing go through Repository.
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
abstract class Model
|
||||
{
|
||||
private static ?MetadataCache $metadata = null;
|
||||
|
||||
private bool $partial = false;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->initializeProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves (and memoizes) the metadata of one model class.
|
||||
*
|
||||
* @param class-string<\Camelia\Orm\Model> $class
|
||||
*/
|
||||
public static function metadataFor(string $class): ClassMetadata
|
||||
{
|
||||
self::$metadata ??= new MetadataCache(new MetadataFactory());
|
||||
|
||||
return self::$metadata->forClass($class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the shared metadata cache. Tests only.
|
||||
*/
|
||||
public static function clearMetadataCache(): void
|
||||
{
|
||||
self::$metadata = null;
|
||||
}
|
||||
|
||||
public static function metadata(): ClassMetadata
|
||||
{
|
||||
/** @var class-string<\Camelia\Orm\Model> $class */
|
||||
$class = static::class;
|
||||
|
||||
return self::metadataFor($class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mass-assigns values keyed by property or column name.
|
||||
*
|
||||
* Properties win when both forms are present. Unknown keys are ignored so HTTP payloads
|
||||
* can be passed through. Guarded properties are skipped.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @throws \InvalidArgumentException when a value cannot be cast to its declared type
|
||||
*/
|
||||
public function hydrate(array $data): static
|
||||
{
|
||||
$this->assign($data, false);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as hydrate(), but a guarded property in the payload is an error instead of being skipped.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @throws \InvalidArgumentException when a value cannot be cast or a guarded property is present
|
||||
*/
|
||||
public function hydrateStrict(array $data): static
|
||||
{
|
||||
$this->assign($data, true);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
private function assign(array $data, bool $rejectGuarded = false): void
|
||||
{
|
||||
$metadata = static::metadata();
|
||||
$resolved = [];
|
||||
|
||||
foreach ($data as $key => $value) {
|
||||
$key = (string) $key;
|
||||
$property = $metadata->resolveProperty($key);
|
||||
|
||||
if ($property === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$definition = $metadata->propertyMetadata($property);
|
||||
|
||||
if ($definition->ignored || $definition->primaryKey) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($definition->guarded && $rejectGuarded) {
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
'Property "%s" is guarded and cannot be mass-assigned.',
|
||||
$property,
|
||||
));
|
||||
}
|
||||
|
||||
// The property name wins over the column alias when both are present.
|
||||
$isPropertyName = $key === $property;
|
||||
|
||||
if (isset($resolved[$property])) {
|
||||
$alreadyFromProperty = $resolved[$property]['isProperty'];
|
||||
|
||||
if ($alreadyFromProperty || !$isPropertyName) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
$resolved[$property] = [
|
||||
'value' => $value,
|
||||
'definition' => $definition,
|
||||
'isProperty' => $isPropertyName,
|
||||
];
|
||||
}
|
||||
|
||||
foreach ($resolved as $property => $entry) {
|
||||
$definition = $entry['definition'];
|
||||
|
||||
if ($definition->guarded) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->{$property} = $this->castFor($definition, $entry['value']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes writable columns plus loaded relationships.
|
||||
*
|
||||
* @param list<string>|null $only property names to include
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(?array $only = null): array
|
||||
{
|
||||
$metadata = static::metadata();
|
||||
$result = [];
|
||||
|
||||
foreach ($metadata->writable() as $property) {
|
||||
if ($only !== null && !in_array($property, $only, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$definition = $metadata->propertyMetadata($property);
|
||||
$result[$definition->column] = TypeCaster::toSerializable($this->{$property});
|
||||
}
|
||||
|
||||
foreach ($metadata->relations() as $relation) {
|
||||
if ($only !== null && !in_array($relation->name, $only, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$result[$relation->name] = $this->serializeRelation($relation);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function toJson(int $flags = 0): string
|
||||
{
|
||||
return (string) json_encode(
|
||||
$this->toArray(),
|
||||
$flags | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, list<string>> property => messages
|
||||
*/
|
||||
public function validate(): array
|
||||
{
|
||||
return (new Validator())->validate($this);
|
||||
}
|
||||
|
||||
public function isValid(): bool
|
||||
{
|
||||
return $this->validate() === [];
|
||||
}
|
||||
|
||||
public function isPartial(): bool
|
||||
{
|
||||
return $this->partial;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the instance as hydrated from a column subset. Persister refuses to write it.
|
||||
*/
|
||||
public function markPartial(bool $partial = true): void
|
||||
{
|
||||
$this->partial = $partial;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies this model without its primary key, ready to be saved as a new row.
|
||||
*/
|
||||
public function replicate(): static
|
||||
{
|
||||
$copy = clone $this;
|
||||
$metadata = static::metadata();
|
||||
$primaryKey = $metadata->primaryKey();
|
||||
$definition = $metadata->propertyMetadata($primaryKey);
|
||||
|
||||
$copy->{$primaryKey} = match (true) {
|
||||
$definition->nullable => null,
|
||||
$definition->type === 'string' => '',
|
||||
$definition->type === 'float' => 0.0,
|
||||
$definition->type === 'bool' => false,
|
||||
default => 0,
|
||||
};
|
||||
|
||||
return $copy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the declared value of a property without dynamic property access surprises.
|
||||
*/
|
||||
public function get(string $property): mixed
|
||||
{
|
||||
return $this->{$property};
|
||||
}
|
||||
|
||||
public function set(string $property, mixed $value): static
|
||||
{
|
||||
$this->{$property} = $value;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook invoked by Persister immediately before an INSERT.
|
||||
*/
|
||||
protected function beforeInsert(): void {}
|
||||
|
||||
/**
|
||||
* Hook invoked by Persister immediately before an UPDATE.
|
||||
*/
|
||||
protected function beforeUpdate(): void {}
|
||||
|
||||
/**
|
||||
* @internal used by Persister
|
||||
*/
|
||||
public function runBeforeInsert(): void
|
||||
{
|
||||
$this->beforeInsert();
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal used by Persister
|
||||
*/
|
||||
public function runBeforeUpdate(): void
|
||||
{
|
||||
$this->beforeUpdate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts the model is valid and throws with every error grouped by property.
|
||||
*
|
||||
* @internal used by Persister
|
||||
*/
|
||||
public function assertValid(): void
|
||||
{
|
||||
$errors = $this->validate();
|
||||
|
||||
if ($errors !== []) {
|
||||
/** @var class-string<\Camelia\Orm\Model> $class */
|
||||
$class = static::class;
|
||||
|
||||
throw new ValidationException($errors, $class);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal used by Persister
|
||||
*/
|
||||
public function castFor(PropertyMetadata $definition, mixed $value): mixed
|
||||
{
|
||||
$context = $definition->declaringClass . '::$' . $definition->name;
|
||||
|
||||
if ($definition->enumClass !== null) {
|
||||
return TypeCaster::castEnum(
|
||||
$value,
|
||||
$definition->enumClass,
|
||||
$definition->nullable,
|
||||
$context,
|
||||
);
|
||||
}
|
||||
|
||||
return TypeCaster::cast($value, $definition->type, $definition->nullable, $context);
|
||||
}
|
||||
|
||||
private function initializeProperties(): void
|
||||
{
|
||||
$reflection = new ReflectionClass($this);
|
||||
|
||||
foreach ($reflection->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
|
||||
if ($property->isStatic() || $property->isInitialized($this)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$type = $property->getType();
|
||||
|
||||
if (!$type instanceof ReflectionNamedType) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$property->setValue($this, self::neutralValue($type));
|
||||
}
|
||||
}
|
||||
|
||||
private static function neutralValue(ReflectionNamedType $type): mixed
|
||||
{
|
||||
if ($type->allowsNull()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return match ($type->getName()) {
|
||||
'string' => '',
|
||||
'int' => 0,
|
||||
'float' => 0.0,
|
||||
'bool' => false,
|
||||
'array' => [],
|
||||
DateTimeImmutable::class => new DateTimeImmutable('now'),
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
private function serializeRelation(PropertyMetadata $relation): mixed
|
||||
{
|
||||
/** @var mixed $value */
|
||||
$value = $this->{$relation->name};
|
||||
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_array($value)) {
|
||||
$serialized = [];
|
||||
|
||||
foreach ($value as $related) {
|
||||
if (!$related instanceof Model) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$serialized[] = $related->toArray();
|
||||
}
|
||||
|
||||
return $serialized;
|
||||
}
|
||||
|
||||
if ($value instanceof Model) {
|
||||
return $value->toArray();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm;
|
||||
|
||||
use Camelia\Orm\Connection\Connection;
|
||||
use Camelia\Orm\Connection\ConnectionFactory;
|
||||
use Camelia\Orm\Persistence\AuditListener;
|
||||
use Camelia\Orm\Persistence\Persister;
|
||||
use Camelia\Orm\Query\Dialect;
|
||||
use Camelia\Orm\Query\MySqlDialect;
|
||||
use Camelia\Orm\Query\QueryBuilder;
|
||||
use Camelia\Orm\Support\Clock;
|
||||
use Camelia\Orm\Support\SystemClock;
|
||||
use PDO;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
/**
|
||||
* Library entry point. Immutable and safe to pass through constructors.
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
final class Orm
|
||||
{
|
||||
private ?Persister $persister = null;
|
||||
|
||||
/** @var array<string, Repository<Model>> */
|
||||
private array $repositories = [];
|
||||
|
||||
public function __construct(
|
||||
private readonly Connection $connection,
|
||||
private readonly Dialect $dialect = new MySqlDialect(),
|
||||
private readonly ?AuditListener $auditListener = null,
|
||||
private readonly ?LoggerInterface $logger = null,
|
||||
private readonly Clock $clock = new SystemClock(),
|
||||
private readonly int $slowQueryMs = 500,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $options
|
||||
*/
|
||||
public static function fromArray(array $options): self
|
||||
{
|
||||
return self::fromConnection(ConnectionFactory::fromArray($options), $options);
|
||||
}
|
||||
|
||||
public static function fromPdo(PDO $pdo): self
|
||||
{
|
||||
return self::fromConnection(ConnectionFactory::fromPdo($pdo));
|
||||
}
|
||||
|
||||
public static function fromEnv(): self
|
||||
{
|
||||
return self::fromConnection(ConnectionFactory::fromEnvironment());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $options
|
||||
*/
|
||||
public static function fromConnection(Connection $connection, array $options = []): self
|
||||
{
|
||||
$audit = $options['auditListener'] ?? null;
|
||||
$logger = $options['logger'] ?? null;
|
||||
$clock = $options['clock'] ?? null;
|
||||
$slowQueryMs = $options['slowQueryMs'] ?? 500;
|
||||
|
||||
return new self(
|
||||
$connection,
|
||||
new MySqlDialect(),
|
||||
$audit instanceof AuditListener ? $audit : null,
|
||||
$logger instanceof LoggerInterface ? $logger : null,
|
||||
$clock instanceof Clock ? $clock : new SystemClock(),
|
||||
is_int($slowQueryMs) ? $slowQueryMs : 500,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @template T of Model
|
||||
* @param class-string<T> $class
|
||||
* @return Repository<T>
|
||||
*/
|
||||
public function repository(string $class): Repository
|
||||
{
|
||||
/** @var Repository<T> $repository */
|
||||
$repository =
|
||||
$this->repositories[$class] ??= new Repository(
|
||||
$this->connection,
|
||||
$class,
|
||||
$this->dialect,
|
||||
$this->persister(),
|
||||
);
|
||||
|
||||
return $repository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the callback inside a transaction, nesting through savepoints.
|
||||
*
|
||||
* @template TReturn
|
||||
* @param callable(self): TReturn $callback
|
||||
* @return TReturn
|
||||
*/
|
||||
public function transaction(callable $callback): mixed
|
||||
{
|
||||
$this->connection->begin();
|
||||
|
||||
try {
|
||||
$result = $callback($this);
|
||||
$this->connection->commit();
|
||||
|
||||
return $result;
|
||||
} catch (\Throwable $exception) {
|
||||
$this->connection->rollBack();
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
|
||||
public function connection(): Connection
|
||||
{
|
||||
return $this->connection;
|
||||
}
|
||||
|
||||
public function dialect(): Dialect
|
||||
{
|
||||
return $this->dialect;
|
||||
}
|
||||
|
||||
public function clock(): Clock
|
||||
{
|
||||
return $this->clock;
|
||||
}
|
||||
|
||||
public function logger(): ?LoggerInterface
|
||||
{
|
||||
return $this->logger;
|
||||
}
|
||||
|
||||
public function slowQueryMs(): int
|
||||
{
|
||||
return $this->slowQueryMs;
|
||||
}
|
||||
|
||||
private function persister(): Persister
|
||||
{
|
||||
return $this->persister ??= new Persister(
|
||||
$this->connection,
|
||||
new QueryBuilder($this->dialect),
|
||||
$this->auditListener,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Pagination;
|
||||
|
||||
use Camelia\Orm\Model;
|
||||
|
||||
/**
|
||||
* Immutable paginated result.
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
final readonly class Page
|
||||
{
|
||||
public const MIN_PER_PAGE = 1;
|
||||
public const MAX_PER_PAGE = 1000;
|
||||
|
||||
/**
|
||||
* @param list<Model> $items
|
||||
*/
|
||||
public function __construct(
|
||||
public array $items,
|
||||
public int $page,
|
||||
public int $perPage,
|
||||
public int $total,
|
||||
public int $totalPages,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Builds a page with boundary-tolerant pagination inputs.
|
||||
*
|
||||
* @param list<Model> $items
|
||||
*/
|
||||
public static function of(array $items, int $page, int $perPage, int $total): self
|
||||
{
|
||||
$safePage = max(1, $page);
|
||||
$safePerPage = max(self::MIN_PER_PAGE, min(self::MAX_PER_PAGE, $perPage));
|
||||
$safeTotal = max(0, $total);
|
||||
$totalPages = $safePerPage === 0 ? 0 : (int) ceil($safeTotal / $safePerPage);
|
||||
|
||||
return new self($items, $safePage, $safePerPage, $safeTotal, $totalPages);
|
||||
}
|
||||
|
||||
public function hasNext(): bool
|
||||
{
|
||||
return $this->page < $this->totalPages;
|
||||
}
|
||||
|
||||
public function hasPrev(): bool
|
||||
{
|
||||
return $this->page > 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* items: list<array<string, mixed>>,
|
||||
* page: int,
|
||||
* per_page: int,
|
||||
* total: int,
|
||||
* total_pages: int,
|
||||
* has_next: bool,
|
||||
* has_prev: bool
|
||||
* }
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$items = [];
|
||||
|
||||
foreach ($this->items as $item) {
|
||||
$items[] = $item->toArray();
|
||||
}
|
||||
|
||||
return [
|
||||
'items' => $items,
|
||||
'page' => $this->page,
|
||||
'per_page' => $this->perPage,
|
||||
'total' => $this->total,
|
||||
'total_pages' => $this->totalPages,
|
||||
'has_next' => $this->hasNext(),
|
||||
'has_prev' => $this->hasPrev(),
|
||||
];
|
||||
}
|
||||
|
||||
public function toJson(int $flags = 0): string
|
||||
{
|
||||
return (string) json_encode(
|
||||
$this->toArray(),
|
||||
$flags | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Persistence;
|
||||
|
||||
/**
|
||||
* Receives a notification after a successful write.
|
||||
*
|
||||
* The library ships no implementation: the consumer decides where the audit trail lives.
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
interface AuditListener
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed>|null $before null on insert
|
||||
* @param array<string, mixed> $after
|
||||
*/
|
||||
public function onWrite(
|
||||
string $table,
|
||||
int|string $pk,
|
||||
string $action,
|
||||
?array $before,
|
||||
array $after,
|
||||
): void;
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Persistence;
|
||||
|
||||
use Camelia\Orm\Connection\Connection;
|
||||
use Camelia\Orm\Exception\CriteriaException;
|
||||
use Camelia\Orm\Exception\PartialModelException;
|
||||
use Camelia\Orm\Model;
|
||||
use Camelia\Orm\Query\QueryBuilder;
|
||||
use Camelia\Orm\Support\TypeCaster;
|
||||
use DateTimeInterface;
|
||||
|
||||
/**
|
||||
* Executes INSERT, UPDATE and DELETE for one model.
|
||||
*
|
||||
* Every write validates first and then maps property values to database values.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class Persister
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Connection $connection,
|
||||
private readonly QueryBuilder $builder,
|
||||
private readonly ?AuditListener $audit = null,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return int|string primary key of the saved row
|
||||
*/
|
||||
public function save(Model $model): int|string
|
||||
{
|
||||
$metadata = $model::metadata();
|
||||
/** @var mixed $pk */
|
||||
$pk = $model->get($metadata->primaryKey());
|
||||
|
||||
if ($pk === null || $pk === 0 || $pk === '0' || $pk === '') {
|
||||
return $this->insert($model);
|
||||
}
|
||||
|
||||
$this->update($model);
|
||||
|
||||
return is_int($pk) || is_string($pk) ? $pk : (string) $pk;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|string
|
||||
*/
|
||||
public function insert(Model $model): int|string
|
||||
{
|
||||
$this->assertNotPartial($model, 'insert');
|
||||
|
||||
$metadata = $model::metadata();
|
||||
$model->assertValid();
|
||||
$model->runBeforeInsert();
|
||||
|
||||
$values = $this->collectWritableValues($model);
|
||||
|
||||
if ($values === []) {
|
||||
throw new CriteriaException(sprintf(
|
||||
'Model "%s" has no writable column to insert.',
|
||||
$metadata->class,
|
||||
));
|
||||
}
|
||||
|
||||
$compiled = $this->builder->insert($metadata, $values);
|
||||
$this->connection->execute($compiled['sql'], $compiled['params']);
|
||||
|
||||
$primaryKeyProperty = $metadata->primaryKey();
|
||||
$primaryKeyMetadata = $metadata->propertyMetadata($primaryKeyProperty);
|
||||
|
||||
if ($primaryKeyMetadata->autoIncrement) {
|
||||
$identifier = $this->connection->lastInsertId();
|
||||
$model->set($primaryKeyProperty, TypeCaster::cast(
|
||||
$identifier,
|
||||
$primaryKeyMetadata->type,
|
||||
false,
|
||||
$metadata->class . '::$' . $primaryKeyProperty,
|
||||
));
|
||||
}
|
||||
|
||||
/** @var mixed $pk */
|
||||
$pk = $model->get($primaryKeyProperty);
|
||||
$normalized = is_int($pk) || is_string($pk) ? $pk : (string) $pk;
|
||||
|
||||
$this->notify(
|
||||
$metadata->table(),
|
||||
$normalized,
|
||||
'insert',
|
||||
null,
|
||||
$this->auditSnapshot($model),
|
||||
);
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
public function update(Model $model): void
|
||||
{
|
||||
$this->assertNotPartial($model, 'update');
|
||||
|
||||
$metadata = $model::metadata();
|
||||
$model->assertValid();
|
||||
$model->runBeforeUpdate();
|
||||
|
||||
$primaryKeyProperty = $metadata->primaryKey();
|
||||
/** @var mixed $pk */
|
||||
$pk = $model->get($primaryKeyProperty);
|
||||
|
||||
if ($pk === null || $pk === 0 || $pk === '0' || $pk === '') {
|
||||
throw new CriteriaException(sprintf(
|
||||
'Cannot update "%s" without a primary key value.',
|
||||
$metadata->class,
|
||||
));
|
||||
}
|
||||
|
||||
$before = $this->existingRow($model, $pk);
|
||||
$values = $this->collectWritableValues($model);
|
||||
$compiled = $this->builder->update($metadata, $values, $pk);
|
||||
$this->connection->execute($compiled['sql'], $compiled['params']);
|
||||
|
||||
$this->notify(
|
||||
$metadata->table(),
|
||||
is_int($pk) || is_string($pk) ? $pk : (string) $pk,
|
||||
'update',
|
||||
$before,
|
||||
$this->auditSnapshot($model),
|
||||
);
|
||||
}
|
||||
|
||||
public function delete(Model $model): void
|
||||
{
|
||||
$metadata = $model::metadata();
|
||||
$primaryKeyProperty = $metadata->primaryKey();
|
||||
/** @var mixed $pk */
|
||||
$pk = $model->get($primaryKeyProperty);
|
||||
|
||||
if ($pk === null || $pk === 0 || $pk === '0' || $pk === '') {
|
||||
throw new CriteriaException(sprintf(
|
||||
'Cannot delete "%s" without a primary key value.',
|
||||
$metadata->class,
|
||||
));
|
||||
}
|
||||
|
||||
$before = $this->existingRow($model, $pk);
|
||||
$compiled = $this->builder->delete($metadata, $pk);
|
||||
$this->connection->execute($compiled['sql'], $compiled['params']);
|
||||
|
||||
$this->notify(
|
||||
$metadata->table(),
|
||||
is_int($pk) || is_string($pk) ? $pk : (string) $pk,
|
||||
'delete',
|
||||
$before,
|
||||
[],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Partial update by primary key: only the supplied properties are written.
|
||||
*
|
||||
* @param array<string, mixed> $values keyed by property or column
|
||||
*/
|
||||
public function patch(Model $model, int|string $pk, array $values): void
|
||||
{
|
||||
$metadata = $model::metadata();
|
||||
$writable = [];
|
||||
|
||||
foreach ($values as $key => $value) {
|
||||
$key = (string) $key;
|
||||
$property = $metadata->resolveProperty($key);
|
||||
|
||||
if ($property === null) {
|
||||
throw CriteriaException::unknownColumn(
|
||||
$metadata->class,
|
||||
$key,
|
||||
$metadata->knownKeys(),
|
||||
);
|
||||
}
|
||||
|
||||
$definition = $metadata->propertyMetadata($property);
|
||||
|
||||
if (!$definition->isWritable()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$writable[$property] = TypeCaster::toDatabaseValue($model->castFor(
|
||||
$definition,
|
||||
$value,
|
||||
));
|
||||
}
|
||||
|
||||
if ($writable === []) {
|
||||
throw new CriteriaException(sprintf(
|
||||
'patch() received no writable column for "%s".',
|
||||
$metadata->class,
|
||||
));
|
||||
}
|
||||
|
||||
$compiled = $this->builder->update($metadata, $writable, $pk);
|
||||
$this->connection->execute($compiled['sql'], $compiled['params']);
|
||||
}
|
||||
|
||||
public function remove(Model $model, int|string $pk): bool
|
||||
{
|
||||
$metadata = $model::metadata();
|
||||
$compiled = $this->builder->delete($metadata, $pk);
|
||||
|
||||
return $this->connection->execute($compiled['sql'], $compiled['params']) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed> keyed by PROPERTY
|
||||
*/
|
||||
public function collectWritableValues(Model $model): array
|
||||
{
|
||||
$metadata = $model::metadata();
|
||||
$values = [];
|
||||
|
||||
foreach ($metadata->writable() as $property) {
|
||||
/** @var mixed $value */
|
||||
$value = $model->get($property);
|
||||
$values[$property] = TypeCaster::toDatabaseValue($value);
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $pk
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
private function existingRow(Model $model, mixed $pk): ?array
|
||||
{
|
||||
if ($this->audit === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$metadata = $model::metadata();
|
||||
$columns = [];
|
||||
|
||||
foreach ($metadata->properties() as $property) {
|
||||
if ($property->isRelation()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$columns[] = $property->column;
|
||||
}
|
||||
|
||||
$sql =
|
||||
'SELECT '
|
||||
. implode(', ', array_map(
|
||||
static fn(string $column): string => '`' . $column . '`',
|
||||
$columns,
|
||||
))
|
||||
. ' FROM `'
|
||||
. $metadata->table()
|
||||
. '` WHERE `'
|
||||
. $metadata->primaryKeyColumn()
|
||||
. '` = ? LIMIT 1';
|
||||
|
||||
$rows = $this->connection->select($sql, [$pk]);
|
||||
|
||||
return $rows[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function auditSnapshot(Model $model): array
|
||||
{
|
||||
$snapshot = [];
|
||||
|
||||
foreach ($model->toArray() as $key => $value) {
|
||||
if ($value instanceof DateTimeInterface) {
|
||||
$snapshot[$key] = $value->format(DATE_ATOM);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_scalar($value) || $value === null) {
|
||||
$snapshot[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $snapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed>|null $before
|
||||
* @param array<string, mixed> $after
|
||||
*/
|
||||
private function notify(
|
||||
string $table,
|
||||
int|string $pk,
|
||||
string $action,
|
||||
?array $before,
|
||||
array $after,
|
||||
): void {
|
||||
$this->audit?->onWrite($table, $pk, $action, $before, $after);
|
||||
}
|
||||
|
||||
private function assertNotPartial(Model $model, string $operation): void
|
||||
{
|
||||
if ($model->isPartial()) {
|
||||
/** @var class-string<\Camelia\Orm\Model> $class */
|
||||
$class = $model::class;
|
||||
|
||||
throw PartialModelException::onWrite($class, $operation);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Persistence;
|
||||
|
||||
use Camelia\Orm\Model;
|
||||
|
||||
/**
|
||||
* Applies the runtime validation rules declared through attributes.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class Validator
|
||||
{
|
||||
/**
|
||||
* @return array<string, list<string>> property => messages, empty when valid
|
||||
*/
|
||||
public function validate(Model $model): array
|
||||
{
|
||||
$metadata = $model::metadata();
|
||||
$errors = [];
|
||||
|
||||
foreach ($metadata->properties() as $property) {
|
||||
if ($property->ignored) {
|
||||
continue;
|
||||
}
|
||||
|
||||
/** @var mixed $value */
|
||||
$value = $model->get($property->name);
|
||||
|
||||
if ($property->required && ($value === null || $value === '')) {
|
||||
$errors[$property->name][] = sprintf('El campo %s es requerido', $property->name);
|
||||
}
|
||||
|
||||
if (
|
||||
$property->enumClass !== null
|
||||
&& $value !== null
|
||||
&& !$value instanceof $property->enumClass
|
||||
) {
|
||||
$errors[$property->name][] = sprintf(
|
||||
'El valor de %s no es válido',
|
||||
$property->name,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
$property->maxLength !== null
|
||||
&& $value !== null
|
||||
&& is_string($value)
|
||||
&& mb_strlen($value) > $property->maxLength
|
||||
) {
|
||||
$errors[$property->name][] = sprintf(
|
||||
'El campo %s supera %d caracteres',
|
||||
$property->name,
|
||||
$property->maxLength,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Query;
|
||||
|
||||
/**
|
||||
* Immutable SQL operator applied to one column.
|
||||
*
|
||||
* Instances are built through the static factories; no global helper functions exist.
|
||||
*/
|
||||
final readonly class Cond
|
||||
{
|
||||
public const OP_EQ = 'eq';
|
||||
public const OP_NEQ = 'neq';
|
||||
public const OP_GT = 'gt';
|
||||
public const OP_GTE = 'gte';
|
||||
public const OP_LT = 'lt';
|
||||
public const OP_LTE = 'lte';
|
||||
public const OP_IN = 'in';
|
||||
public const OP_NOT_IN = 'notIn';
|
||||
public const OP_BETWEEN = 'between';
|
||||
public const OP_NOT_BETWEEN = 'notBetween';
|
||||
public const OP_LIKE = 'like';
|
||||
public const OP_NOT_LIKE = 'notLike';
|
||||
public const OP_IS_NULL = 'isNull';
|
||||
public const OP_IS_NOT_NULL = 'isNotNull';
|
||||
public const OP_RAW = 'raw';
|
||||
|
||||
/**
|
||||
* @param list<mixed> $values
|
||||
*/
|
||||
private function __construct(
|
||||
public string $operator,
|
||||
public array $values,
|
||||
public string $rawSql = '',
|
||||
) {}
|
||||
|
||||
public static function eq(mixed $value): self
|
||||
{
|
||||
return new self(self::OP_EQ, [$value]);
|
||||
}
|
||||
|
||||
public static function neq(mixed $value): self
|
||||
{
|
||||
return new self(self::OP_NEQ, [$value]);
|
||||
}
|
||||
|
||||
public static function gt(mixed $value): self
|
||||
{
|
||||
return new self(self::OP_GT, [$value]);
|
||||
}
|
||||
|
||||
public static function gte(mixed $value): self
|
||||
{
|
||||
return new self(self::OP_GTE, [$value]);
|
||||
}
|
||||
|
||||
public static function lt(mixed $value): self
|
||||
{
|
||||
return new self(self::OP_LT, [$value]);
|
||||
}
|
||||
|
||||
public static function lte(mixed $value): self
|
||||
{
|
||||
return new self(self::OP_LTE, [$value]);
|
||||
}
|
||||
|
||||
/** @param list<mixed> $values */
|
||||
public static function in(array $values): self
|
||||
{
|
||||
return new self(self::OP_IN, array_values($values));
|
||||
}
|
||||
|
||||
/** @param list<mixed> $values */
|
||||
public static function notIn(array $values): self
|
||||
{
|
||||
return new self(self::OP_NOT_IN, array_values($values));
|
||||
}
|
||||
|
||||
public static function between(mixed $from, mixed $to): self
|
||||
{
|
||||
return new self(self::OP_BETWEEN, [$from, $to]);
|
||||
}
|
||||
|
||||
public static function notBetween(mixed $from, mixed $to): self
|
||||
{
|
||||
return new self(self::OP_NOT_BETWEEN, [$from, $to]);
|
||||
}
|
||||
|
||||
public static function like(string $value): self
|
||||
{
|
||||
return new self(self::OP_LIKE, [$value]);
|
||||
}
|
||||
|
||||
public static function notLike(string $value): self
|
||||
{
|
||||
return new self(self::OP_NOT_LIKE, [$value]);
|
||||
}
|
||||
|
||||
public static function isNull(): self
|
||||
{
|
||||
return new self(self::OP_IS_NULL, []);
|
||||
}
|
||||
|
||||
public static function isNotNull(): self
|
||||
{
|
||||
return new self(self::OP_IS_NOT_NULL, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape hatch: the SQL fragment and its parameters are emitted verbatim.
|
||||
*
|
||||
* The column identifier is not validated here; callers own the safety of $sql.
|
||||
*
|
||||
* @param list<mixed> $params
|
||||
*/
|
||||
public static function raw(string $sql, array $params = []): self
|
||||
{
|
||||
return new self(self::OP_RAW, array_values($params), $sql);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Query;
|
||||
|
||||
use Camelia\Orm\Exception\CriteriaException;
|
||||
use Camelia\Orm\Metadata\ClassMetadata;
|
||||
|
||||
/**
|
||||
* Turns a criteria map into a WHERE fragment plus bound parameters.
|
||||
*
|
||||
* Every read path goes through here: find, findFirst, count, page and Query.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class CriteriaCompiler
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Dialect $dialect,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed|Cond> $criteria
|
||||
* @return array{0: string, 1: list<mixed>} empty SQL when there is nothing to filter
|
||||
*/
|
||||
public function compile(ClassMetadata $metadata, array $criteria): array
|
||||
{
|
||||
$clauses = [];
|
||||
$params = [];
|
||||
|
||||
foreach ($criteria as $key => $value) {
|
||||
$key = (string) $key;
|
||||
$property = $metadata->resolveProperty($key);
|
||||
|
||||
if ($property === null) {
|
||||
throw CriteriaException::unknownColumn(
|
||||
$metadata->class,
|
||||
$key,
|
||||
$metadata->knownKeys(),
|
||||
);
|
||||
}
|
||||
|
||||
$column = $metadata->propertyMetadata($property)->column;
|
||||
$quotedColumn = $this->quoteColumn($column);
|
||||
|
||||
[$sql, $bound] = $this->compileValue($quotedColumn, $value);
|
||||
|
||||
$clauses[] = $sql;
|
||||
$params = array_merge($params, $bound);
|
||||
}
|
||||
|
||||
if ($clauses === []) {
|
||||
return ['', []];
|
||||
}
|
||||
|
||||
return [implode(' AND ', $clauses), $params];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: string, 1: list<mixed>}
|
||||
*/
|
||||
private function compileValue(string $quotedColumn, mixed $value): array
|
||||
{
|
||||
if ($value instanceof Cond) {
|
||||
if ($value->operator === Cond::OP_IN && $value->values === []) {
|
||||
throw CriteriaException::emptyIn();
|
||||
}
|
||||
|
||||
return $this->dialect->renderCondition($quotedColumn, $value);
|
||||
}
|
||||
|
||||
if ($value === null) {
|
||||
return [$quotedColumn . ' IS NULL', []];
|
||||
}
|
||||
|
||||
if (is_array($value)) {
|
||||
if ($value === []) {
|
||||
return ['1 = 0', []];
|
||||
}
|
||||
|
||||
return $this->dialect->renderCondition($quotedColumn, Cond::in(array_values($value)));
|
||||
}
|
||||
|
||||
return [$quotedColumn . ' = ?', [$value]];
|
||||
}
|
||||
|
||||
/**
|
||||
* Quotes a column, honoring a table-qualified name such as "table.column".
|
||||
*/
|
||||
private function quoteColumn(string $column): string
|
||||
{
|
||||
if (!str_contains($column, '.')) {
|
||||
return $this->dialect->quoteIdentifier($column);
|
||||
}
|
||||
|
||||
[$table, $rest] = explode('.', $column, 2);
|
||||
|
||||
return (
|
||||
$this->dialect->quoteIdentifier($table) . '.' . $this->dialect->quoteIdentifier($rest)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Query;
|
||||
|
||||
/**
|
||||
* Translates abstract query parts into engine-specific SQL.
|
||||
*/
|
||||
interface Dialect
|
||||
{
|
||||
public function quoteIdentifier(string $identifier): string;
|
||||
|
||||
/**
|
||||
* Renders one operator applied to an already quoted column.
|
||||
*
|
||||
* @return array{0: string, 1: list<mixed>}
|
||||
*/
|
||||
public function renderCondition(string $quotedColumn, Cond $cond): array;
|
||||
|
||||
/** @param list<mixed> $values */
|
||||
public function placeholders(array $values): string;
|
||||
|
||||
public function limitClause(?int $limit, ?int $offset): string;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Query;
|
||||
|
||||
/**
|
||||
* Mutable accumulator used only inside Query::whereGroup().
|
||||
*
|
||||
* This is the single mutable entry point of the API, and it never escapes the closure.
|
||||
*/
|
||||
final class GroupCond
|
||||
{
|
||||
/** @var list<array{0: string, 1: mixed|Cond, 2: 'AND'|'OR'}> */
|
||||
private array $parts = [];
|
||||
|
||||
public function and(string $column, mixed $value): self
|
||||
{
|
||||
$this->parts[] = [$column, $value, 'AND'];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function or(string $column, mixed $value): self
|
||||
{
|
||||
$this->parts[] = [$column, $value, 'OR'];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
* @return list<array{0: string, 1: mixed|Cond, 2: 'AND'|'OR'}>
|
||||
*/
|
||||
public function parts(): array
|
||||
{
|
||||
return $this->parts;
|
||||
}
|
||||
|
||||
public function isEmpty(): bool
|
||||
{
|
||||
return $this->parts === [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Query;
|
||||
|
||||
use Camelia\Orm\Exception\CriteriaException;
|
||||
|
||||
/**
|
||||
* MariaDB / MySQL renderer. The only Dialect implementation shipped.
|
||||
*/
|
||||
final class MySqlDialect implements Dialect
|
||||
{
|
||||
public function quoteIdentifier(string $identifier): string
|
||||
{
|
||||
return '`' . str_replace('`', '``', $identifier) . '`';
|
||||
}
|
||||
|
||||
public function renderCondition(string $quotedColumn, Cond $cond): array
|
||||
{
|
||||
return match ($cond->operator) {
|
||||
Cond::OP_EQ => [$quotedColumn . ' = ?', $cond->values],
|
||||
Cond::OP_NEQ => [$quotedColumn . ' <> ?', $cond->values],
|
||||
Cond::OP_GT => [$quotedColumn . ' > ?', $cond->values],
|
||||
Cond::OP_GTE => [$quotedColumn . ' >= ?', $cond->values],
|
||||
Cond::OP_LT => [$quotedColumn . ' < ?', $cond->values],
|
||||
Cond::OP_LTE => [$quotedColumn . ' <= ?', $cond->values],
|
||||
Cond::OP_LIKE => [$quotedColumn . ' LIKE ?', $cond->values],
|
||||
Cond::OP_NOT_LIKE => [$quotedColumn . ' NOT LIKE ?', $cond->values],
|
||||
Cond::OP_IN => $this->renderIn($quotedColumn, $cond->values),
|
||||
Cond::OP_NOT_IN => $this->renderNotIn($quotedColumn, $cond->values),
|
||||
Cond::OP_BETWEEN => [$quotedColumn . ' BETWEEN ? AND ?', $cond->values],
|
||||
Cond::OP_NOT_BETWEEN => [$quotedColumn . ' NOT BETWEEN ? AND ?', $cond->values],
|
||||
Cond::OP_IS_NULL => [$quotedColumn . ' IS NULL', []],
|
||||
Cond::OP_IS_NOT_NULL => [$quotedColumn . ' IS NOT NULL', []],
|
||||
Cond::OP_RAW => ['(' . $cond->rawSql . ')', $cond->values],
|
||||
default => throw new CriteriaException(sprintf(
|
||||
'Unsupported operator "%s".',
|
||||
$cond->operator,
|
||||
)),
|
||||
};
|
||||
}
|
||||
|
||||
public function placeholders(array $values): string
|
||||
{
|
||||
return implode(', ', array_fill(0, count($values), '?'));
|
||||
}
|
||||
|
||||
public function limitClause(?int $limit, ?int $offset): string
|
||||
{
|
||||
if ($limit === null && $offset === null) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($limit === null) {
|
||||
// MySQL requires a LIMIT when OFFSET is present; use the documented max row count.
|
||||
return ' LIMIT 18446744073709551615 OFFSET ' . max(0, (int) $offset);
|
||||
}
|
||||
|
||||
$clause = ' LIMIT ' . max(0, $limit);
|
||||
|
||||
if ($offset !== null) {
|
||||
$clause .= ' OFFSET ' . max(0, $offset);
|
||||
}
|
||||
|
||||
return $clause;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<mixed> $values
|
||||
* @return array{0: string, 1: list<mixed>}
|
||||
*/
|
||||
private function renderIn(string $quotedColumn, array $values): array
|
||||
{
|
||||
if ($values === []) {
|
||||
// An empty IN set matches nothing; emit a deterministic always-false predicate.
|
||||
return ['1 = 0', []];
|
||||
}
|
||||
|
||||
return [$quotedColumn . ' IN (' . $this->placeholders($values) . ')', $values];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<mixed> $values
|
||||
* @return array{0: string, 1: list<mixed>}
|
||||
*/
|
||||
private function renderNotIn(string $quotedColumn, array $values): array
|
||||
{
|
||||
if ($values === []) {
|
||||
// NOT IN over an empty set matches every row.
|
||||
return ['1 = 1', []];
|
||||
}
|
||||
|
||||
return [$quotedColumn . ' NOT IN (' . $this->placeholders($values) . ')', $values];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Query;
|
||||
|
||||
use Camelia\Orm\Connection\Connection;
|
||||
use Camelia\Orm\Exception\CriteriaException;
|
||||
use Camelia\Orm\Exception\RecordNotFoundException;
|
||||
use Camelia\Orm\Model;
|
||||
use Camelia\Orm\Pagination\Page;
|
||||
use Camelia\Orm\Repository;
|
||||
use Camelia\Orm\Support\TypeCaster;
|
||||
|
||||
/**
|
||||
* Immutable fluent query. Every builder method returns a copy.
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
final class Query
|
||||
{
|
||||
/**
|
||||
* @param Repository<Model> $repository
|
||||
*/
|
||||
private function __construct(
|
||||
private readonly Repository $repository,
|
||||
private readonly Connection $connection,
|
||||
private readonly QueryBuilder $builder,
|
||||
private readonly QueryState $state,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param Repository<Model> $repository
|
||||
*/
|
||||
public static function start(
|
||||
Repository $repository,
|
||||
QueryState $state,
|
||||
Connection $connection,
|
||||
QueryBuilder $builder,
|
||||
): self {
|
||||
return new self($repository, $connection, $builder, $state);
|
||||
}
|
||||
|
||||
public function where(string $column, mixed $value): self
|
||||
{
|
||||
$criteria = $this->state->criteria;
|
||||
$criteria[$column] = $value;
|
||||
|
||||
return $this->withState($this->state->withCriteria($criteria));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<mixed> $values
|
||||
*/
|
||||
public function whereIn(string $column, array $values): self
|
||||
{
|
||||
return $this->where($column, Cond::in($values));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<mixed> $values
|
||||
*/
|
||||
public function whereNotIn(string $column, array $values): self
|
||||
{
|
||||
return $this->where($column, Cond::notIn($values));
|
||||
}
|
||||
|
||||
public function whereNull(string $column): self
|
||||
{
|
||||
return $this->where($column, Cond::isNull());
|
||||
}
|
||||
|
||||
public function whereNotNull(string $column): self
|
||||
{
|
||||
return $this->where($column, Cond::isNotNull());
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a parenthesized group of OR conditions, combined with $boolean.
|
||||
*
|
||||
* @param callable(GroupCond): mixed $callback
|
||||
*/
|
||||
public function whereGroup(callable $callback, string $boolean = 'AND'): self
|
||||
{
|
||||
$group = new GroupCond();
|
||||
$callback($group);
|
||||
|
||||
if ($group->isEmpty()) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$parts = [];
|
||||
|
||||
foreach ($group->parts() as [$column, $value, $_]) {
|
||||
$parts[] = [$column, $value];
|
||||
}
|
||||
|
||||
$groups = $this->state->groups;
|
||||
$groups[] = [strtoupper($boolean) === 'OR' ? 'OR' : 'AND', $parts];
|
||||
|
||||
return $this->withState($this->state->withGroups($groups));
|
||||
}
|
||||
|
||||
public function orderBy(string $column, string $direction = 'ASC'): self
|
||||
{
|
||||
$order = $this->state->order;
|
||||
$order[] = [$column, strtoupper($direction) === 'DESC' ? 'DESC' : 'ASC'];
|
||||
|
||||
return $this->withState($this->state->withOrder($order));
|
||||
}
|
||||
|
||||
public function orderByDesc(string $column): self
|
||||
{
|
||||
return $this->orderBy($column, 'DESC');
|
||||
}
|
||||
|
||||
public function limit(int $limit): self
|
||||
{
|
||||
return $this->withState($this->state->withLimit($limit));
|
||||
}
|
||||
|
||||
public function offset(int $offset): self
|
||||
{
|
||||
return $this->withState($this->state->withOffset($offset));
|
||||
}
|
||||
|
||||
public function select(string ...$columns): self
|
||||
{
|
||||
return $this->withState($this->state->withColumns(array_values($columns)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param true|string|array<int|string, mixed> ...$relations
|
||||
*/
|
||||
public function with(bool|string|array ...$relations): self
|
||||
{
|
||||
if ($relations === []) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
if ($relations[0] === true) {
|
||||
return $this->withState($this->state->withRelations(true));
|
||||
}
|
||||
|
||||
$normalized = [];
|
||||
|
||||
foreach ($relations as $relation) {
|
||||
if (!is_array($relation)) {
|
||||
$normalized[] = (string) $relation;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($relation as $key => $value) {
|
||||
if (is_int($key)) {
|
||||
$normalized[] = (string) $value;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$normalized[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->withState($this->state->withRelations($normalized));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<Model>
|
||||
*/
|
||||
public function get(): array
|
||||
{
|
||||
return $this->runSelect();
|
||||
}
|
||||
|
||||
public function first(): ?Model
|
||||
{
|
||||
$rows = $this->withState($this->state->withLimit(1))->runSelect();
|
||||
|
||||
return $rows[0] ?? null;
|
||||
}
|
||||
|
||||
public function firstOrFail(): Model
|
||||
{
|
||||
$model = $this->first();
|
||||
|
||||
if ($model === null) {
|
||||
throw RecordNotFoundException::first($this->state->metadata->class);
|
||||
}
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
public function count(): int
|
||||
{
|
||||
$compiled = $this->builder->count($this->state->metadata, []);
|
||||
$sql = $compiled['sql'];
|
||||
$params = [];
|
||||
|
||||
[$where, $whereParams] = $this->compileWhere();
|
||||
|
||||
if ($where !== '') {
|
||||
$sql .= ' WHERE ' . $where;
|
||||
$params = $whereParams;
|
||||
}
|
||||
|
||||
return (int) $this->connection->scalar($sql, $params);
|
||||
}
|
||||
|
||||
public function exists(): bool
|
||||
{
|
||||
return $this->count() > 0;
|
||||
}
|
||||
|
||||
public function sum(string $column): float
|
||||
{
|
||||
return (float) ($this->aggregate($column, 'SUM') ?? 0.0);
|
||||
}
|
||||
|
||||
public function avg(string $column): float
|
||||
{
|
||||
return (float) ($this->aggregate($column, 'AVG') ?? 0.0);
|
||||
}
|
||||
|
||||
public function max(string $column): ?float
|
||||
{
|
||||
return $this->aggregate($column, 'MAX');
|
||||
}
|
||||
|
||||
public function min(string $column): ?float
|
||||
{
|
||||
return $this->aggregate($column, 'MIN');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<mixed>
|
||||
*/
|
||||
public function pluck(string $column): array
|
||||
{
|
||||
$metadata = $this->state->metadata;
|
||||
$property = $metadata->resolveProperty($column);
|
||||
|
||||
if ($property === null) {
|
||||
throw CriteriaException::unknownColumn(
|
||||
$metadata->class,
|
||||
$column,
|
||||
$metadata->knownKeys(),
|
||||
);
|
||||
}
|
||||
|
||||
$models = $this->withState($this->state->withColumns([$property]))->runSelect();
|
||||
$values = [];
|
||||
|
||||
foreach ($models as $model) {
|
||||
$values[] = TypeCaster::toSerializable($model->get($property));
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
public function page(int $page = 1, int $perPage = 20): Page
|
||||
{
|
||||
$total = $this->count();
|
||||
$safePage = max(1, $page);
|
||||
$safePerPage = max(Page::MIN_PER_PAGE, min(Page::MAX_PER_PAGE, $perPage));
|
||||
|
||||
$items = $this->withState(
|
||||
$this->state->withLimit($safePerPage)->withOffset(($safePage - 1) * $safePerPage),
|
||||
)->runSelect();
|
||||
|
||||
return Page::of($items, $safePage, $safePerPage, $total);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{sql: string, params: list<mixed>}
|
||||
*/
|
||||
public function toSql(): array
|
||||
{
|
||||
return $this->compileSelect();
|
||||
}
|
||||
|
||||
private function withState(QueryState $state): self
|
||||
{
|
||||
return new self($this->repository, $this->connection, $this->builder, $state);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{sql: string, params: list<mixed>}
|
||||
*/
|
||||
private function compileSelect(): array
|
||||
{
|
||||
$compiled = $this->builder->select(
|
||||
$this->state->metadata,
|
||||
[],
|
||||
$this->state->order,
|
||||
$this->state->limit,
|
||||
$this->state->offset,
|
||||
$this->state->columns,
|
||||
);
|
||||
|
||||
[$where, $whereParams] = $this->compileWhere();
|
||||
|
||||
if ($where === '') {
|
||||
return $compiled;
|
||||
}
|
||||
|
||||
return [
|
||||
'sql' => $this->injectWhere($compiled['sql'], $where),
|
||||
'params' => array_merge($whereParams, $compiled['params']),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts a WHERE clause before ORDER BY / LIMIT, which is where SQL requires it.
|
||||
*/
|
||||
private function injectWhere(string $sql, string $where): string
|
||||
{
|
||||
$positions = [];
|
||||
|
||||
foreach ([' ORDER BY', ' LIMIT'] as $clause) {
|
||||
$position = strpos($sql, $clause);
|
||||
|
||||
if ($position !== false) {
|
||||
$positions[] = $position;
|
||||
}
|
||||
}
|
||||
|
||||
$insertAt = $positions === [] ? strlen($sql) : min($positions);
|
||||
|
||||
return substr($sql, 0, $insertAt) . ' WHERE ' . $where . substr($sql, $insertAt);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: string, 1: list<mixed>}
|
||||
*/
|
||||
private function compileWhere(): array
|
||||
{
|
||||
$compiler = new CriteriaCompiler(new MySqlDialect());
|
||||
[$baseSql, $params] = $compiler->compile($this->state->metadata, $this->state->criteria);
|
||||
|
||||
$sqlParts = $baseSql === '' ? [] : ['(' . $baseSql . ')'];
|
||||
|
||||
foreach ($this->state->groups as [$boolean, $parts]) {
|
||||
$rendered = [];
|
||||
|
||||
foreach ($parts as [$column, $value]) {
|
||||
[$sql, $bound] = $compiler->compile($this->state->metadata, [$column => $value]);
|
||||
|
||||
if ($sql === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($rendered !== []) {
|
||||
$rendered[] = 'OR';
|
||||
}
|
||||
|
||||
$rendered[] = $sql;
|
||||
$params = array_merge($params, $bound);
|
||||
}
|
||||
|
||||
if ($rendered === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($sqlParts !== []) {
|
||||
$sqlParts[] = $boolean;
|
||||
}
|
||||
|
||||
$sqlParts[] = '(' . implode(' ', $rendered) . ')';
|
||||
}
|
||||
|
||||
return [$sqlParts === [] ? '' : implode(' ', $sqlParts), $params];
|
||||
}
|
||||
|
||||
private function aggregate(string $column, string $function): ?float
|
||||
{
|
||||
$compiled = $this->builder->aggregate($this->state->metadata, $column, $function, []);
|
||||
$sql = $compiled['sql'];
|
||||
$params = [];
|
||||
|
||||
[$where, $whereParams] = $this->compileWhere();
|
||||
|
||||
if ($where !== '') {
|
||||
$sql .= ' WHERE ' . $where;
|
||||
$params = $whereParams;
|
||||
}
|
||||
|
||||
$value = $this->connection->scalar($sql, $params);
|
||||
|
||||
return $value === null ? null : (float) $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<Model>
|
||||
*/
|
||||
private function runSelect(): array
|
||||
{
|
||||
$compiled = $this->compileSelect();
|
||||
$rows = $this->connection->select($compiled['sql'], $compiled['params']);
|
||||
|
||||
return $this->repository->hydrateRows($rows, $this->state->columns, $this->state->with);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Query;
|
||||
|
||||
use Camelia\Orm\Exception\CriteriaException;
|
||||
use Camelia\Orm\Metadata\ClassMetadata;
|
||||
|
||||
/**
|
||||
* Compiles SQL statements for one model. Produces strings and parameter lists only.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class QueryBuilder
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Dialect $dialect,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed|Cond> $criteria
|
||||
* @param list<array{0: string, 1: 'ASC'|'DESC'}> $order
|
||||
* @param list<string>|null $columns properties to select
|
||||
* @return array{sql: string, params: list<mixed>}
|
||||
*/
|
||||
public function select(
|
||||
ClassMetadata $metadata,
|
||||
array $criteria,
|
||||
array $order = [],
|
||||
?int $limit = null,
|
||||
?int $offset = null,
|
||||
?array $columns = null,
|
||||
): array {
|
||||
$table = $this->dialect->quoteIdentifier($metadata->table());
|
||||
$list = $this->compileSelectList($metadata, $columns);
|
||||
|
||||
[$where, $params] = (new CriteriaCompiler($this->dialect))->compile($metadata, $criteria);
|
||||
|
||||
$sql = 'SELECT ' . $list . ' FROM ' . $table;
|
||||
|
||||
if ($where !== '') {
|
||||
$sql .= ' WHERE ' . $where;
|
||||
}
|
||||
|
||||
$sql .= $this->compileOrder($metadata, $order, $table);
|
||||
$sql .= $this->dialect->limitClause($limit, $offset);
|
||||
|
||||
return ['sql' => $sql, 'params' => $params];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed|Cond> $criteria
|
||||
* @return array{sql: string, params: list<mixed>}
|
||||
*/
|
||||
public function count(ClassMetadata $metadata, array $criteria): array
|
||||
{
|
||||
$table = $this->dialect->quoteIdentifier($metadata->table());
|
||||
[$where, $params] = (new CriteriaCompiler($this->dialect))->compile($metadata, $criteria);
|
||||
|
||||
$sql = 'SELECT COUNT(*) AS aggregate FROM ' . $table;
|
||||
|
||||
if ($where !== '') {
|
||||
$sql .= ' WHERE ' . $where;
|
||||
}
|
||||
|
||||
return ['sql' => $sql, 'params' => $params];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed|Cond> $criteria
|
||||
* @return array{sql: string, params: list<mixed>}
|
||||
*/
|
||||
public function aggregate(
|
||||
ClassMetadata $metadata,
|
||||
string $column,
|
||||
string $function,
|
||||
array $criteria,
|
||||
): array {
|
||||
$property = $metadata->resolveProperty($column);
|
||||
|
||||
if ($property === null) {
|
||||
throw CriteriaException::unknownColumn(
|
||||
$metadata->class,
|
||||
$column,
|
||||
$metadata->knownKeys(),
|
||||
);
|
||||
}
|
||||
|
||||
$quoted = $this->dialect->quoteIdentifier($metadata->propertyMetadata($property)->column);
|
||||
$table = $this->dialect->quoteIdentifier($metadata->table());
|
||||
[$where, $params] = (new CriteriaCompiler($this->dialect))->compile($metadata, $criteria);
|
||||
|
||||
$sql = 'SELECT ' . $function . '(' . $quoted . ') AS aggregate FROM ' . $table;
|
||||
|
||||
if ($where !== '') {
|
||||
$sql .= ' WHERE ' . $where;
|
||||
}
|
||||
|
||||
return ['sql' => $sql, 'params' => $params];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $values keyed by PROPERTY
|
||||
* @return array{sql: string, params: list<mixed>}
|
||||
*/
|
||||
public function insert(ClassMetadata $metadata, array $values): array
|
||||
{
|
||||
$columns = [];
|
||||
$placeholders = [];
|
||||
$params = [];
|
||||
|
||||
foreach ($values as $property => $value) {
|
||||
$columns[] = $this->dialect->quoteIdentifier($metadata->column($property));
|
||||
$placeholders[] = '?';
|
||||
$params[] = $value;
|
||||
}
|
||||
|
||||
if ($columns === []) {
|
||||
throw new CriteriaException('Refusing to build an INSERT without columns.');
|
||||
}
|
||||
|
||||
$sql =
|
||||
'INSERT INTO '
|
||||
. $this->dialect->quoteIdentifier($metadata->table())
|
||||
. ' ('
|
||||
. implode(', ', $columns)
|
||||
. ') VALUES ('
|
||||
. implode(', ', $placeholders)
|
||||
. ')';
|
||||
|
||||
return ['sql' => $sql, 'params' => $params];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $values keyed by PROPERTY
|
||||
* @return array{sql: string, params: list<mixed>}
|
||||
*/
|
||||
public function update(ClassMetadata $metadata, array $values, mixed $primaryKey): array
|
||||
{
|
||||
$assignments = [];
|
||||
$params = [];
|
||||
|
||||
foreach ($values as $property => $value) {
|
||||
$assignments[] = $this->dialect->quoteIdentifier($metadata->column($property)) . ' = ?';
|
||||
$params[] = $value;
|
||||
}
|
||||
|
||||
if ($assignments === []) {
|
||||
throw new CriteriaException('Refusing to build an UPDATE without columns.');
|
||||
}
|
||||
|
||||
$params[] = $primaryKey;
|
||||
|
||||
$sql =
|
||||
'UPDATE '
|
||||
. $this->dialect->quoteIdentifier($metadata->table())
|
||||
. ' SET '
|
||||
. implode(', ', $assignments)
|
||||
. ' WHERE '
|
||||
. $this->dialect->quoteIdentifier($metadata->primaryKeyColumn())
|
||||
. ' = ?';
|
||||
|
||||
return ['sql' => $sql, 'params' => $params];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{sql: string, params: list<mixed>}
|
||||
*/
|
||||
public function delete(ClassMetadata $metadata, mixed $primaryKey): array
|
||||
{
|
||||
$sql =
|
||||
'DELETE FROM '
|
||||
. $this->dialect->quoteIdentifier($metadata->table())
|
||||
. ' WHERE '
|
||||
. $this->dialect->quoteIdentifier($metadata->primaryKeyColumn())
|
||||
. ' = ?';
|
||||
|
||||
return ['sql' => $sql, 'params' => [$primaryKey]];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string>|null $columns
|
||||
*/
|
||||
private function compileSelectList(ClassMetadata $metadata, ?array $columns): string
|
||||
{
|
||||
if ($columns === null || $columns === []) {
|
||||
$parts = [];
|
||||
|
||||
foreach ($metadata->properties() as $property) {
|
||||
if ($property->isRelation()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$parts[] = $this->dialect->quoteIdentifier($property->column);
|
||||
}
|
||||
|
||||
return implode(', ', $parts);
|
||||
}
|
||||
|
||||
$parts = [];
|
||||
|
||||
foreach ($columns as $column) {
|
||||
$property = $metadata->resolveProperty($column);
|
||||
|
||||
if ($property === null) {
|
||||
throw CriteriaException::unknownColumn(
|
||||
$metadata->class,
|
||||
$column,
|
||||
$metadata->knownKeys(),
|
||||
);
|
||||
}
|
||||
|
||||
$parts[] = $this->dialect->quoteIdentifier($metadata->propertyMetadata(
|
||||
$property,
|
||||
)->column);
|
||||
}
|
||||
|
||||
return implode(', ', $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{0: string, 1: 'ASC'|'DESC'}> $order
|
||||
*/
|
||||
private function compileOrder(ClassMetadata $metadata, array $order, string $table): string
|
||||
{
|
||||
if ($order === []) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$parts = [];
|
||||
|
||||
foreach ($order as [$column, $direction]) {
|
||||
$property = $metadata->resolveProperty($column);
|
||||
|
||||
if ($property === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$normalized = strtoupper($direction);
|
||||
|
||||
if ($normalized !== 'ASC' && $normalized !== 'DESC') {
|
||||
throw CriteriaException::invalidOrderDirection($direction);
|
||||
}
|
||||
|
||||
$parts[] =
|
||||
$table
|
||||
. '.'
|
||||
. $this->dialect->quoteIdentifier($metadata->propertyMetadata($property)->column)
|
||||
. ' '
|
||||
. $normalized;
|
||||
}
|
||||
|
||||
if ($parts === []) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return ' ORDER BY ' . implode(', ', $parts);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Query;
|
||||
|
||||
use Camelia\Orm\Metadata\ClassMetadata;
|
||||
|
||||
/**
|
||||
* Immutable snapshot of every builder clause accumulated by Query.
|
||||
*
|
||||
* Each builder method on Query returns a copy of this value with one clause replaced, which is
|
||||
* what makes Query immutable without duplicating ten constructor arguments.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final readonly class QueryState
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed|Cond> $criteria
|
||||
* @param list<array{0: string, 1: 'ASC'|'DESC'}> $order
|
||||
* @param list<array{0: 'AND'|'OR', 1: list<array{0: string, 1: mixed|Cond}>}> $groups
|
||||
* @param list<string>|null $columns
|
||||
* @param true|array<int|string, mixed>|false $with
|
||||
*/
|
||||
public function __construct(
|
||||
public ClassMetadata $metadata,
|
||||
public array $criteria = [],
|
||||
public array $order = [],
|
||||
public array $groups = [],
|
||||
public ?array $columns = null,
|
||||
public ?int $limit = null,
|
||||
public ?int $offset = null,
|
||||
public bool|array $with = false,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed|Cond> $criteria
|
||||
*/
|
||||
public function withCriteria(array $criteria): self
|
||||
{
|
||||
return $this->with(['criteria' => $criteria]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{0: string, 1: 'ASC'|'DESC'}> $order
|
||||
*/
|
||||
public function withOrder(array $order): self
|
||||
{
|
||||
return $this->with(['order' => $order]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{0: 'AND'|'OR', 1: list<array{0: string, 1: mixed|Cond}>}> $groups
|
||||
*/
|
||||
public function withGroups(array $groups): self
|
||||
{
|
||||
return $this->with(['groups' => $groups]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $columns
|
||||
*/
|
||||
public function withColumns(array $columns): self
|
||||
{
|
||||
return $this->with(['columns' => $columns]);
|
||||
}
|
||||
|
||||
public function withLimit(?int $limit): self
|
||||
{
|
||||
return $this->with(['limit' => $limit]);
|
||||
}
|
||||
|
||||
public function withOffset(?int $offset): self
|
||||
{
|
||||
return $this->with(['offset' => $offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param true|array<int|string, mixed> $with
|
||||
*/
|
||||
public function withRelations(bool|array $with): self
|
||||
{
|
||||
return $this->with(['with' => $with]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $changes
|
||||
*/
|
||||
private function with(array $changes): self
|
||||
{
|
||||
return new self(
|
||||
$this->metadata,
|
||||
$changes['criteria'] ?? $this->criteria,
|
||||
$changes['order'] ?? $this->order,
|
||||
$changes['groups'] ?? $this->groups,
|
||||
array_key_exists('columns', $changes) ? $changes['columns'] : $this->columns,
|
||||
array_key_exists('limit', $changes) ? $changes['limit'] : $this->limit,
|
||||
array_key_exists('offset', $changes) ? $changes['offset'] : $this->offset,
|
||||
array_key_exists('with', $changes) ? $changes['with'] : $this->with,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Support;
|
||||
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* Abstraction over the current time, so hooks and generated values are testable.
|
||||
*/
|
||||
interface Clock
|
||||
{
|
||||
public function now(): DateTimeImmutable;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Support;
|
||||
|
||||
/**
|
||||
* Pure name conversion between PHP and SQL conventions.
|
||||
*/
|
||||
final class NameConverter
|
||||
{
|
||||
/**
|
||||
* Inserts an underscore before every internal uppercase letter.
|
||||
*
|
||||
* The first character is never prefixed, so leading acronyms keep their shape:
|
||||
* codigoEmpresa -> codigo_empresa, idZona -> id_zona, normal -> normal.
|
||||
*/
|
||||
public static function camelToSnake(string $name): string
|
||||
{
|
||||
if ($name === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$result = $name[0];
|
||||
$length = strlen($name);
|
||||
|
||||
for ($i = 1; $i < $length; $i++) {
|
||||
$char = $name[$i];
|
||||
|
||||
if ($char >= 'A' && $char <= 'Z' && $name[$i - 1] !== '_') {
|
||||
$result .= '_';
|
||||
}
|
||||
|
||||
$result .= $char;
|
||||
}
|
||||
|
||||
return strtolower($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a column name back to the matching camelCase property name.
|
||||
*/
|
||||
public static function snakeToCamel(string $name): string
|
||||
{
|
||||
if ($name === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$camel = str_replace(' ', '', ucwords(str_replace('_', ' ', $name)));
|
||||
|
||||
return lcfirst($camel);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Support;
|
||||
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* Default clock backed by the system time.
|
||||
*/
|
||||
final class SystemClock implements Clock
|
||||
{
|
||||
public function now(): DateTimeImmutable
|
||||
{
|
||||
return new DateTimeImmutable('now');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Orm\Support;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use DateTimeInterface;
|
||||
use Stringable;
|
||||
|
||||
/**
|
||||
* Converts scalar values between PHP types, SQL storage and JSON.
|
||||
*
|
||||
* Every refusal throws: a value that cannot be cast is never silently turned into null.
|
||||
* BigDecimal support is resolved by class name, because brick/math is only a suggestion.
|
||||
*/
|
||||
final class TypeCaster
|
||||
{
|
||||
private const BIG_DECIMAL = 'Brick\\Math\\BigDecimal';
|
||||
|
||||
public static function hasBigDecimal(): bool
|
||||
{
|
||||
return class_exists(self::BIG_DECIMAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Casts an incoming value to the declared property type.
|
||||
*
|
||||
* @throws \InvalidArgumentException when the value does not fit the type
|
||||
*/
|
||||
public static function cast(
|
||||
mixed $value,
|
||||
string $type,
|
||||
bool $nullable,
|
||||
string $context = '',
|
||||
): mixed {
|
||||
if ($value === null) {
|
||||
if ($nullable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw self::refusal(
|
||||
$context,
|
||||
$value,
|
||||
$type,
|
||||
'null is not allowed for a non-nullable property',
|
||||
);
|
||||
}
|
||||
|
||||
return match ($type) {
|
||||
'int' => self::toInt($value, $context),
|
||||
'float' => self::toFloat($value, $context),
|
||||
'bool' => self::toBool($value, $context),
|
||||
'string' => self::toString($value, $context),
|
||||
'array' => self::toArray($value, $context),
|
||||
DateTimeImmutable::class => self::toDateTime($value, $context),
|
||||
self::BIG_DECIMAL => self::toBigDecimal($value, $context),
|
||||
default => $value,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Casts an incoming value to a backed enum instance.
|
||||
*
|
||||
* @param class-string<\BackedEnum> $enumClass
|
||||
*/
|
||||
public static function castEnum(
|
||||
mixed $value,
|
||||
string $enumClass,
|
||||
bool $nullable,
|
||||
string $context,
|
||||
): mixed {
|
||||
if ($value === null) {
|
||||
if ($nullable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw self::refusal(
|
||||
$context,
|
||||
$value,
|
||||
$enumClass,
|
||||
'null is not allowed for a non-nullable enum',
|
||||
);
|
||||
}
|
||||
|
||||
if (!is_subclass_of($enumClass, \BackedEnum::class)) {
|
||||
throw self::refusal($context, $value, $enumClass, 'declared enum is not a backed enum');
|
||||
}
|
||||
|
||||
if ($value instanceof $enumClass) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (is_int($value) || is_string($value)) {
|
||||
$case = $enumClass::tryFrom($value);
|
||||
|
||||
if ($case !== null) {
|
||||
return $case;
|
||||
}
|
||||
}
|
||||
|
||||
throw self::refusal($context, $value, $enumClass, 'value is not a case of the enum');
|
||||
}
|
||||
|
||||
public static function toDatabaseValue(mixed $value): mixed
|
||||
{
|
||||
if ($value instanceof \BackedEnum) {
|
||||
return $value->value;
|
||||
}
|
||||
|
||||
if (is_object($value) && is_a($value, self::BIG_DECIMAL)) {
|
||||
return (string) $value;
|
||||
}
|
||||
|
||||
if ($value instanceof DateTimeInterface) {
|
||||
return $value->format('Y-m-d H:i:s');
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
public static function toSerializable(mixed $value): mixed
|
||||
{
|
||||
if ($value instanceof \BackedEnum) {
|
||||
return $value->value;
|
||||
}
|
||||
|
||||
if ($value instanceof DateTimeInterface) {
|
||||
return $value->format(DATE_ATOM);
|
||||
}
|
||||
|
||||
if (is_object($value) && is_a($value, self::BIG_DECIMAL)) {
|
||||
return (string) $value;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
private static function toInt(mixed $value, string $context): int
|
||||
{
|
||||
if (is_int($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (is_bool($value)) {
|
||||
return $value ? 1 : 0;
|
||||
}
|
||||
|
||||
if (is_float($value)) {
|
||||
return (int) $value;
|
||||
}
|
||||
|
||||
if (is_string($value) && self::isNumericString($value)) {
|
||||
return (int) $value;
|
||||
}
|
||||
|
||||
throw self::refusal($context, $value, 'int', 'not an integer, numeric string or bool');
|
||||
}
|
||||
|
||||
private static function toFloat(mixed $value, string $context): float
|
||||
{
|
||||
if (is_float($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (is_bool($value)) {
|
||||
return $value ? 1.0 : 0.0;
|
||||
}
|
||||
|
||||
if (is_int($value)) {
|
||||
return (float) $value;
|
||||
}
|
||||
|
||||
if (is_string($value) && self::isNumericString($value)) {
|
||||
return (float) $value;
|
||||
}
|
||||
|
||||
throw self::refusal($context, $value, 'float', 'not a float, numeric string or bool');
|
||||
}
|
||||
|
||||
private static function toBool(mixed $value, string $context): bool
|
||||
{
|
||||
if (is_bool($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if ($value === 0 || $value === 1) {
|
||||
return $value === 1;
|
||||
}
|
||||
|
||||
if ($value === '0' || $value === '1') {
|
||||
return $value === '1';
|
||||
}
|
||||
|
||||
if (is_string($value)) {
|
||||
$normalized = strtolower($value);
|
||||
|
||||
if ($normalized === 'true') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($normalized === 'false') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
throw self::refusal($context, $value, 'bool', 'use true/false, 0/1 or "true"/"false"');
|
||||
}
|
||||
|
||||
private static function toString(mixed $value, string $context): string
|
||||
{
|
||||
if (is_string($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (is_scalar($value) || $value instanceof Stringable) {
|
||||
return (string) $value;
|
||||
}
|
||||
|
||||
throw self::refusal($context, $value, 'string', 'not a scalar or Stringable');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<mixed>
|
||||
*/
|
||||
private static function toArray(mixed $value, string $context): array
|
||||
{
|
||||
if (is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (is_string($value)) {
|
||||
$decoded = json_decode($value, true);
|
||||
|
||||
if (is_array($decoded)) {
|
||||
return $decoded;
|
||||
}
|
||||
}
|
||||
|
||||
throw self::refusal(
|
||||
$context,
|
||||
$value,
|
||||
'array',
|
||||
'not an array or a JSON object/array string',
|
||||
);
|
||||
}
|
||||
|
||||
private static function toDateTime(mixed $value, string $context): DateTimeImmutable
|
||||
{
|
||||
if ($value instanceof DateTimeImmutable) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if ($value instanceof DateTimeInterface) {
|
||||
return DateTimeImmutable::createFromInterface($value);
|
||||
}
|
||||
|
||||
if (is_string($value) && $value !== '') {
|
||||
try {
|
||||
return new DateTimeImmutable($value);
|
||||
} catch (\Exception) {
|
||||
throw self::refusal(
|
||||
$context,
|
||||
$value,
|
||||
DateTimeImmutable::class,
|
||||
'not a valid date string',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
throw self::refusal(
|
||||
$context,
|
||||
$value,
|
||||
DateTimeImmutable::class,
|
||||
'not a date or date string',
|
||||
);
|
||||
}
|
||||
|
||||
private static function toBigDecimal(mixed $value, string $context): mixed
|
||||
{
|
||||
$class = self::BIG_DECIMAL;
|
||||
|
||||
if ($value instanceof $class) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (is_int($value) || is_float($value)) {
|
||||
return $class::of((string) $value);
|
||||
}
|
||||
|
||||
if (is_string($value) && self::isNumericString($value)) {
|
||||
return $class::of($value);
|
||||
}
|
||||
|
||||
throw self::refusal($context, $value, self::BIG_DECIMAL, 'not numeric');
|
||||
}
|
||||
|
||||
private static function isNumericString(string $value): bool
|
||||
{
|
||||
return $value !== '' && is_numeric($value);
|
||||
}
|
||||
|
||||
private static function refusal(
|
||||
string $context,
|
||||
mixed $value,
|
||||
string $type,
|
||||
string $reason,
|
||||
): \InvalidArgumentException {
|
||||
$field = $context === '' ? 'value' : $context;
|
||||
|
||||
return new \InvalidArgumentException(sprintf(
|
||||
'Cannot cast %s to %s: %s (received %s).',
|
||||
$field,
|
||||
$type,
|
||||
$reason,
|
||||
self::describe($value),
|
||||
));
|
||||
}
|
||||
|
||||
private static function describe(mixed $value): string
|
||||
{
|
||||
if (is_object($value)) {
|
||||
return $value::class;
|
||||
}
|
||||
|
||||
if (is_array($value)) {
|
||||
return 'array';
|
||||
}
|
||||
|
||||
if (is_string($value)) {
|
||||
return '"' . (strlen($value) > 40 ? substr($value, 0, 40) . '...' : $value) . '"';
|
||||
}
|
||||
|
||||
return var_export($value, true);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user