|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace App\Infrastructure\Doctrine\Transactions; |
|
4
|
|
|
|
|
5
|
|
|
use App\Infrastructure\Transactions\TransactionInterface; |
|
6
|
|
|
use Doctrine\Common\Collections\ArrayCollection; |
|
7
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
|
8
|
|
|
|
|
9
|
|
|
class DoctrineTransaction implements TransactionInterface |
|
10
|
|
|
{ |
|
11
|
|
|
private ArrayCollection $afterCommit; |
|
12
|
|
|
private ArrayCollection $afterRollback; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* @param EntityManagerInterface $entityManager |
|
16
|
|
|
* @param mixed $func |
|
17
|
|
|
*/ |
|
18
|
15 |
|
public function __construct( |
|
19
|
|
|
private EntityManagerInterface $entityManager, |
|
20
|
|
|
private mixed $func |
|
21
|
|
|
) |
|
22
|
|
|
{ |
|
23
|
15 |
|
$this->afterCommit = new ArrayCollection(); |
|
24
|
15 |
|
$this->afterRollback = new ArrayCollection(); |
|
25
|
15 |
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* After Transaction has been executed, the related Entity Manager |
|
29
|
|
|
* is cleaned and closed, so it cannot be re-used. |
|
30
|
|
|
* |
|
31
|
15 |
|
* @return mixed |
|
32
|
|
|
* @throws \Exception |
|
33
|
|
|
*/ |
|
34
|
15 |
|
public function execute(): mixed |
|
35
|
15 |
|
{ |
|
36
|
10 |
|
try { |
|
37
|
|
|
$result = $this->entityManager->wrapInTransaction($this->func); |
|
38
|
15 |
|
foreach ($this->afterCommit->toArray() as $rollbackFn) { |
|
39
|
|
|
$rollbackFn($result); |
|
40
|
|
|
} |
|
41
|
|
|
$this->cleanup(); |
|
42
|
|
|
return $result; |
|
43
|
|
|
} catch (\Exception $e) { |
|
44
|
|
|
foreach ($this->afterRollback->toArray() as $rollbackFn) { |
|
45
|
|
|
$rollbackFn(); |
|
46
|
|
|
} |
|
47
|
|
|
$this->cleanup(); |
|
48
|
|
|
throw $e; |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
10 |
|
|
|
52
|
|
|
/** |
|
53
|
10 |
|
* @param $func |
|
54
|
10 |
|
* @return $this |
|
55
|
|
|
*/ |
|
56
|
|
|
public function afterCommit($func): self |
|
57
|
|
|
{ |
|
58
|
|
|
$this->afterCommit->add($func); |
|
59
|
|
|
return $this; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* @param $func |
|
64
|
|
|
* @return $this |
|
65
|
|
|
*/ |
|
66
|
1 |
|
public function afterRollback($func): self |
|
67
|
|
|
{ |
|
68
|
|
|
$this->afterRollback->add($func); |
|
69
|
|
|
return $this; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
private function cleanup(): void |
|
73
|
|
|
{ |
|
74
|
|
|
if ($this->entityManager->isOpen()) { |
|
75
|
|
|
$this->entityManager->clear(); |
|
76
|
|
|
$this->entityManager->close(); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
} |