add set elements

This commit is contained in:
Yisroel Baum 2026-05-24 22:32:46 +03:00
parent db35a97910
commit 2c4cdabc15
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9
17 changed files with 497 additions and 0 deletions

View file

@ -0,0 +1,84 @@
<?php
namespace App\Element\UseCases\CreateElement;
use App\Element\CreateElementDto;
use App\Element\Element;
use App\Element\ElementRepository;
use App\Exceptions\BadRequestException;
use App\Set\SetRepository;
use DomainException;
class CreateElement
{
public function __construct(
private ElementRepository $elementRepo,
private SetRepository $setRepo,
) {}
/**
* @throws BadRequestException
* @throws DomainException
*/
public function execute(CreateElementRequest $request): Element
{
if ($request->setId === null) {
throw new BadRequestException('setId is required');
}
if ($request->title === null || $request->title === '') {
throw new BadRequestException('title is required');
}
$set = $this->setRepo->find($request->setId);
if ($set === null) {
throw new DomainException(
"Set with id: {$request->setId} doesnt exist"
);
}
if ($request->parentElementId === null) {
$this->validateNoRootElementExists($request->setId);
return $this->elementRepo->create(new CreateElementDto(
set: $set,
title: $request->title,
parentElement: null,
));
}
$parentElement = $this->elementRepo->find(
$request->parentElementId
);
if ($parentElement === null) {
throw new DomainException(
"Element with id: {$request->parentElementId} doesnt exist"
);
}
if ($parentElement->getSet()->getId() !== $set->getId()) {
throw new DomainException(
'Parent element must belong to the same set'
);
}
return $this->elementRepo->create(new CreateElementDto(
set: $set,
title: $request->title,
parentElement: $parentElement,
));
}
/**
* @throws DomainException
*/
private function validateNoRootElementExists(int $setId): void
{
$elements = $this->elementRepo->findBySetId($setId);
foreach ($elements as $element) {
if ($element->getParentElement() === null) {
throw new DomainException(
'A root element already exists for this set'
);
}
}
}
}

View file

@ -0,0 +1,12 @@
<?php
namespace App\Element\UseCases\CreateElement;
class CreateElementRequest
{
public function __construct(
public ?int $setId,
public ?string $title,
public ?int $parentElementId,
) {}
}