$dto->set->getId(), 'title' => $dto->title, 'description' => $dto->description, 'rich_text' => $dto->richText, 'pdf_path' => $dto->pdfPath, 'youtube_url' => $dto->youtubeUrl, 'parent_element_id' => $dto->parentElement?->getId(), ]); return new Element( id: $model->id, title: $dto->title, description: $dto->description, richText: $dto->richText, pdfPath: $dto->pdfPath, youtubeUrl: $dto->youtubeUrl, set: $dto->set, parentElement: $dto->parentElement, ); } public function find(int $id): ?Element { $model = ElementModel::find($id); return $model === null ? null : $this->toDomain($model); } public function findRootBySet(DomainSet $set): ?Element { $model = ElementModel::where('set_id', $set->getId()) ->whereNull('parent_element_id') ->orderBy('id') ->first(); return $model === null ? null : $this->toDomain($model); } /** * @return Element[] */ public function findBySet(DomainSet $set): array { $models = ElementModel::where('set_id', $set->getId()) ->orderBy('id') ->get(); $elements = []; foreach ($models as $model) { $elements[] = $this->toDomain($model); } return $elements; } /** * @return Element[] */ public function findByParentElement(Element $parentElement): array { $models = ElementModel::where( 'parent_element_id', $parentElement->getId(), ) ->orderBy('id') ->get(); $elements = []; foreach ($models as $model) { $elements[] = $this->toDomain($model); } return $elements; } private function toDomain(ElementModel $model): Element { $set = $this->setRepo->find($model->set_id); if ($set === null) { throw new DomainException( "Set with id: {$model->set_id} doesnt exist" ); } $parentElement = null; if ($model->parent_element_id !== null) { $parentElement = $this->find($model->parent_element_id); if ($parentElement === null) { throw new DomainException( "Element with id: {$model->parent_element_id} doesnt exist" ); } } return new Element( id: $model->id, title: $model->title, description: $model->description, richText: $model->rich_text, pdfPath: $model->pdf_path, youtubeUrl: $model->youtube_url, set: $set, parentElement: $parentElement, ); } }