Skip to content

Commit

Permalink
refactor: Machine.php
Browse files Browse the repository at this point in the history
  • Loading branch information
YunusEmreNalbant committed Nov 16, 2023
1 parent b448600 commit 37b865e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 20 deletions.
44 changes: 25 additions & 19 deletions src/Actor/Machine.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,34 +165,40 @@ public function send(
bool $shouldPersist = true,
): State {
if ($this->state !== null) {
$lock = Cache::lock($this->state->history->first()->root_event_id, 60);
$lock = Cache::lock('machine-id:'.$this->state->history->first()->root_event_id, 60);
}

if (!($lock?->get() ?? true)) {
if (isset($lock) && !$lock->get()) {
throw MachineAlreadyRunningException::build($this->state->history->first()->root_event_id);
}

$lastPreviousEventNumber = $this->state !== null
? $this->state->history->last()->sequence_number
: 0;
try {
$lastPreviousEventNumber = $this->state !== null
? $this->state->history->last()->sequence_number
: 0;

// If the event is a string, we assume it's the event type.
if (is_string($event)) {
$event = ['type' => $event];
}
// If the event is a string, we assume it's the event type.
if (is_string($event)) {
$event = ['type' => $event];
}

$this->state = match (true) {
$event->isTransactional ?? false => DB::transaction(fn () => $this->definition->transition($event, $this->state)),
default => $this->definition->transition($event, $this->state)
};
$this->state = match (true) {
$event->isTransactional ?? false => DB::transaction(fn () => $this->definition->transition($event, $this->state)),
default => $this->definition->transition($event, $this->state)
};

if ($shouldPersist === true) {
$this->persist();
}

$this->handleValidationGuards($lastPreviousEventNumber);
if ($shouldPersist === true) {
$this->persist();
}

$lock?->release();
$this->handleValidationGuards($lastPreviousEventNumber);
} catch (Exception $exception) {
throw $exception;
} finally {
if (isset($lock)) {
$lock->release();
}
}

return $this->state;
}
Expand Down
2 changes: 1 addition & 1 deletion tests/MachineTransitionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@
$machine = AsdMachine::create();
$machine->persist();

$rootEventId = $machine->state->history->first()->root_event_id;
$rootEventId = 'machine-id:'.$machine->state->history->first()->root_event_id;

Cache::shouldReceive('lock')
->once()
Expand Down

0 comments on commit 37b865e

Please sign in to comment.