Skip to content

Commit

Permalink
refactor: Updated context data
Browse files Browse the repository at this point in the history
  • Loading branch information
aydinfatih committed Dec 22, 2023
1 parent 738136d commit f97c153
Showing 1 changed file with 30 additions and 7 deletions.
37 changes: 30 additions & 7 deletions src/Actor/Machine.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']
);

Expand Down

0 comments on commit f97c153

Please sign in to comment.