game-village-politics-backend/app/Actions/VillageAction.php

69 lines
2.1 KiB
PHP
Raw Normal View History

<?php
namespace App\Actions;
use App\Engine\Engine;
use App\Engine\Military;
use App\Engine\Push;
use App\Engine\Simulation;
use App\Engine\Starvation;
use App\Game\GameRuleViolation;
use App\Models\Building;
use App\Models\User;
use App\Models\Village;
use Carbon\CarbonImmutable;
use Closure;
use Illuminate\Support\Facades\DB;
/** Shared path of every village mutation: catch up, lock, settle to now, change, save. */
abstract class VillageAction
{
public function __construct(protected readonly Engine $engine) {}
/** @param Closure(Simulation, Village, CarbonImmutable): void $change */
protected function mutate(User $user, int $villageId, Closure $change): Village
{
$now = now()->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.');
}
}