transactions->run(fn (): bool => match ($level) { CatalogLevel::ServiceUnit => $this->moveServiceUnit($id, $direction), CatalogLevel::Service => $this->moveService($id, $direction), CatalogLevel::WorkType => $this->moveWorkType($id, $direction), }); } private function moveServiceUnit(int $id, MoveDirection $direction): bool { $item = $this->serviceUnits->findById($id) ?? throw new CatalogItemNotFound(CatalogLevel::ServiceUnit, $id); $neighbour = $this->serviceUnits->neighbour($item, $direction); return $neighbour !== null && $this->swap($item, $neighbour, fn (ServiceUnit $unit) => $this->serviceUnits->save($unit)); } private function moveService(int $id, MoveDirection $direction): bool { $item = $this->services->findById($id) ?? throw new CatalogItemNotFound(CatalogLevel::Service, $id); $neighbour = $this->services->neighbour($item, $direction); return $neighbour !== null && $this->swap($item, $neighbour, fn (Service $service) => $this->services->save($service)); } private function moveWorkType(int $id, MoveDirection $direction): bool { $item = $this->workTypes->findById($id) ?? throw new CatalogItemNotFound(CatalogLevel::WorkType, $id); $neighbour = $this->workTypes->neighbour($item, $direction); return $neighbour !== null && $this->swap($item, $neighbour, fn (WorkType $workType) => $this->workTypes->save($workType)); } /** * @template T of ServiceUnit|Service|WorkType * * @param T $item * @param T $neighbour * @param callable(T): mixed $save */ private function swap(ServiceUnit|Service|WorkType $item, ServiceUnit|Service|WorkType $neighbour, callable $save): bool { $item->swapOrderWith($neighbour); $save($item); $save($neighbour); return true; } }