From f97c153276af67ec17454c623f383fc4082d4ed8 Mon Sep 17 00:00:00 2001 From: Fatih AYDIN Date: Fri, 22 Dec 2023 16:06:03 +0300 Subject: [PATCH] refactor: Updated `context` data --- src/Actor/Machine.php | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/src/Actor/Machine.php b/src/Actor/Machine.php index c60297c..e146e6d 100644 --- a/src/Actor/Machine.php +++ b/src/Actor/Machine.php @@ -217,14 +217,37 @@ public function send( */ public function persist(): ?State { + // Retrieve the previous context from the definition's config, or set it to an empty array if not set. + $incrementalContext = $this->definition->initializeContextFromState()->toArray(); + + // Get the last event from the state's history. + $lastHistoryEvent = $this->state->history->last(); + MachineEvent::upsert( - values: $this->state->history->map(fn (MachineEvent $machineEvent) => array_merge($machineEvent->toArray(), [ - 'created_at' => $machineEvent->created_at->toDateTimeString(), - 'machine_value' => json_encode($machineEvent->machine_value, JSON_THROW_ON_ERROR), - 'payload' => json_encode($machineEvent->payload, JSON_THROW_ON_ERROR), - 'context' => json_encode($machineEvent->context, JSON_THROW_ON_ERROR), - 'meta' => json_encode($machineEvent->meta, JSON_THROW_ON_ERROR), - ]))->toArray(), + values: $this->state->history->map(function (MachineEvent $machineEvent, int $index) use (&$incrementalContext, $lastHistoryEvent) { + // Get the context of the current machine event. + $changes = $machineEvent->context; + + // If the current machine event is not the last one, compare its context with the incremental context and get the differences. + if ($machineEvent->id !== $lastHistoryEvent->id && $index > 0) { + $changes = $this->arrayRecursiveDiff($changes, $incrementalContext); + } + + // If there are changes, update the incremental context to the current event's context. + if (!empty($changes)) { + $incrementalContext = $this->arrayRecursiveMerge($incrementalContext, $machineEvent->context); + } + + $machineEvent->context = $changes; + + return array_merge($machineEvent->toArray(), [ + 'created_at' => $machineEvent->created_at->toDateTimeString(), + 'machine_value' => json_encode($machineEvent->machine_value, JSON_THROW_ON_ERROR), + 'payload' => json_encode($machineEvent->payload, JSON_THROW_ON_ERROR), + 'context' => json_encode($machineEvent->context, JSON_THROW_ON_ERROR), + 'meta' => json_encode($machineEvent->meta, JSON_THROW_ON_ERROR), + ]); + })->toArray(), uniqueBy: ['id'] );