@@ -31,10 +31,10 @@ final class PersistenceManager
31
31
private bool $ flush = true ;
32
32
private bool $ persist = true ;
33
33
34
- /** @var list<object> */
34
+ /** @var list<list< object> > */
35
35
private array $ objectsToPersist = [];
36
36
37
- /** @var list<callable():void> */
37
+ /** @var list<list< callable():void> > */
38
38
private array $ afterPersistCallbacks = [];
39
39
40
40
/**
@@ -61,6 +61,12 @@ public function enablePersisting(): void
61
61
$ this ->persist = true ;
62
62
}
63
63
64
+ public function startTransaction (): void
65
+ {
66
+ $ this ->objectsToPersist [] = [];
67
+ $ this ->afterPersistCallbacks [] = [];
68
+ }
69
+
64
70
/**
65
71
* @template T of object
66
72
*
@@ -81,11 +87,17 @@ public function save(object $object): object
81
87
return $ object ;
82
88
}
83
89
84
- public function saveAll (): void
90
+ public function commit (): void
85
91
{
86
92
$ objectManagers = [];
87
93
88
- foreach ($ this ->objectsToPersist as $ object ) {
94
+ $ objectsToPersist = array_pop ($ this ->objectsToPersist );
95
+
96
+ if ($ objectsToPersist === null ) {
97
+ return ;
98
+ }
99
+
100
+ foreach ($ objectsToPersist as $ object ) {
89
101
$ om = $ this ->strategyFor ($ object ::class)->objectManagerFor ($ object ::class);
90
102
$ om ->persist ($ object );
91
103
@@ -94,8 +106,6 @@ public function saveAll(): void
94
106
}
95
107
}
96
108
97
- $ this ->objectsToPersist = [];
98
-
99
109
foreach ($ objectManagers as $ om ) {
100
110
$ this ->flush ($ om );
101
111
}
@@ -117,9 +127,9 @@ public function scheduleForInsert(object $object, array $afterPersistCallbacks =
117
127
$ object = unproxy ($ object );
118
128
}
119
129
120
- $ this ->objectsToPersist [] = $ object ;
130
+ $ this ->objectsToPersist [array_key_last ( $ this -> objectsToPersist )][ ] = $ object ;
121
131
122
- $ this ->afterPersistCallbacks = [...$ this ->afterPersistCallbacks , ...$ afterPersistCallbacks ];
132
+ $ this ->afterPersistCallbacks [ array_key_last ( $ this -> afterPersistCallbacks )] = [...$ this ->afterPersistCallbacks [ array_key_last ( $ this -> afterPersistCallbacks )] , ...$ afterPersistCallbacks ];
123
133
124
134
return $ object ;
125
135
}
@@ -168,8 +178,7 @@ private function callPostPersistCallbacks(): void
168
178
return ;
169
179
}
170
180
171
- $ afterPersistCallbacks = $ this ->afterPersistCallbacks ;
172
- $ this ->afterPersistCallbacks = [];
181
+ $ afterPersistCallbacks = array_pop ($ this ->afterPersistCallbacks );
173
182
174
183
foreach ($ afterPersistCallbacks as $ afterPersistCallback ) {
175
184
$ afterPersistCallback ();
0 commit comments