Last active
March 9, 2021 22:28
-
-
Save GDXbsv/bb52b176457c3223e8f831c9927575b2 to your computer and use it in GitHub Desktop.
Locking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
final class DoctrineSagaPersistence implements SagaPersistence | |
{ | |
private ManagerRegistry $mr; | |
private SagaFinding $sagaFinding; | |
public function __construct(ManagerRegistry $mr, SagaFinding $sagaFinding) | |
{ | |
$this->mr = $mr; | |
$this->sagaFinding = $sagaFinding; | |
} | |
public function retrieveSaga(DomainMessage $domainMessage, string $sagaType): Saga | |
{ | |
/** @var object $message */ | |
$message = $domainMessage->getPayload(); | |
/** @var EntityManagerInterface $em */ | |
$em = $this->mr->getManager(); | |
$em->beginTransaction(); | |
foreach ($this->sagaFinding->sagasForMessage($message) as $finderDefinition) { | |
if ($finderDefinition->sagaType !== $sagaType) { | |
continue; | |
} | |
/** @var Id<Saga> $id */ | |
$id = ($finderDefinition->messageProperty)($message, $domainMessage); | |
/** @psalm-suppress TooManyArguments */ | |
$saga = $em->find( | |
$sagaType, | |
$id, | |
LockMode::PESSIMISTIC_WRITE | |
); | |
if ($saga === null) { | |
$saga = new $finderDefinition->sagaType($id); | |
$em->persist($saga); | |
} | |
return $saga; | |
} | |
throw new \Exception("Did not find saga $sagaType for message ".get_class($message)); | |
} | |
public function saveSaga(Saga $saga): void | |
{ | |
/** @var EntityManager $em */ | |
$em = $this->mr->getManager(); | |
$em->getUnitOfWork()->commit($saga); | |
$em->commit(); | |
} | |
public function cleanSaga(Saga $saga): void | |
{ | |
/** @var EntityManager $em */ | |
$em = $this->mr->getManager(); | |
$em->rollback(); | |
$this->mr->resetManager(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment