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

58 lines
2.3 KiB
PHP
Raw Normal View History

<?php
namespace App\Actions;
use App\Engine\Rally;
use App\Game\GameRuleViolation;
use App\Game\Trade\TradeRules;
use App\Game\Travel\TravelTime;
use App\Models\TradeOffer;
use App\Models\User;
use App\Models\Village;
use App\Presenters\MarketPresenter;
/** The open offers of a world, nearest to the village first, optionally of one resource given or asked for. */
final class ListOffers
{
public const LIMIT = 100;
public function __invoke(User $user, int $villageId, ?string $give = null, ?string $want = null): array
{
$village = Village::with('player', 'world')->find($villageId);
if (! $village || $village->player?->user_id !== $user->id) {
throw new GameRuleViolation('not_found', 'Village not found.');
}
$rules = new TradeRules($village->world->gameConfig());
[$x, $y] = [$village->x, $village->y];
$offers = TradeOffer::with('village.player')
->select('trade_offers.*')
->join('villages', 'villages.id', '=', 'trade_offers.village_id')
->where('trade_offers.world_id', $village->world_id)
->when($give, fn ($q) => $q->where('trade_offers.give_resource', $give))
->when($want, fn ($q) => $q->where('trade_offers.want_resource', $want))
->orderByRaw('(villages.x - ?) * (villages.x - ?) + (villages.y - ?) * (villages.y - ?)', [$x, $x, $y, $y])
->orderBy('trade_offers.id')
->limit(self::LIMIT)
->get();
return [
'server_time' => MarketPresenter::iso(now()),
'offers' => $offers->map(function (TradeOffer $o) use ($village, $rules, $x, $y) {
$distance = TravelTime::distance($x, $y, $o->village->x, $o->village->y);
return [
'id' => $o->id,
'village' => Rally::summary($o->village),
'give' => ['resource' => $o->give_resource, 'amount' => $o->give_amount],
'want' => ['resource' => $o->want_resource, 'amount' => $o->want_amount],
'count' => $o->count,
'distance' => round($distance, 2),
'seconds' => $rules->seconds($distance),
'own' => $o->village->player_id === $village->player_id,
];
})->values()->all(),
];
}
}