initial commit
This commit is contained in:
commit
3f64f4a49a
221 files changed
+26665
No files matched your search
@@ -0,0 +1,732 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Database\Model;
|
||||
|
||||
use JsonSerializable;
|
||||
use Rsgrinko\Proton\Database\Connection;
|
||||
use Rsgrinko\Proton\Database\Model\Relations\BelongsTo;
|
||||
use Rsgrinko\Proton\Database\Model\Relations\BelongsToMany;
|
||||
use Rsgrinko\Proton\Database\Model\Relations\HasMany;
|
||||
use Rsgrinko\Proton\Database\Model\Relations\HasOne;
|
||||
use Rsgrinko\Proton\Database\Model\Relations\Relation;
|
||||
use Rsgrinko\Proton\Support\ProtonException;
|
||||
use Rsgrinko\Proton\Support\Str;
|
||||
|
||||
/**
|
||||
* Модель: строка таблицы как объект (Active Record).
|
||||
*
|
||||
* class User extends Model
|
||||
* {
|
||||
* protected static string $table = 'users';
|
||||
* protected array $fillable = ['login', 'email', 'name'];
|
||||
* protected array $casts = ['active' => 'bool', 'settings' => 'json'];
|
||||
*
|
||||
* public function posts(): HasMany
|
||||
* {
|
||||
* return $this->hasMany(Post::class);
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* $user = User::where('login', 'ivan')->first();
|
||||
* $user->name = 'Иван';
|
||||
* $user->save();
|
||||
*
|
||||
* Имя таблицы можно не задавать — оно берётся из имени класса (User -> users).
|
||||
* Отметки created_at/updated_at проставляются сами, если в таблице есть такие
|
||||
* колонки; мягкое удаление включается свойством $softDelete.
|
||||
*
|
||||
* Массовое присвоение работает по «белому списку» $fillable: без него форма,
|
||||
* в которую дописали лишнее поле, меняла бы что угодно, вплоть до role_id.
|
||||
*/
|
||||
abstract class Model implements JsonSerializable
|
||||
{
|
||||
public const CREATED_AT = 'created_at';
|
||||
public const UPDATED_AT = 'updated_at';
|
||||
public const DELETED_AT = 'deleted_at';
|
||||
|
||||
/** Имя таблицы; пусто — считается по имени класса */
|
||||
protected static string $table = '';
|
||||
|
||||
/** Первичный ключ */
|
||||
protected static string $primaryKey = 'id';
|
||||
|
||||
/** Проставлять ли created_at и updated_at */
|
||||
protected bool $timestamps = true;
|
||||
|
||||
/** Мягкое удаление: запись остаётся, но помечается deleted_at */
|
||||
protected bool $softDelete = false;
|
||||
|
||||
/** @var array<int, string> Поля, которые можно заполнять массово */
|
||||
protected array $fillable = [];
|
||||
|
||||
/** @var array<int, string> Поля, которые нельзя показывать наружу (toArray, JSON) */
|
||||
protected array $hidden = [];
|
||||
|
||||
/** @var array<string, string> Приведение типов: int, float, bool, json, datetime */
|
||||
protected array $casts = [];
|
||||
|
||||
/** @var array<string, mixed> Значения колонок */
|
||||
protected array $attributes = [];
|
||||
|
||||
/** @var array<string, mixed> Значения, прочитанные из базы, — по ним видно, что изменилось */
|
||||
protected array $original = [];
|
||||
|
||||
/** @var array<string, mixed> Загруженные связи */
|
||||
protected array $loaded = [];
|
||||
|
||||
/** Запись уже есть в базе */
|
||||
protected bool $exists = false;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
public function __construct(array $attributes = [])
|
||||
{
|
||||
$this->fill($attributes);
|
||||
}
|
||||
|
||||
// --- Настройки модели ----------------------------------------------------
|
||||
|
||||
/**
|
||||
* Имя таблицы: задано свойством или посчитано по имени класса.
|
||||
*/
|
||||
public function table(): string
|
||||
{
|
||||
if (static::$table !== '') {
|
||||
return static::$table;
|
||||
}
|
||||
|
||||
$short = substr(strrchr(static::class, '\\') ?: static::class, 1);
|
||||
|
||||
return Str::plural(Str::snake($short));
|
||||
}
|
||||
|
||||
public function keyName(): string
|
||||
{
|
||||
return static::$primaryKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Значение первичного ключа.
|
||||
*/
|
||||
public function key(): mixed
|
||||
{
|
||||
return $this->attributes[static::$primaryKey] ?? null;
|
||||
}
|
||||
|
||||
public function id(): int
|
||||
{
|
||||
return (int) $this->key();
|
||||
}
|
||||
|
||||
public function connection(): Connection
|
||||
{
|
||||
return Connection::instance();
|
||||
}
|
||||
|
||||
public function hasTimestamps(): bool
|
||||
{
|
||||
return $this->timestamps;
|
||||
}
|
||||
|
||||
public function softDeletes(): bool
|
||||
{
|
||||
return $this->softDelete;
|
||||
}
|
||||
|
||||
public function existsInDatabase(): bool
|
||||
{
|
||||
return $this->exists;
|
||||
}
|
||||
|
||||
// --- Выборка -------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Построитель запросов этой модели.
|
||||
*/
|
||||
public static function query(): Query
|
||||
{
|
||||
return new Query(static::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, static>
|
||||
*/
|
||||
public static function all(): array
|
||||
{
|
||||
/** @var array<int, static> $models */
|
||||
$models = static::query()->get();
|
||||
|
||||
return $models;
|
||||
}
|
||||
|
||||
public static function find(int|string|null $id): ?static
|
||||
{
|
||||
if ($id === null || $id === '' || $id === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @var static|null $model */
|
||||
$model = static::query()->where(static::$primaryKey, $id)->first();
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Запись обязана быть — иначе исключение, которое ядро превратит в 404.
|
||||
*/
|
||||
public static function findOrFail(int|string|null $id): static
|
||||
{
|
||||
$model = static::find($id);
|
||||
|
||||
if ($model === null) {
|
||||
throw new RecordNotFound('Запись не найдена: ' . static::class . ' #' . (string) $id);
|
||||
}
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Условие прямо от класса: User::where('active', 1)->get().
|
||||
*/
|
||||
public static function where(string $column, mixed $operator = null, mixed $value = null): Query
|
||||
{
|
||||
if (func_num_args() === 2) {
|
||||
return static::query()->where($column, $operator);
|
||||
}
|
||||
|
||||
return static::query()->where($column, $operator, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Первая запись по условию — короткая запись для поиска по одному полю.
|
||||
*/
|
||||
public static function findBy(string $column, mixed $value): ?static
|
||||
{
|
||||
/** @var static|null $model */
|
||||
$model = static::query()->where($column, $value)->first();
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Создать и сразу сохранить.
|
||||
*
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
public static function create(array $attributes): static
|
||||
{
|
||||
$model = new static($attributes);
|
||||
|
||||
$model->save();
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Найти по условию или создать новую запись.
|
||||
*
|
||||
* @param array<string, mixed> $search
|
||||
* @param array<string, mixed> $values
|
||||
*/
|
||||
public static function firstOrCreate(array $search, array $values = []): static
|
||||
{
|
||||
$query = static::query();
|
||||
|
||||
foreach ($search as $column => $value) {
|
||||
$query->where($column, $value);
|
||||
}
|
||||
|
||||
/** @var static|null $found */
|
||||
$found = $query->first();
|
||||
|
||||
if ($found !== null) {
|
||||
return $found;
|
||||
}
|
||||
|
||||
return static::create(array_merge($search, $values));
|
||||
}
|
||||
|
||||
/**
|
||||
* Модель из готовой строки базы. Значения считаются сохранёнными.
|
||||
*
|
||||
* @param array<string, mixed> $row
|
||||
*/
|
||||
public static function fromRow(array $row): static
|
||||
{
|
||||
$model = new static();
|
||||
|
||||
$model->attributes = $row;
|
||||
$model->original = $row;
|
||||
$model->exists = true;
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
// --- Запись --------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Заполняет разрешённые поля.
|
||||
*
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
public function fill(array $attributes): static
|
||||
{
|
||||
foreach ($attributes as $key => $value) {
|
||||
if ($this->fillable === [] || in_array($key, $this->fillable, true)) {
|
||||
$this->setAttribute((string) $key, $value);
|
||||
}
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Заполняет что угодно, минуя белый список. Только для своего кода —
|
||||
* данные из запроса сюда пускать нельзя.
|
||||
*
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
public function forceFill(array $attributes): static
|
||||
{
|
||||
foreach ($attributes as $key => $value) {
|
||||
$this->setAttribute((string) $key, $value);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сохраняет: вставляет новую запись или обновляет изменённые поля.
|
||||
*/
|
||||
public function save(): bool
|
||||
{
|
||||
$now = date('Y-m-d H:i:s');
|
||||
|
||||
if ($this->exists) {
|
||||
$changes = $this->changes();
|
||||
|
||||
if ($changes === []) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($this->timestamps && $this->hasColumn(self::UPDATED_AT)) {
|
||||
$changes[self::UPDATED_AT] = $this->attributes[self::UPDATED_AT] = $now;
|
||||
}
|
||||
|
||||
$this->connection()->update($this->table(), $changes, [static::$primaryKey => $this->key()]);
|
||||
|
||||
$this->original = $this->attributes;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($this->timestamps) {
|
||||
foreach ([self::CREATED_AT, self::UPDATED_AT] as $column) {
|
||||
if (!isset($this->attributes[$column]) && $this->hasColumn($column)) {
|
||||
$this->attributes[$column] = $now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$id = $this->connection()->insert($this->table(), $this->forStorage($this->attributes));
|
||||
|
||||
if ($id > 0 && !isset($this->attributes[static::$primaryKey])) {
|
||||
$this->attributes[static::$primaryKey] = $id;
|
||||
}
|
||||
|
||||
$this->original = $this->attributes;
|
||||
$this->exists = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновить поля и сразу сохранить.
|
||||
*
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
public function update(array $attributes): bool
|
||||
{
|
||||
return $this->fill($attributes)->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Удалить. При включённом мягком удалении запись остаётся с отметкой времени.
|
||||
*/
|
||||
public function delete(): bool
|
||||
{
|
||||
if (!$this->exists) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->softDelete) {
|
||||
$this->attributes[self::DELETED_AT] = date('Y-m-d H:i:s');
|
||||
|
||||
$this->connection()->update(
|
||||
$this->table(),
|
||||
[self::DELETED_AT => $this->attributes[self::DELETED_AT]],
|
||||
[static::$primaryKey => $this->key()]
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->connection()->delete($this->table(), [static::$primaryKey => $this->key()]);
|
||||
|
||||
$this->exists = false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Удалить насовсем, даже если включено мягкое удаление.
|
||||
*/
|
||||
public function forceDelete(): bool
|
||||
{
|
||||
if (!$this->exists) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->connection()->delete($this->table(), [static::$primaryKey => $this->key()]);
|
||||
|
||||
$this->exists = false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Вернуть мягко удалённую запись.
|
||||
*/
|
||||
public function restore(): bool
|
||||
{
|
||||
if (!$this->softDelete) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->attributes[self::DELETED_AT] = null;
|
||||
|
||||
$this->connection()->update(
|
||||
$this->table(),
|
||||
[self::DELETED_AT => null],
|
||||
[static::$primaryKey => $this->key()]
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function trashed(): bool
|
||||
{
|
||||
return $this->softDelete && ($this->attributes[self::DELETED_AT] ?? null) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Перечитать запись из базы.
|
||||
*/
|
||||
public function refresh(): static
|
||||
{
|
||||
$fresh = static::find($this->key());
|
||||
|
||||
if ($fresh !== null) {
|
||||
$this->attributes = $fresh->attributes;
|
||||
$this->original = $fresh->attributes;
|
||||
$this->loaded = [];
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Что изменилось после чтения из базы.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function changes(): array
|
||||
{
|
||||
$changes = [];
|
||||
|
||||
foreach ($this->attributes as $key => $value) {
|
||||
if (!array_key_exists($key, $this->original) || $this->original[$key] !== $value) {
|
||||
$changes[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
// Ключ не меняем никогда: править первичный ключ через save() нельзя
|
||||
unset($changes[static::$primaryKey]);
|
||||
|
||||
return $this->forStorage($changes);
|
||||
}
|
||||
|
||||
public function isDirty(): bool
|
||||
{
|
||||
return $this->changes() !== [];
|
||||
}
|
||||
|
||||
// --- Связи ---------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Много записей чужой таблицы ссылаются на нас.
|
||||
*
|
||||
* @param class-string<Model> $related
|
||||
*/
|
||||
public function hasMany(string $related, ?string $foreignKey = null, ?string $localKey = null): HasMany
|
||||
{
|
||||
return new HasMany($this, $related, $foreignKey ?? $this->foreignKeyName(), $localKey ?? static::$primaryKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Одна чужая запись ссылается на нас.
|
||||
*
|
||||
* @param class-string<Model> $related
|
||||
*/
|
||||
public function hasOne(string $related, ?string $foreignKey = null, ?string $localKey = null): HasOne
|
||||
{
|
||||
return new HasOne($this, $related, $foreignKey ?? $this->foreignKeyName(), $localKey ?? static::$primaryKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Мы ссылаемся на чужую запись.
|
||||
*
|
||||
* @param class-string<Model> $related
|
||||
*/
|
||||
public function belongsTo(string $related, ?string $foreignKey = null, ?string $ownerKey = null): BelongsTo
|
||||
{
|
||||
$instance = new $related();
|
||||
|
||||
return new BelongsTo(
|
||||
$this,
|
||||
$related,
|
||||
$foreignKey ?? $instance->foreignKeyName(),
|
||||
$ownerKey ?? $instance->keyName()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Многие ко многим через таблицу-связку.
|
||||
*
|
||||
* @param class-string<Model> $related
|
||||
*/
|
||||
public function belongsToMany(
|
||||
string $related,
|
||||
?string $pivot = null,
|
||||
?string $foreignKey = null,
|
||||
?string $relatedKey = null
|
||||
): BelongsToMany {
|
||||
$instance = new $related();
|
||||
|
||||
// Имя связки по умолчанию — обе таблицы через подчёркивание по алфавиту
|
||||
if ($pivot === null) {
|
||||
$tables = [$this->table(), $instance->table()];
|
||||
|
||||
sort($tables);
|
||||
|
||||
$pivot = implode('_', $tables);
|
||||
}
|
||||
|
||||
return new BelongsToMany(
|
||||
$this,
|
||||
$related,
|
||||
$pivot,
|
||||
$foreignKey ?? $this->foreignKeyName(),
|
||||
$relatedKey ?? $instance->foreignKeyName()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Имя внешнего ключа на эту модель: User -> user_id.
|
||||
*/
|
||||
public function foreignKeyName(): string
|
||||
{
|
||||
$short = substr(strrchr(static::class, '\\') ?: static::class, 1);
|
||||
|
||||
return Str::snake($short) . '_id';
|
||||
}
|
||||
|
||||
/**
|
||||
* Объект связи по имени метода — нужен подгрузке через with().
|
||||
*/
|
||||
public function relation(string $name): Relation
|
||||
{
|
||||
if (!method_exists($this, $name)) {
|
||||
throw new ProtonException('У модели ' . static::class . ' нет связи «' . $name . '»');
|
||||
}
|
||||
|
||||
$relation = $this->{$name}();
|
||||
|
||||
if (!$relation instanceof Relation) {
|
||||
throw new ProtonException('Метод ' . $name . '() модели ' . static::class . ' не возвращает связь');
|
||||
}
|
||||
|
||||
return $relation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Кладёт готовое значение связи — так работает подгрузка через with().
|
||||
*/
|
||||
public function setRelation(string $name, mixed $value): void
|
||||
{
|
||||
$this->loaded[$name] = $value;
|
||||
}
|
||||
|
||||
public function relationLoaded(string $name): bool
|
||||
{
|
||||
return array_key_exists($name, $this->loaded);
|
||||
}
|
||||
|
||||
// --- Доступ к значениям --------------------------------------------------
|
||||
|
||||
public function __get(string $name): mixed
|
||||
{
|
||||
if (array_key_exists($name, $this->loaded)) {
|
||||
return $this->loaded[$name];
|
||||
}
|
||||
|
||||
if (array_key_exists($name, $this->attributes)) {
|
||||
return $this->castValue($name, $this->attributes[$name]);
|
||||
}
|
||||
|
||||
// Связь, объявленная методом: $user->posts вернёт результат, $user->posts() — саму связь
|
||||
if (method_exists($this, $name)) {
|
||||
$relation = $this->{$name}();
|
||||
|
||||
if ($relation instanceof Relation) {
|
||||
return $this->loaded[$name] = $relation->result();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function __set(string $name, mixed $value): void
|
||||
{
|
||||
$this->setAttribute($name, $value);
|
||||
}
|
||||
|
||||
public function __isset(string $name): bool
|
||||
{
|
||||
return isset($this->attributes[$name]) || isset($this->loaded[$name]);
|
||||
}
|
||||
|
||||
public function setAttribute(string $name, mixed $value): void
|
||||
{
|
||||
$this->attributes[$name] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Значение как оно лежит в базе, без приведения типов.
|
||||
*/
|
||||
public function raw(string $name): mixed
|
||||
{
|
||||
return $this->attributes[$name] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Все значения как массив — с приведением типов и без скрытых полей.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach ($this->attributes as $key => $value) {
|
||||
if (in_array($key, $this->hidden, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$result[$key] = $this->castValue((string) $key, $value);
|
||||
}
|
||||
|
||||
foreach ($this->loaded as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
$result[$key] = array_map(
|
||||
static fn (mixed $item): mixed => $item instanceof self ? $item->toArray() : $item,
|
||||
$value
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$result[$key] = $value instanceof self ? $value->toArray() : $value;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
return $this->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Приведение значения по объявленному типу.
|
||||
*/
|
||||
protected function castValue(string $name, mixed $value): mixed
|
||||
{
|
||||
$type = $this->casts[$name] ?? null;
|
||||
|
||||
if ($type === null || $value === null) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
return match ($type) {
|
||||
'int', 'integer' => (int) $value,
|
||||
'float', 'double' => (float) $value,
|
||||
'bool', 'boolean' => (bool) $value && $value !== '0',
|
||||
'json', 'array' => is_array($value) ? $value : (json_decode((string) $value, true) ?? []),
|
||||
'datetime' => is_string($value) ? $value : (string) $value,
|
||||
default => $value,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Готовит значения к записи: массивы и объекты уезжают в базу как JSON,
|
||||
* булево — числом. Иначе PDO спотыкается о тип, которого не знает.
|
||||
*
|
||||
* @param array<string, mixed> $values
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function forStorage(array $values): array
|
||||
{
|
||||
foreach ($values as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
$values[$key] = (string) json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_bool($value)) {
|
||||
$values[$key] = (int) $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Есть ли колонка в таблице. Ответ на процесс один: спрашивать схему на
|
||||
* каждое сохранение незачем.
|
||||
*/
|
||||
protected function hasColumn(string $column): bool
|
||||
{
|
||||
static $columns = [];
|
||||
|
||||
$table = $this->table();
|
||||
|
||||
if (!isset($columns[$table])) {
|
||||
$columns[$table] = [];
|
||||
}
|
||||
|
||||
if (!array_key_exists($column, $columns[$table])) {
|
||||
$columns[$table][$column] = $this->connection()->hasColumn($table, $column);
|
||||
}
|
||||
|
||||
return $columns[$table][$column];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Database\Model;
|
||||
|
||||
use Rsgrinko\Proton\Database\Query\Builder;
|
||||
|
||||
/**
|
||||
* Построитель запросов, который отдаёт не массивы, а модели.
|
||||
*
|
||||
* Всё, что умеет обычный Builder (where, join, orderBy, paginate), работает и здесь —
|
||||
* различие только в том, что приходит на выходе. Отдельный класс, а не флаг в
|
||||
* построителе: возвращаемый тип должен быть понятен по коду, а не по настройке.
|
||||
*/
|
||||
final class Query extends Builder
|
||||
{
|
||||
/** @var class-string<Model> */
|
||||
private string $model;
|
||||
|
||||
/** @var array<int, string> Связи, которые нужно подгрузить сразу */
|
||||
private array $with = [];
|
||||
|
||||
/** Показывать ли мягко удалённые записи */
|
||||
private bool $withTrashed = false;
|
||||
|
||||
/** Только мягко удалённые */
|
||||
private bool $onlyTrashed = false;
|
||||
|
||||
/**
|
||||
* @param class-string<Model> $model
|
||||
*/
|
||||
public function __construct(string $model)
|
||||
{
|
||||
$instance = new $model();
|
||||
|
||||
parent::__construct($instance->connection(), $instance->table());
|
||||
|
||||
$this->model = $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Подгрузить связи одним запросом на связь, а не по запросу на строку.
|
||||
*/
|
||||
public function with(string ...$relations): self
|
||||
{
|
||||
foreach ($relations as $relation) {
|
||||
$this->with[] = $relation;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Вместе с мягко удалёнными.
|
||||
*/
|
||||
public function withTrashed(bool $with = true): self
|
||||
{
|
||||
$this->withTrashed = $with;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Только мягко удалённые — корзина.
|
||||
*/
|
||||
public function onlyTrashed(): self
|
||||
{
|
||||
$this->onlyTrashed = true;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Модели по запросу.
|
||||
*
|
||||
* @return array<int, Model>
|
||||
*/
|
||||
public function get(): array
|
||||
{
|
||||
$this->applyTrashed();
|
||||
|
||||
$models = [];
|
||||
|
||||
foreach (parent::get() as $row) {
|
||||
$models[] = ($this->model)::fromRow($row);
|
||||
}
|
||||
|
||||
if ($models !== [] && $this->with !== []) {
|
||||
$this->loadRelations($models);
|
||||
}
|
||||
|
||||
return $models;
|
||||
}
|
||||
|
||||
/**
|
||||
* Строки как есть, без превращения в модели — нужно агрегатам и pluck.
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function rows(): array
|
||||
{
|
||||
$this->applyTrashed();
|
||||
|
||||
return parent::get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Первая модель или null.
|
||||
*/
|
||||
public function first(): ?Model
|
||||
{
|
||||
$models = (clone $this)->limit(1)->get();
|
||||
|
||||
return $models[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Первая модель или исключение — когда запись обязана быть.
|
||||
*/
|
||||
public function firstOrFail(): Model
|
||||
{
|
||||
$model = $this->first();
|
||||
|
||||
if ($model === null) {
|
||||
throw new RecordNotFound('Запись не найдена: ' . $this->model);
|
||||
}
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Одно значение — берём из сырой строки, модель тут не нужна.
|
||||
*/
|
||||
public function value(string $column): mixed
|
||||
{
|
||||
$row = (clone $this)->select($column)->limit(1)->rows()[0] ?? null;
|
||||
|
||||
if ($row === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return reset($row);
|
||||
}
|
||||
|
||||
public function count(string $column = '*'): int
|
||||
{
|
||||
$this->applyTrashed();
|
||||
|
||||
return parent::count($column);
|
||||
}
|
||||
|
||||
/**
|
||||
* Страница моделей.
|
||||
*
|
||||
* @return array{items: array<int, Model>, total: int, page: int, pages: int, per_page: int}
|
||||
*/
|
||||
public function paginate(int $page = 1, int $perPage = 30): array
|
||||
{
|
||||
$total = $this->count();
|
||||
$pages = max(1, (int) ceil($total / max(1, $perPage)));
|
||||
$page = max(1, min($page, $pages));
|
||||
|
||||
return [
|
||||
'items' => (clone $this)->limit($perPage)->offset(($page - 1) * $perPage)->get(),
|
||||
'total' => $total,
|
||||
'page' => $page,
|
||||
'pages' => $pages,
|
||||
'per_page' => $perPage,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновление через модель проставляет отметку времени — иначе updated_at
|
||||
* молча отстаёт от данных.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public function update(array $data): int
|
||||
{
|
||||
$model = new ($this->model)();
|
||||
|
||||
if ($model->hasTimestamps() && !array_key_exists('updated_at', $data)) {
|
||||
$data['updated_at'] = date('Y-m-d H:i:s');
|
||||
}
|
||||
|
||||
$this->applyTrashed();
|
||||
|
||||
return parent::update($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Мягкое удаление, если модель его поддерживает, иначе обычное.
|
||||
*/
|
||||
public function delete(): int
|
||||
{
|
||||
$model = new ($this->model)();
|
||||
|
||||
if ($model->softDeletes()) {
|
||||
return parent::update([Model::DELETED_AT => date('Y-m-d H:i:s')]);
|
||||
}
|
||||
|
||||
return parent::delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Настоящее удаление, даже если включено мягкое.
|
||||
*/
|
||||
public function forceDelete(): int
|
||||
{
|
||||
return parent::delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Условие по мягкому удалению добавляется один раз и перед самым запросом:
|
||||
* до этого момента ещё может прийти withTrashed().
|
||||
*/
|
||||
private function applyTrashed(): void
|
||||
{
|
||||
static $applied = false;
|
||||
|
||||
$model = new ($this->model)();
|
||||
|
||||
if (!$model->softDeletes() || $this->withTrashed) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Повторный вызов (count(), затем get()) не должен добавлять условие дважды
|
||||
foreach ($this->wheres as $where) {
|
||||
if (str_contains($where['sql'], Model::DELETED_AT)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->onlyTrashed) {
|
||||
$this->whereNotNull(Model::DELETED_AT);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->whereNull(Model::DELETED_AT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Подгружает объявленные связи: один запрос на связь.
|
||||
*
|
||||
* @param array<int, Model> $models
|
||||
*/
|
||||
private function loadRelations(array $models): void
|
||||
{
|
||||
foreach ($this->with as $name) {
|
||||
$relation = $models[0]->relation($name);
|
||||
|
||||
$relation->load($name, $models);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Database\Model;
|
||||
|
||||
use Rsgrinko\Proton\Support\ProtonException;
|
||||
|
||||
/**
|
||||
* Записи нет. Ядро панели ловит это исключение и возвращает человека в список
|
||||
* с сообщением, API отвечает 404 — проверять «а вдруг null» в каждом контроллере
|
||||
* не нужно.
|
||||
*/
|
||||
final class RecordNotFound extends ProtonException
|
||||
{
|
||||
/** Куда вернуть человека — имя маршрута списка */
|
||||
private string $route;
|
||||
|
||||
public function __construct(string $message = 'Запись не найдена', string $route = '')
|
||||
{
|
||||
parent::__construct($message, [], 404);
|
||||
|
||||
$this->route = $route;
|
||||
}
|
||||
|
||||
public function route(): string
|
||||
{
|
||||
return $this->route;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Database\Model\Relations;
|
||||
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
|
||||
/**
|
||||
* «Мой хозяин»: внешний ключ лежит у нас. У заметки есть автор —
|
||||
* $note->belongsTo(User::class) по note.user_id.
|
||||
*/
|
||||
final class BelongsTo extends Relation
|
||||
{
|
||||
public function result(): ?Model
|
||||
{
|
||||
$key = $this->parent->raw($this->foreignKey);
|
||||
|
||||
if ($key === null || $key === '' || $key === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->query()->where($this->localKey, $key)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, Model> $models
|
||||
*/
|
||||
public function load(string $name, array $models): void
|
||||
{
|
||||
$keys = $this->keys($models, $this->foreignKey);
|
||||
|
||||
if ($keys === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$owners = [];
|
||||
|
||||
foreach ($this->query()->whereIn($this->localKey, $keys)->get() as $owner) {
|
||||
$owners[(string) $owner->raw($this->localKey)] = $owner;
|
||||
}
|
||||
|
||||
foreach ($models as $model) {
|
||||
$model->setRelation($name, $owners[(string) $model->raw($this->foreignKey)] ?? null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Database\Model\Relations;
|
||||
|
||||
use Rsgrinko\Proton\Database\Connection;
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
|
||||
/**
|
||||
* «Многие ко многим» через таблицу-связку: у роли много прав, у пользователя
|
||||
* много проектов. Сама связка — обычная таблица из двух ключей, своей модели
|
||||
* ей не нужно.
|
||||
*/
|
||||
final class BelongsToMany extends Relation
|
||||
{
|
||||
private string $pivot;
|
||||
|
||||
/** Колонка связки, указывающая на связанную модель */
|
||||
private string $relatedKey;
|
||||
|
||||
/**
|
||||
* @param class-string<Model> $related
|
||||
*/
|
||||
public function __construct(Model $parent, string $related, string $pivot, string $foreignKey, string $relatedKey)
|
||||
{
|
||||
parent::__construct($parent, $related, $foreignKey, $parent->keyName());
|
||||
|
||||
$this->pivot = $pivot;
|
||||
$this->relatedKey = $relatedKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, Model>
|
||||
*/
|
||||
public function result(): array
|
||||
{
|
||||
$key = $this->parent->raw($this->localKey);
|
||||
|
||||
if ($key === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$ids = $this->db()->table($this->pivot)
|
||||
->where($this->foreignKey, $key)
|
||||
->pluck($this->relatedKey);
|
||||
|
||||
if ($ids === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$instance = new ($this->related)();
|
||||
|
||||
return $this->query()->whereIn($instance->keyName(), array_values($ids))->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Привязать запись, если её ещё нет в связке.
|
||||
*/
|
||||
public function attach(int|string $id): void
|
||||
{
|
||||
$exists = $this->db()->table($this->pivot)
|
||||
->where($this->foreignKey, $this->parent->raw($this->localKey))
|
||||
->where($this->relatedKey, $id)
|
||||
->exists();
|
||||
|
||||
if ($exists) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->db()->insert($this->pivot, [
|
||||
$this->foreignKey => $this->parent->raw($this->localKey),
|
||||
$this->relatedKey => $id,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Отвязать запись.
|
||||
*/
|
||||
public function detach(int|string $id): void
|
||||
{
|
||||
$this->db()->delete($this->pivot, [
|
||||
$this->foreignKey => $this->parent->raw($this->localKey),
|
||||
$this->relatedKey => $id,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Оставить в связке ровно этот список: чего нет — добавить, лишнее — убрать.
|
||||
*
|
||||
* @param array<int, int|string> $ids
|
||||
*/
|
||||
public function sync(array $ids): void
|
||||
{
|
||||
$current = array_map(
|
||||
'strval',
|
||||
array_values($this->db()->table($this->pivot)
|
||||
->where($this->foreignKey, $this->parent->raw($this->localKey))
|
||||
->pluck($this->relatedKey))
|
||||
);
|
||||
|
||||
$wanted = array_map('strval', $ids);
|
||||
|
||||
foreach (array_diff($wanted, $current) as $id) {
|
||||
$this->attach($id);
|
||||
}
|
||||
|
||||
foreach (array_diff($current, $wanted) as $id) {
|
||||
$this->detach($id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, Model> $models
|
||||
*/
|
||||
public function load(string $name, array $models): void
|
||||
{
|
||||
$keys = $this->keys($models, $this->localKey);
|
||||
|
||||
if ($keys === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$links = $this->db()->table($this->pivot)
|
||||
->whereIn($this->foreignKey, $keys)
|
||||
->get();
|
||||
|
||||
if ($links === []) {
|
||||
foreach ($models as $model) {
|
||||
$model->setRelation($name, []);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$instance = new ($this->related)();
|
||||
$ids = array_values(array_unique(array_map(
|
||||
fn (array $row): mixed => $row[$this->relatedKey],
|
||||
$links
|
||||
)));
|
||||
|
||||
$related = [];
|
||||
|
||||
foreach ($this->query()->whereIn($instance->keyName(), $ids)->get() as $model) {
|
||||
$related[(string) $model->key()] = $model;
|
||||
}
|
||||
|
||||
$grouped = [];
|
||||
|
||||
foreach ($links as $link) {
|
||||
$target = $related[(string) $link[$this->relatedKey]] ?? null;
|
||||
|
||||
if ($target !== null) {
|
||||
$grouped[(string) $link[$this->foreignKey]][] = $target;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($models as $model) {
|
||||
$model->setRelation($name, $grouped[(string) $model->raw($this->localKey)] ?? []);
|
||||
}
|
||||
}
|
||||
|
||||
private function db(): Connection
|
||||
{
|
||||
return $this->parent->connection();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Database\Model\Relations;
|
||||
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
|
||||
/**
|
||||
* «Много моих»: чужие записи ссылаются на нас своим внешним ключом.
|
||||
* У пользователя — заметки: $user->hasMany(Note::class) по note.user_id.
|
||||
*/
|
||||
class HasMany extends Relation
|
||||
{
|
||||
/**
|
||||
* @return array<int, Model>
|
||||
*/
|
||||
public function result(): array
|
||||
{
|
||||
$key = $this->parent->raw($this->localKey);
|
||||
|
||||
if ($key === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->query()->where($this->foreignKey, $key)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Новая запись на этой стороне связи — внешний ключ проставляется сам.
|
||||
*
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
public function create(array $attributes): Model
|
||||
{
|
||||
$model = new ($this->related)($attributes);
|
||||
|
||||
$model->setAttribute($this->foreignKey, $this->parent->raw($this->localKey));
|
||||
$model->save();
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, Model> $models
|
||||
*/
|
||||
public function load(string $name, array $models): void
|
||||
{
|
||||
$keys = $this->keys($models, $this->localKey);
|
||||
|
||||
if ($keys === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$grouped = [];
|
||||
|
||||
foreach ($this->query()->whereIn($this->foreignKey, $keys)->get() as $related) {
|
||||
$grouped[(string) $related->raw($this->foreignKey)][] = $related;
|
||||
}
|
||||
|
||||
foreach ($models as $model) {
|
||||
$model->setRelation($name, $grouped[(string) $model->raw($this->localKey)] ?? []);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Database\Model\Relations;
|
||||
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
|
||||
/**
|
||||
* «Один мой»: то же, что HasMany, только запись ожидается одна —
|
||||
* профиль пользователя, настройки, последняя сессия.
|
||||
*/
|
||||
final class HasOne extends HasMany
|
||||
{
|
||||
public function result(): ?Model
|
||||
{
|
||||
$key = $this->parent->raw($this->localKey);
|
||||
|
||||
if ($key === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->query()->where($this->foreignKey, $key)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, Model> $models
|
||||
*/
|
||||
public function load(string $name, array $models): void
|
||||
{
|
||||
$keys = $this->keys($models, $this->localKey);
|
||||
|
||||
if ($keys === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$found = [];
|
||||
|
||||
foreach ($this->query()->whereIn($this->foreignKey, $keys)->get() as $related) {
|
||||
$found[(string) $related->raw($this->foreignKey)] ??= $related;
|
||||
}
|
||||
|
||||
foreach ($models as $model) {
|
||||
$model->setRelation($name, $found[(string) $model->raw($this->localKey)] ?? null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Database\Model\Relations;
|
||||
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
use Rsgrinko\Proton\Database\Model\Query;
|
||||
|
||||
/**
|
||||
* Связь между моделями.
|
||||
*
|
||||
* Умеет две вещи: достать результат для одной записи ($user->posts) и подгрузить
|
||||
* связь сразу для списка записей (Query::with('posts')) — одним запросом на связь,
|
||||
* а не по запросу на строку. Второе и есть причина, по которой связь оформлена
|
||||
* объектом, а не методом, возвращающим сразу данные.
|
||||
*/
|
||||
abstract class Relation
|
||||
{
|
||||
protected Model $parent;
|
||||
|
||||
/** @var class-string<Model> */
|
||||
protected string $related;
|
||||
|
||||
protected string $foreignKey;
|
||||
|
||||
protected string $localKey;
|
||||
|
||||
/**
|
||||
* @param class-string<Model> $related
|
||||
*/
|
||||
public function __construct(Model $parent, string $related, string $foreignKey, string $localKey)
|
||||
{
|
||||
$this->parent = $parent;
|
||||
$this->related = $related;
|
||||
$this->foreignKey = $foreignKey;
|
||||
$this->localKey = $localKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Построитель по связанной модели — на него можно навесить свои условия:
|
||||
* $user->posts()->where('published', 1)->get().
|
||||
*/
|
||||
public function query(): Query
|
||||
{
|
||||
return ($this->related)::query();
|
||||
}
|
||||
|
||||
/**
|
||||
* Результат связи для одной записи.
|
||||
*/
|
||||
abstract public function result(): mixed;
|
||||
|
||||
/**
|
||||
* Подгружает связь сразу для списка моделей.
|
||||
*
|
||||
* @param array<int, Model> $models
|
||||
*/
|
||||
abstract public function load(string $name, array $models): void;
|
||||
|
||||
/**
|
||||
* Собирает значения ключа у списка моделей — по ним и идёт один общий запрос.
|
||||
*
|
||||
* @param array<int, Model> $models
|
||||
*
|
||||
* @return array<int, mixed>
|
||||
*/
|
||||
protected function keys(array $models, string $column): array
|
||||
{
|
||||
$keys = [];
|
||||
|
||||
foreach ($models as $model) {
|
||||
$value = $model->raw($column);
|
||||
|
||||
if ($value !== null && !in_array($value, $keys, true)) {
|
||||
$keys[] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $keys;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user