1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace RemiSan\TransactionManager\Doctrine; |
4
|
|
|
|
5
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
6
|
|
|
use RemiSan\TransactionManager\Exception\BeginException; |
7
|
|
|
use RemiSan\TransactionManager\Exception\CommitException; |
8
|
|
|
use RemiSan\TransactionManager\Exception\RollbackException; |
9
|
|
|
use RemiSan\TransactionManager\Transactional; |
10
|
|
|
|
11
|
|
|
final class DoctrineEntityManager implements Transactional |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var EntityManagerInterface |
15
|
|
|
*/ |
16
|
|
|
private $entityManager; |
17
|
|
|
/** |
18
|
|
|
* @var bool |
19
|
|
|
*/ |
20
|
|
|
private $closeEntityManagerOnRollback; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Constructor. |
24
|
|
|
* |
25
|
|
|
* @param EntityManagerInterface $entityManager |
26
|
|
|
* @param bool $closeEntityManagerOnRollback |
27
|
|
|
*/ |
28
|
30 |
|
public function __construct(EntityManagerInterface $entityManager, $closeEntityManagerOnRollback = false) |
29
|
|
|
{ |
30
|
30 |
|
$this->entityManager = $entityManager; |
31
|
30 |
|
$this->closeEntityManagerOnRollback = $closeEntityManagerOnRollback; |
32
|
30 |
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* {@inheritdoc} |
36
|
|
|
*/ |
37
|
9 |
|
public function beginTransaction() |
38
|
|
|
{ |
39
|
9 |
|
if (!$this->entityManager->isOpen()) { |
40
|
3 |
|
throw new BeginException('Entity Manager is closed'); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
try { |
44
|
6 |
|
$this->entityManager->beginTransaction(); |
45
|
6 |
|
} catch (\Exception $e) { |
46
|
3 |
|
throw new BeginException('Cannot begin Doctrine ORM transaction', $e->getCode(), $e); |
47
|
|
|
} |
48
|
3 |
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* {@inheritdoc} |
52
|
|
|
*/ |
53
|
6 |
|
public function commit() |
54
|
|
|
{ |
55
|
|
|
try { |
56
|
6 |
|
$this->entityManager->flush(); |
57
|
6 |
|
$this->entityManager->commit(); |
58
|
6 |
|
} catch (\Exception $e) { |
59
|
3 |
|
throw new CommitException('Cannot commit Doctrine ORM transaction', $e->getCode(), $e); |
60
|
|
|
} |
61
|
3 |
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* {@inheritdoc} |
65
|
|
|
*/ |
66
|
12 |
|
public function rollback() |
67
|
|
|
{ |
68
|
|
|
try { |
69
|
12 |
|
$this->entityManager->rollback(); |
70
|
12 |
|
} catch (\Exception $e) { |
71
|
3 |
|
throw new RollbackException('Cannot rollback Doctrine ORM transaction', $e->getCode(), $e); |
72
|
|
|
} |
73
|
|
|
|
74
|
9 |
|
if ($this->closeEntityManagerOnRollback) { |
75
|
3 |
|
$this->entityManager->close(); |
76
|
3 |
|
} |
77
|
9 |
|
} |
78
|
|
|
} |
79
|
|
|
|