game-village-politics-backend/app/Engine/Tribes.php

55 lines
2.0 KiB
PHP
Raw Permalink Normal View History

<?php
namespace App\Engine;
use App\Game\Tribes\Diplomacy;
use App\Models\Player;
use App\Models\TribeRelation;
use Carbon\CarbonImmutable;
/** Tribe relations as rows: between two players, and from one tribe to all others. */
final class Tribes
{
/** What $b is to $a: own tribe, ally, NAP partner, enemy, or nothing. */
public static function between(?Player $a, ?Player $b, CarbonImmutable $now): string
{
$mine = $a?->tribeId();
$theirs = $b?->tribeId();
if ($mine === null || $theirs === null || $mine === $theirs) {
return Diplomacy::relation($mine, $theirs, [], $now);
}
$rows = TribeRelation::where(fn ($q) => $q->where('tribe_id', $mine)->where('other_tribe_id', $theirs))
->orWhere(fn ($q) => $q->where('tribe_id', $theirs)->where('other_tribe_id', $mine))
->get()->map->row();
return Diplomacy::relation($mine, $theirs, $rows, $now);
}
/**
* Every other tribe this one has a relation with: tribe id => relation.
*
* @return array<int, string>
*/
public static function relationsOf(?int $tribeId, CarbonImmutable $now): array
{
if ($tribeId === null) {
return [];
}
$rows = TribeRelation::where('tribe_id', $tribeId)->orWhere('other_tribe_id', $tribeId)->get()->map->row();
$out = [];
foreach ($rows as $row) {
$other = $row['tribe_id'] === $tribeId ? $row['other_tribe_id'] : $row['tribe_id'];
$out[$other] ??= Diplomacy::relation($tribeId, $other, $rows, $now);
}
return array_filter($out, fn (string $r) => $r !== Diplomacy::NONE);
}
/** Drop pacts whose notice has run out. */
public static function prune(int $tribeId, CarbonImmutable $now): void
{
TribeRelation::where(fn ($q) => $q->where('tribe_id', $tribeId)->orWhere('other_tribe_id', $tribeId))
->whereNotNull('ends_at')->where('ends_at', '<=', Engine::stamp($now))->delete();
}
}