1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Infrastructure\Doctrine\Transactions; |
4
|
|
|
|
5
|
|
|
use App\Infrastructure\Transactions\TransactionInterface; |
6
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
7
|
|
|
use DusanKasan\Knapsack\Collection; |
8
|
|
|
|
9
|
|
|
class DoctrineTransaction implements TransactionInterface |
10
|
|
|
{ |
11
|
|
|
private Collection $afterCommit; |
12
|
|
|
private Collection $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 = Collection::from([]); |
24
|
15 |
|
$this->afterRollback = Collection::from([]); |
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 |
|
$this->afterCommit |
39
|
|
|
->each(function ($successFn) use ($result) { |
40
|
|
|
$successFn($result); |
41
|
|
|
}) |
42
|
|
|
->realize(); |
43
|
|
|
$this->cleanup(); |
44
|
|
|
return $result; |
45
|
|
|
} catch (\Exception $e) { |
46
|
|
|
$this->afterRollback |
47
|
|
|
->each(function ($rollbackFn) { |
48
|
|
|
$rollbackFn(); |
49
|
|
|
}) |
50
|
|
|
->realize(); |
51
|
10 |
|
$this->cleanup(); |
52
|
|
|
throw $e; |
53
|
10 |
|
} |
54
|
10 |
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param $func |
58
|
|
|
* @return $this |
59
|
|
|
*/ |
60
|
|
|
public function afterCommit($func): self |
61
|
|
|
{ |
62
|
|
|
$this->afterCommit = $this->afterCommit->append($func); |
63
|
|
|
return $this; |
64
|
|
|
} |
65
|
|
|
|
66
|
1 |
|
/** |
67
|
|
|
* @param $func |
68
|
|
|
* @return $this |
69
|
|
|
*/ |
70
|
|
|
public function afterRollback($func): self |
71
|
|
|
{ |
72
|
|
|
$this->afterRollback = $this->afterRollback->append($func); |
73
|
|
|
return $this; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
private function cleanup(): void |
77
|
|
|
{ |
78
|
|
|
if ($this->entityManager->isOpen()) { |
79
|
|
|
$this->entityManager->clear(); |
80
|
|
|
$this->entityManager->close(); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
} |