diff --git a/backend/app/Element/ElementRepository.php b/backend/app/Element/ElementRepository.php index b9ad71f..86631bd 100644 --- a/backend/app/Element/ElementRepository.php +++ b/backend/app/Element/ElementRepository.php @@ -2,8 +2,13 @@ namespace App\Element; +use DomainException; + interface ElementRepository { + /** + * @throws DomainException + */ public function create(CreateElementDto $dto): Element; public function find(int $id): ?Element; diff --git a/backend/app/Element/EloquentElementRepository.php b/backend/app/Element/EloquentElementRepository.php index a1a2709..3b8bc7b 100644 --- a/backend/app/Element/EloquentElementRepository.php +++ b/backend/app/Element/EloquentElementRepository.php @@ -4,6 +4,7 @@ namespace App\Element; use App\Set\Set; use App\Set\SetRepository; +use DomainException; use RuntimeException; class EloquentElementRepository implements ElementRepository @@ -14,6 +15,7 @@ class EloquentElementRepository implements ElementRepository public function create(CreateElementDto $dto): Element { + $this->validateParentSet($dto); $position = $this->nextPosition( $dto->set, $dto->parentElement, @@ -43,6 +45,23 @@ class EloquentElementRepository implements ElementRepository return $model === null ? null : $this->toDomain($model); } + /** + * @throws DomainException + */ + private function validateParentSet(CreateElementDto $dto): void + { + $parentElement = $dto->parentElement; + if ($parentElement === null) { + return; + } + + if ($parentElement->getSet()->getId() !== $dto->set->getId()) { + throw new DomainException( + 'parent element must belong to the same set', + ); + } + } + private function nextPosition( Set $set, ?Element $parentElement, diff --git a/backend/tests/Fakes/FakeElementRepository.php b/backend/tests/Fakes/FakeElementRepository.php index 4746bf3..ebe197d 100644 --- a/backend/tests/Fakes/FakeElementRepository.php +++ b/backend/tests/Fakes/FakeElementRepository.php @@ -5,6 +5,7 @@ namespace Tests\Fakes; use App\Element\CreateElementDto; use App\Element\Element; use App\Element\ElementRepository; +use DomainException; class FakeElementRepository implements ElementRepository { @@ -15,6 +16,7 @@ class FakeElementRepository implements ElementRepository public function create(CreateElementDto $dto): Element { + $this->validateParentSet($dto); $id = count($this->elements) + 1; $element = new Element( id: $id, @@ -36,6 +38,23 @@ class FakeElementRepository implements ElementRepository return $element === null ? null : $this->copy($element); } + /** + * @throws DomainException + */ + private function validateParentSet(CreateElementDto $dto): void + { + $parentElement = $dto->parentElement; + if ($parentElement === null) { + return; + } + + if ($parentElement->getSet()->getId() !== $dto->set->getId()) { + throw new DomainException( + 'parent element must belong to the same set', + ); + } + } + private function nextPosition(CreateElementDto $dto): int { $requestedParentId = $dto->parentElement?->getId();