add element persistence

This commit is contained in:
Yisroel Baum 2026-08-08 22:21:25 +03:00
parent aaab0e5379
commit fcc6ade8f3
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9
7 changed files with 289 additions and 0 deletions

View file

@ -0,0 +1,98 @@
<?php
namespace App\Element;
use App\Set\Set;
use App\Set\SetRepository;
use RuntimeException;
class EloquentElementRepository implements ElementRepository
{
public function __construct(
private SetRepository $setRepository,
) {}
public function create(CreateElementDto $dto): Element
{
$position = $this->nextPosition(
$dto->set,
$dto->parentElement,
);
$model = ElementModel::create([
'set_id' => $dto->set->getId(),
'name' => $dto->name,
'kind' => $dto->kind,
'parent_element_id' => $dto->parentElement?->getId(),
'position' => $position,
]);
return new Element(
id: $model->id,
name: $model->name,
kind: $model->kind,
set: $dto->set,
parentElement: $dto->parentElement,
position: $model->position,
);
}
public function find(int $id): ?Element
{
$model = ElementModel::find($id);
return $model === null ? null : $this->toDomain($model);
}
private function nextPosition(
Set $set,
?Element $parentElement,
): int {
$query = ElementModel::query()
->where('set_id', $set->getId());
if ($parentElement === null) {
$query->whereNull('parent_element_id');
} else {
$query->where('parent_element_id', $parentElement->getId());
}
$currentMaximum = $query->max('position');
if ($currentMaximum === null) {
return 1;
}
return (int) $currentMaximum + 1;
}
private function toDomain(ElementModel $model): Element
{
$set = $this->findSet($model->set_id);
$parentElement = null;
if ($model->parent_element_id !== null) {
$parentElement = $this->find($model->parent_element_id);
if ($parentElement === null) {
throw new RuntimeException('element parent not found');
}
}
return new Element(
id: $model->id,
name: $model->name,
kind: $model->kind,
set: $set,
parentElement: $parentElement,
position: $model->position,
);
}
private function findSet(int $id): Set
{
foreach ($this->setRepository->all() as $set) {
if ($set->getId() === $id) {
return $set;
}
}
throw new RuntimeException('element set not found');
}
}