$dto->name, 'description' => $dto->description, 'icon_image_url' => $dto->iconImageUrl, 'sort_order' => $this->nextSortOrder(), ]); return $this->toDomain($model); } public function update(Set $set): Set { $model = SetModel::find($set->getId()); if ($model === null) { throw new DomainException( "Set with id: {$set->getId()} doesnt exist" ); } $model->name = $set->getName(); $model->description = $set->getDescription(); $model->icon_image_url = $set->getIconImageUrl(); $model->save(); return $this->toDomain($model); } public function delete(Set $set): void { $model = SetModel::find($set->getId()); if ($model === null) { throw new DomainException( "Set with id: {$set->getId()} doesnt exist" ); } $model->delete(); } public function find(int $id): ?Set { $model = SetModel::find($id); return $model === null ? null : $this->toDomain($model); } public function getAll(): array { $models = SetModel::orderBy('sort_order')->orderBy('id')->get(); $sets = []; foreach ($models as $model) { $sets[] = $this->toDomain($model); } return $sets; } public function reorder(array $setIds): array { DB::transaction(function () use ($setIds): void { $sortOrder = 1; foreach ($setIds as $setId) { SetModel::where('id', $setId) ->update(['sort_order' => $sortOrder]); $sortOrder++; } }); return $this->getAll(); } private function nextSortOrder(): int { $currentMaxSortOrder = SetModel::max('sort_order'); if ($currentMaxSortOrder === null) { return 1; } return (int) $currentMaxSortOrder + 1; } private function toDomain(SetModel $model): Set { return new Set( id: $model->id, name: $model->name, description: $model->description, iconImageUrl: $model->icon_image_url, ); } }