• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nextras / orm / 43632413080

14 Nov 2026 07:30PM UTC coverage: 92.038% (-0.2%) from 92.222%
43632413080

Pull #852

github

web-flow
Merge f17a16229 into 07ee8e7ce
Pull Request #852: Add model rollback and transaction callbacks

153 of 177 new or added lines in 9 files covered. (86.44%)

4601 of 4999 relevant lines covered (92.04%)

6.26 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

89.76
/src/Model/Model.php
1
<?php declare(strict_types = 1);
2

3
namespace Nextras\Orm\Model;
4

5

6
use Nette\SmartObject;
7
use Nextras\Orm\Entity\IEntity;
8
use Nextras\Orm\Exception\InvalidArgumentException;
9
use Nextras\Orm\Exception\InvalidStateException;
10
use Nextras\Orm\Exception\NotSupportedException;
11
use Nextras\Orm\Exception\RollbackException;
12
use Nextras\Orm\Mapper\IRollbackableMapper;
13
use Nextras\Orm\Mapper\ITransactionalMapper;
14
use Nextras\Orm\Relationships\IRelationshipCollection;
15
use Nextras\Orm\Relationships\IRelationshipContainer;
16
use Nextras\Orm\Repository\IRepository;
17
use Nextras\Orm\Repository\PersistenceHelper;
18
use Nextras\Orm\Repository\PersistenceMode;
19
use Throwable;
20
use function array_merge;
21
use function is_string;
22

23

24
class Model implements IModel
25
{
26
        use SmartObject;
27

28
        /** @var list<callable(IEntity[] $persisted, IEntity[] $removed): void> */
29
        public array $onFlush = [];
30

31
        private bool $transactionActive = false;
32

33
        private Throwable|null $transactionFailure = null;
34

35

36
        public function __construct(
5 ✔
37
                private readonly IRepositoryLoader $repositoryLoader,
2 ✔
38
                private readonly MetadataStorage $metadataStorage,
2 ✔
39
        )
40
        {
41
        }
7 ✔
42

43

44
        #[\NoDiscard]
45
        public function hasRepositoryByName(string $name): bool
46
        {
47
                return $this->repositoryLoader->hasRepositoryByName($name);
×
48
        }
49

50

51
        #[\NoDiscard]
52
        public function getRepositoryByName(string $name): IRepository
53
        {
54
                return $this->repositoryLoader->getRepositoryByName($name)
7 ✔
55
                        ?? throw new InvalidArgumentException("Repository with '$name' simple name does not exist.");
7 ✔
56
        }
57

58

59
        #[\NoDiscard]
60
        public function hasRepository(string $className): bool
61
        {
62
                return $this->repositoryLoader->hasRepository($className);
×
63
        }
64

65

66
        #[\NoDiscard]
67
        public function getRepository(string $className): IRepository
68
        {
69
                return $this->repositoryLoader->getRepository($className)
7 ✔
70
                        ?? throw new InvalidArgumentException("Repository with '$className' class name does not exist.");
7 ✔
71
        }
72

73

74
        #[\NoDiscard]
75
        public function getRepositoryForEntity($entity): IRepository
76
        {
77
                $entityClassName = is_string($entity) ? $entity : $entity::class;
7 ✔
78
                $repositoryClassName = $this->repositoryLoader->getRepositoryClassNameForEntity($entityClassName)
7 ✔
79
                        ?? throw new InvalidArgumentException("No repository manages '$entityClassName' entity.");
×
80
                return $this->getRepository($repositoryClassName);
7 ✔
81
        }
82

83

84
        #[\NoDiscard]
85
        public function getMetadataStorage(): MetadataStorage
86
        {
87
                return $this->metadataStorage;
×
88
        }
89

90

91
        public function persist(IEntity $entity, bool $withCascade = true): IEntity
92
        {
93
                $this->processPersist(mode: PersistenceMode::Persist, entity: $entity, withCascade: $withCascade);
7 ✔
94
                return $entity;
7 ✔
95
        }
96

97

98
        public function persistAndFlush(IEntity $entity): IEntity
99
        {
100
                $this->persist($entity);
7 ✔
101
                $this->flush();
7 ✔
102
                return $entity;
7 ✔
103
        }
104

105

106
        public function remove(IEntity $entity, bool $withCascade = true): IEntity
107
        {
108
                $this->processPersist(mode: PersistenceMode::Remove, entity: $entity, withCascade: $withCascade);
7 ✔
109
                return $entity;
7 ✔
110
        }
111

112

113
        public function removeAndFlush(IEntity $entity, bool $withCascade = true): IEntity
114
        {
115
                $this->remove($entity, $withCascade);
7 ✔
116
                $this->flush();
7 ✔
117
                return $entity;
7 ✔
118
        }
119

120

121
        public function flush(): void
122
        {
123
                if ($this->transactionFailure !== null) {
7 ✔
NEW
124
                        throw new InvalidStateException('The transaction has already failed.', 0, $this->transactionFailure);
×
125
                }
126
                try {
127
                        $allPersisted = [];
7 ✔
128
                        $allRemoved = [];
7 ✔
129
                        foreach ($this->repositoryLoader->getInitializedRepositories() as $repository) {
7 ✔
130
                                [$persisted, $removed] = $repository->doFlush($this->transactionActive);
7 ✔
131
                                $allPersisted = array_merge($allPersisted, $persisted);
7 ✔
132
                                $allRemoved = array_merge($allRemoved, $removed);
7 ✔
133
                        }
134

135
                        $this->onFlush($allPersisted, $allRemoved);
7 ✔
136

NEW
137
                } catch (Throwable $e) {
×
NEW
138
                        if ($this->transactionActive) {
×
NEW
139
                                $this->transactionFailure = $e;
×
140
                        }
NEW
141
                        throw $e;
×
142
                }
143
        }
7 ✔
144

145

146
        public function rollback(): void
147
        {
148
                if ($this->transactionActive) {
7 ✔
NEW
149
                        throw new InvalidStateException('Cannot call rollback() inside transactional(). Throw an exception instead.');
×
150
                }
151
                $errors = [];
7 ✔
152
                $participants = [];
7 ✔
153
                foreach ($this->repositoryLoader->getInitializedRepositories() as $repository) {
7 ✔
154
                        try {
155
                                $mapper = $repository->getMapper();
7 ✔
156
                                if ($mapper instanceof ITransactionalMapper) {
7 ✔
157
                                        $id = spl_object_id($mapper->getTransactionCoordinator());
7 ✔
158
                                        if (isset($participants[$id])) {
7 ✔
159
                                                continue;
7 ✔
160
                                        }
161
                                        $participants[$id] = true;
7 ✔
162
                                }
163
                                if (!$mapper instanceof IRollbackableMapper) {
7 ✔
NEW
164
                                        throw new NotSupportedException('Mapper ' . $mapper::class . ' does not support rollback.');
×
165
                                }
166
                                $mapper->rollback();
7 ✔
167
                        } catch (Throwable $e) {
7 ✔
168
                                $errors[] = $e;
7 ✔
169
                        }
170
                }
171
                $errors = array_merge($errors, $this->resetRepositories());
7 ✔
172
                if ($errors !== []) {
7 ✔
173
                        throw new RollbackException($errors);
7 ✔
174
                }
175
        }
7 ✔
176

177

178
        public function transactional(callable $callback): mixed
179
        {
180
                if ($this->transactionActive) {
7 ✔
181
                        throw new InvalidStateException('Nested Model::transactional() calls are not supported.');
7 ✔
182
                }
183
                $coordinator = null;
7 ✔
184
                foreach ($this->repositoryLoader->getRepositories() as $repository) {
7 ✔
185
                        $mapper = $repository->getMapper();
7 ✔
186
                        if (!$mapper instanceof ITransactionalMapper) {
7 ✔
187
                                throw new NotSupportedException('Mapper ' . $mapper::class . ' does not support transaction callbacks.');
7 ✔
188
                        }
189
                        $participant = $mapper->getTransactionCoordinator();
7 ✔
190
                        if ($coordinator !== null && $participant !== $coordinator) {
7 ✔
191
                                throw new NotSupportedException('Model::transactional() requires all mappers to share one transaction coordinator.');
7 ✔
192
                        }
193
                        $coordinator = $participant;
7 ✔
194
                }
195
                if ($coordinator === null) {
7 ✔
NEW
196
                        throw new NotSupportedException('Model::transactional() requires at least one transactional mapper.');
×
197
                }
198

199
                $this->transactionActive = true;
7 ✔
200
                $started = false;
7 ✔
201
                try {
202
                        $result = $coordinator->transactional(function () use ($callback, &$started) {
7 ✔
203
                                $started = true;
7 ✔
204
                                $result = $callback($this);
7 ✔
205
                                if ($this->transactionFailure !== null) {
7 ✔
206
                                        throw $this->transactionFailure;
7 ✔
207
                                }
208
                                $this->flush();
7 ✔
209
                                return $result;
7 ✔
210
                        });
7 ✔
211
                } catch (Throwable $e) {
7 ✔
212
                        if ($started) {
7 ✔
213
                                $errors = $this->resetRepositories();
7 ✔
214
                                if ($errors !== []) {
7 ✔
215
                                        throw new RollbackException($errors, $e);
7 ✔
216
                                }
217
                        }
218
                        throw $e;
7 ✔
219
                } finally {
7 ✔
220
                        $this->transactionActive = false;
7 ✔
221
                        $this->transactionFailure = null;
7 ✔
222
                }
223
                foreach ($this->repositoryLoader->getInitializedRepositories() as $completedRepository) {
7 ✔
224
                        $completedRepository->doFinalizeTransaction();
7 ✔
225
                }
226
                return $result;
7 ✔
227
        }
228

229

230
        /**
231
         * @return list<Throwable>
232
         */
233
        private function resetRepositories(): array
234
        {
235
                $errors = [];
7 ✔
236
                foreach ($this->repositoryLoader->getInitializedRepositories() as $repository) {
7 ✔
237
                        try {
238
                                $repository->doClear();
7 ✔
239
                        } catch (Throwable $e) {
7 ✔
240
                                $errors[] = $e;
7 ✔
241
                        }
242
                }
243
                return $errors;
7 ✔
244
        }
245

246

247
        public function clear(): void
248
        {
249
                foreach ($this->repositoryLoader->getInitializedRepositories() as $repository) {
7 ✔
250
                        $repository->doClear();
7 ✔
251
                }
252
        }
7 ✔
253

254

255
        public function refreshAll(bool $allowOverwrite = false): void
256
        {
257
                foreach ($this->repositoryLoader->getInitializedRepositories() as $repository) {
7 ✔
258
                        $repository->doRefreshAll($allowOverwrite);
7 ✔
259
                }
260
        }
7 ✔
261

262

263
        /**
264
         * Returns repository by its name.
265
         * @return IRepository<*>
266
         */
267
        public function &__get(string $name): IRepository
268
        {
269
                $repository = $this->getRepositoryByName($name);
7 ✔
270
                return $repository;
7 ✔
271
        }
272

273

274
        protected function processPersist(PersistenceMode $mode, IEntity $entity, bool $withCascade): void
275
        {
276
                if ($this->transactionFailure !== null) {
7 ✔
NEW
277
                        throw new InvalidStateException('The transaction has already failed.', 0, $this->transactionFailure);
×
278
                }
279
                try {
280
                        [$queuePersist, $queueRemove] = PersistenceHelper::getCascadeQueue($entity, $mode, $this, $withCascade);
7 ✔
281
                        foreach ($queuePersist as $object) {
7 ✔
282
                                if ($object instanceof IEntity) {
7 ✔
283
                                        $repository = $this->getRepositoryForEntity($object);
7 ✔
284
                                        $repository->doPersist($object);
7 ✔
285
                                } elseif ($object instanceof IRelationshipCollection) {
7 ✔
286
                                        $object->doPersist();
7 ✔
287
                                } elseif ($object instanceof IRelationshipContainer) {
7 ✔
288
                                        $object->doPersist();
7 ✔
289
                                }
290
                        }
291
                        foreach ($queueRemove as $object) {
7 ✔
292
                                $repository = $this->getRepositoryForEntity($object);
7 ✔
293
                                $repository->doRemove($object);
7 ✔
294
                        }
295
                } catch (Throwable $e) {
7 ✔
296
                        if ($this->transactionActive) {
7 ✔
297
                                $this->transactionFailure = $e;
7 ✔
298
                        }
299
                        throw $e;
7 ✔
300
                }
301
        }
7 ✔
302
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc