47 lines
2.3 KiB
PHP
47 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\User;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
use stdClass;
|
|
|
|
class PartnershipDraftSaves
|
|
{
|
|
public function replay(User $actor, stdClass $record, ?string $key, string $hash): ?stdClass
|
|
{
|
|
if ($key === null) {
|
|
return null;
|
|
}
|
|
// The caller holds the partnership lock and has checked its current write authority.
|
|
$event = DB::table('partnership_events')->where('partnership_id', $record->id)->where('actor_id', $actor->id)->where('event_type', 'partnership_opportunity.changed.v1')->whereRaw("payload->'payload'->>'operation_key' = ?", [$key])->selectRaw("payload->'payload'->>'operation_hash' AS hash, payload->'payload'->'result_version' AS version")->first();
|
|
if (! $event) {
|
|
return null;
|
|
}
|
|
abort_unless($event->hash === $hash, 409, 'Chave de gravação já utilizada com outro conteúdo.');
|
|
$version = is_string($event->version) ? json_decode($event->version, true, 512, JSON_THROW_ON_ERROR) : $event->version;
|
|
abort_unless(is_int($version) && $version > 0, 409, 'A versão da gravação anterior não foi identificada.');
|
|
$record->command_replayed = true;
|
|
$record->command_saved_version = $version;
|
|
|
|
return $record;
|
|
}
|
|
|
|
/** @return list<array{key:string,version:int}> */
|
|
public function commands(User $actor, stdClass $record): array
|
|
{
|
|
abort_unless(app(PartnershipExchange::class)->owns($actor, $record), 403);
|
|
$events = DB::table('partnership_events')->where('partnership_id', $record->id)->where('actor_id', $actor->id)->where('event_type', 'partnership_opportunity.changed.v1')->whereRaw("payload->'payload'->>'operation_key' IS NOT NULL")->orderBy('aggregate_version')->selectRaw("payload->'payload'->>'operation_key' AS key, payload->'payload'->'result_version' AS version")->get();
|
|
$commands = [];
|
|
foreach ($events as $event) {
|
|
$version = is_string($event->version) ? json_decode($event->version, true, 512, JSON_THROW_ON_ERROR) : $event->version;
|
|
if (is_string($event->key) && Str::isUuid($event->key) && is_int($version) && $version > 0) {
|
|
$commands[] = ['key' => $event->key, 'version' => $version];
|
|
}
|
|
}
|
|
|
|
return $commands;
|
|
}
|
|
}
|