toImmutable(); $this->engine->catchUpAround($villageId, $now); try { return $this->locked($user, $villageId, $change, $now); } finally { Push::flush(); } } private function locked(User $user, int $villageId, Closure $change, CarbonImmutable $now): Village { return DB::transaction(function () use ($user, $villageId, $change, $now) { $village = Village::whereKey($villageId)->lockForUpdate()->first(); if (! $village || $village->player?->user_id !== $user->id) { throw new GameRuleViolation('not_found', 'Village not found.'); } if (! $this->readOnly()) { $village->world->ensureOpen(); } $sim = Simulation::of($village); $sim->settle($now); Military::of($village, $sim)->settle($now); $change($sim, $village, $now); Starvation::of($village, $sim)->sync($now); $village->save(); return $village; }); } /** Looking is allowed after the world ended; changing is not. */ protected function readOnly(): bool { return false; } protected function building(Village $village, int $buildingId): Building { return $village->buildings->firstWhere('id', $buildingId) ?? throw new GameRuleViolation('not_found', 'Building not found.'); } }