18
18
use Doctrine \DBAL ;
19
19
use Doctrine \ORM ;
20
20
use Doctrine \Persistence ;
21
+ use FastyBird \Library \Application \Events ;
21
22
use FastyBird \Library \Application \Exceptions ;
22
23
use FastyBird \Library \Metadata \Types as MetadataTypes ;
23
24
use Nette ;
25
+ use Psr \EventDispatcher ;
24
26
use Psr \Log ;
25
27
use Throwable ;
26
28
use function gc_collect_cycles ;
@@ -41,6 +43,7 @@ class Database
41
43
42
44
public function __construct (
43
45
private readonly Persistence \ManagerRegistry |null $ managerRegistry = null ,
46
+ private readonly EventDispatcher \EventDispatcherInterface |null $ dispatcher = null ,
44
47
private readonly Log \LoggerInterface $ logger = new Log \NullLogger (),
45
48
)
46
49
{
@@ -95,6 +98,8 @@ public function transaction(callable $callback)
95
98
// Start transaction connection to the database
96
99
$ connection ->beginTransaction ();
97
100
101
+ $ this ->dispatcher ?->dispatch(new Events \DbTransactionStarted ());
102
+
98
103
$ result = $ callback ();
99
104
100
105
if ($ connection ->isRollbackOnly ()) {
@@ -106,6 +111,8 @@ public function transaction(callable $callback)
106
111
$ connection ->commit ();
107
112
}
108
113
114
+ $ this ->dispatcher ?->dispatch(new Events \DbTransactionFinished ());
115
+
109
116
return $ result ;
110
117
} catch (Throwable $ ex ) {
111
118
// Revert all changes when error occur
@@ -137,6 +144,8 @@ public function beginTransaction(): void
137
144
$ this ->pingAndReconnect ();
138
145
139
146
$ connection ->beginTransaction ();
147
+
148
+ $ this ->dispatcher ?->dispatch(new Events \DbTransactionStarted ());
140
149
} catch (Throwable $ ex ) {
141
150
throw new Exceptions \InvalidState (
142
151
'An error occurred: ' . $ ex ->getMessage (),
@@ -165,6 +174,8 @@ public function commitTransaction(): void
165
174
} else {
166
175
// Commit all changes into database
167
176
$ connection ->commit ();
177
+
178
+ $ this ->dispatcher ?->dispatch(new Events \DbTransactionFinished ());
168
179
}
169
180
} catch (Throwable $ ex ) {
170
181
// Revert all changes when error occur
@@ -234,24 +245,6 @@ public function clear(): void
234
245
continue ;
235
246
}
236
247
237
- // Flushing and then clearing Doctrine's entity manager allows
238
- // for more memory to be released by PHP
239
- try {
240
- if ($ manager ->isOpen ()) {
241
- $ manager ->flush ();
242
- }
243
- } catch (Throwable $ ex ) {
244
- // Log caught exception
245
- $ this ->logger ->error (
246
- 'An unhandled error occurred during flushing entity manager ' ,
247
- [
248
- 'source ' => MetadataTypes \Sources \Module::NOT_SPECIFIED ,
249
- 'type ' => 'helper ' ,
250
- 'exception ' => Logger::buildException ($ ex ),
251
- ],
252
- );
253
- }
254
-
255
248
try {
256
249
$ manager ->getConnection ()->close ();
257
250
} catch (Throwable $ ex ) {
0 commit comments