• 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

88.74
/src/Repository/Repository.php
1
<?php declare(strict_types = 1);
2

3
/**
4
 * This file is part of the Nextras\Orm library.
5
 * This file was inspired by PetrP's ORM library https://github.com/PetrP/Orm/.
6
 * @link       https://github.com/nextras/orm
7
 */
8

9
namespace Nextras\Orm\Repository;
10

11

12
use Nextras\Orm\Collection\ArrayCollection;
13
use Nextras\Orm\Collection\Functions\AvgAggregateFunction;
14
use Nextras\Orm\Collection\Functions\CollectionFunction;
15
use Nextras\Orm\Collection\Functions\CompareEqualsFunction;
16
use Nextras\Orm\Collection\Functions\CompareGreaterThanEqualsFunction;
17
use Nextras\Orm\Collection\Functions\CompareGreaterThanFunction;
18
use Nextras\Orm\Collection\Functions\CompareLikeFunction;
19
use Nextras\Orm\Collection\Functions\CompareNotEqualsFunction;
20
use Nextras\Orm\Collection\Functions\CompareSmallerThanEqualsFunction;
21
use Nextras\Orm\Collection\Functions\CompareSmallerThanFunction;
22
use Nextras\Orm\Collection\Functions\ConjunctionOperatorFunction;
23
use Nextras\Orm\Collection\Functions\CountAggregateFunction;
24
use Nextras\Orm\Collection\Functions\DisjunctionOperatorFunction;
25
use Nextras\Orm\Collection\Functions\FetchPropertyFunction;
26
use Nextras\Orm\Collection\Functions\MaxAggregateFunction;
27
use Nextras\Orm\Collection\Functions\MinAggregateFunction;
28
use Nextras\Orm\Collection\Functions\SumAggregateFunction;
29
use Nextras\Orm\Collection\Helpers\ConditionParser;
30
use Nextras\Orm\Collection\ICollection;
31
use Nextras\Orm\Entity\IEntity;
32
use Nextras\Orm\Entity\Reflection\EntityMetadata;
33
use Nextras\Orm\Exception\InvalidArgumentException;
34
use Nextras\Orm\Exception\InvalidStateException;
35
use Nextras\Orm\Exception\MemberAccessException;
36
use Nextras\Orm\Exception\NoResultException;
37
use Nextras\Orm\Exception\NotImplementedException;
38
use Nextras\Orm\Exception\RollbackException;
39
use Nextras\Orm\Mapper\IMapper;
40
use Nextras\Orm\Model\IModel;
41
use Nextras\Orm\Model\MetadataStorage;
42
use ReflectionClass;
43
use Throwable;
44
use function sort;
45

46

47
/**
48
 * @template E of IEntity
49
 * @implements IRepository<E>
50
 */
51
abstract class Repository implements IRepository
52
{
53
        /** @var array<mixed, callable(E $entity): void> */
54
        public array $onBeforePersist = [];
55

56
        /** @var array<mixed, callable(E $entity): void> */
57
        public array $onAfterPersist = [];
58

59
        /** @var array<mixed, callable(E $entity): void> */
60
        public array $onBeforeInsert = [];
61

62
        /** @var array<mixed, callable(E $entity): void> */
63
        public array $onAfterInsert = [];
64

65
        /** @var array<mixed, callable(E $entity): void> */
66
        public array $onBeforeUpdate = [];
67

68
        /** @var array<mixed, callable(E $entity): void> */
69
        public array $onAfterUpdate = [];
70

71
        /** @var array<mixed, callable(E $entity): void> */
72
        public array $onBeforeRemove = [];
73

74
        /** @var array<mixed, callable(E $entity): void> */
75
        public array $onAfterRemove = [];
76

77
        /** @var array<mixed, callable(E[] $persisted, E[] $removed): void> */
78
        public array $onFlush = [];
79

80
        /** @var class-string<E>|null */
81
        protected string|null $entityClassName = null;
82

83
        private IModel|null $model = null;
84
        private ConditionParser|null $conditionParser = null;
85

86
        /** @var IdentityMap<E> */
87
        private IdentityMap $identityMap;
88

89
        /** @var array<string, bool> */
90
        private array $proxyMethods = [];
91

92
        /** @var array{list<E>, list<E>} */
93
        private array $entitiesToFlush = [[], []];
94

95
        /** @var list<E> Persistence and removal attempts retained until the transaction completes. */
96
        private array $entitiesToRollback = [];
97

98
        /** @var array<string, CollectionFunction> Collection functions cache */
99
        private array $collectionFunctions = [];
100

101

102
        public function __construct(
5 ✔
103
                /** @var IMapper<E> */
104
                protected readonly IMapper $mapper,
2 ✔
105
                protected readonly IDependencyProvider|null $dependencyProvider = null,
2 ✔
106
        )
107
        {
108
                $this->mapper->setRepository($this);
7 ✔
109

110
                /** @var IdentityMap<E> $identityMap */
111
                $identityMap = new IdentityMap($this);
7 ✔
112
                $this->identityMap = $identityMap;
7 ✔
113

114
                $reflection = new ReflectionClass($this);
7 ✔
115
                preg_match_all(
7 ✔
116
                        '~^[ \t*]* @method[ \t]+[^\s]+[ \t]+(\w+)\(.*\).*$~um',
7 ✔
117
                        (string) $reflection->getDocComment(),
7 ✔
118
                        $matches,
119
                        PREG_SET_ORDER,
7 ✔
120
                );
121
                foreach ($matches as [, $methodname]) {
7 ✔
122
                        $this->proxyMethods[strtolower($methodname)] = true;
7 ✔
123
                }
124
        }
7 ✔
125

126

127
        #[\NoDiscard]
128
        public function getModel(): IModel
129
        {
130
                if ($this->model === null) {
7 ✔
131
                        throw new InvalidStateException('Repository is not attached to model.');
×
132
                }
133

134
                return $this->model;
7 ✔
135
        }
136

137

138
        public function setModel(IModel $model): void
139
        {
140
                if ($this->model !== null && $this->model !== $model) {
7 ✔
141
                        throw new InvalidStateException('Repository is already attached.');
×
142
                }
143

144
                $this->model = $model;
7 ✔
145
        }
7 ✔
146

147

148
        #[\NoDiscard]
149
        public function getMapper(): IMapper
150
        {
151
                return $this->mapper;
7 ✔
152
        }
153

154

155
        #[\NoDiscard]
156
        public function getBy(array $conds): IEntity|null
157
        {
158
                return $this->findAll()->getBy($conds);
7 ✔
159
        }
160

161

162
        #[\NoDiscard]
163
        public function getByChecked(array $conds): IEntity
164
        {
165
                $entity = $this->getBy($conds);
7 ✔
166
                if ($entity === null) {
7 ✔
167
                        throw new NoResultException();
×
168
                }
169
                return $entity;
7 ✔
170
        }
171

172

173
        #[\NoDiscard]
174
        public function getById($id): IEntity|null
175
        {
176
                if ($id === null) {
7 ✔
177
                        return null;
×
178
                }
179

180
                $entity = $this->identityMap->getById($id);
7 ✔
181
                if ($entity === false) { // entity was removed
7 ✔
182
                        return null;
×
183
                } elseif ($entity instanceof IEntity) {
7 ✔
184
                        return $entity;
7 ✔
185
                }
186

187
                $entity = $this->findAll()->getBy(['id' => $id]);
7 ✔
188
                if ($entity === null) {
7 ✔
189
                        $this->identityMap->remove($id);
7 ✔
190
                }
191

192
                return $entity;
7 ✔
193
        }
194

195

196
        #[\NoDiscard]
197
        public function getByIdChecked($id): IEntity
198
        {
199
                $entity = $this->getById($id);
7 ✔
200
                if ($entity === null) {
7 ✔
201
                        throw new NoResultException();
×
202
                }
203
                return $entity;
7 ✔
204
        }
205

206

207
        #[\NoDiscard]
208
        public function findAll(): ICollection
209
        {
210
                return $this->mapper->findAll();
7 ✔
211
        }
212

213

214
        #[\NoDiscard]
215
        public function findBy(array $conds): ICollection
216
        {
217
                return $this->findAll()->findBy($conds);
7 ✔
218
        }
219

220

221
        #[\NoDiscard]
222
        public function findByIds(array $ids): ICollection
223
        {
224
                $entities = [];
7 ✔
225
                $missingEntities = false;
7 ✔
226

227
                foreach ($ids as $id) {
7 ✔
228
                        $entity = $this->identityMap->getById($id);
7 ✔
229
                        if ($entity === null || $entity === false) {
7 ✔
230
                                $missingEntities = true;
7 ✔
231
                                break;
7 ✔
232
                        }
233
                        $entities[] = $entity;
7 ✔
234
                }
235

236
                if (!$missingEntities) {
7 ✔
237
                        return new ArrayCollection($entities, $this);
7 ✔
238
                }
239

240
                return $this->findAll()->findBy(['id' => $ids]);
7 ✔
241
        }
242

243

244
        #[\NoDiscard]
245
        public function getCollectionFunction(string $name): CollectionFunction
246
        {
247
                if (!isset($this->collectionFunctions[$name])) {
7 ✔
248
                        $this->collectionFunctions[$name] = $this->createCollectionFunction($name);
7 ✔
249
                }
250
                return $this->collectionFunctions[$name];
7 ✔
251
        }
252

253

254
        protected function createCollectionFunction(string $name): CollectionFunction
255
        {
256
                /** @var array<class-string<CollectionFunction>, true> $knownFunctions */
257
                static $knownFunctions = [
7 ✔
258
                        FetchPropertyFunction::class => true,
259
                        CompareEqualsFunction::class => true,
260
                        CompareGreaterThanEqualsFunction::class => true,
261
                        CompareGreaterThanFunction::class => true,
262
                        CompareNotEqualsFunction::class => true,
263
                        CompareSmallerThanEqualsFunction::class => true,
264
                        CompareSmallerThanFunction::class => true,
265
                        CompareLikeFunction::class => true,
266
                        AvgAggregateFunction::class => true,
267
                        CountAggregateFunction::class => true,
268
                        MaxAggregateFunction::class => true,
269
                        MinAggregateFunction::class => true,
270
                        SumAggregateFunction::class => true,
271
                ];
272

273
                if ($name === FetchPropertyFunction::class) {
7 ✔
274
                        return new FetchPropertyFunction($this, $this->mapper, $this->getModel());
7 ✔
275
                } elseif ($name === ConjunctionOperatorFunction::class) {
7 ✔
276
                        return new ConjunctionOperatorFunction($this->getConditionParser());
7 ✔
277
                } elseif ($name === DisjunctionOperatorFunction::class) {
7 ✔
278
                        return new DisjunctionOperatorFunction($this->getConditionParser());
7 ✔
279
                }
280

281
                if (isset($knownFunctions[$name])) {
7 ✔
282
                        $function = new $name();
7 ✔
283
                        assert($function instanceof CollectionFunction);
284
                        return $function;
7 ✔
285
                } else {
286
                        throw new NotImplementedException('Override ' . static::class . '::createCollectionFunction() to return an instance of ' . $name . ' collection function.');
×
287
                }
288
        }
289

290

291
        public function attach(IEntity $entity): void
292
        {
293
                if (!$entity->isAttached()) {
7 ✔
294
                        $entity->onAttach($this, MetadataStorage::get($entity::class));
7 ✔
295
                        if ($this->dependencyProvider !== null) {
7 ✔
296
                                $this->dependencyProvider->injectDependencies($entity);
7 ✔
297
                        }
298
                }
299
        }
7 ✔
300

301

302
        public function detach(IEntity $entity): void
303
        {
304
                if ($entity->isAttached()) {
7 ✔
305
                        $entity->onDetach();
7 ✔
306
                }
307
        }
7 ✔
308

309

310
        public function hydrateEntity(array $data): IEntity|null
311
        {
312
                return $this->identityMap->create($data);
7 ✔
313
        }
314

315

316
        #[\NoDiscard]
317
        public function getEntityMetadata(string|null $entityClass = null): EntityMetadata
318
        {
319
                $classNames = static::getEntityClassNames();
7 ✔
320
                if ($entityClass !== null && !in_array($entityClass, $classNames, true)) {
7 ✔
321
                        throw new InvalidArgumentException("Class '$entityClass' is not accepted by '" . static::class . "' repository.");
×
322
                }
323
                return MetadataStorage::get($entityClass ?? $classNames[0]);
7 ✔
324
        }
325

326

327
        #[\NoDiscard]
328
        public function getEntityClassName(array $data): string
329
        {
330
                if ($this->entityClassName === null) {
7 ✔
331
                        /** @var class-string<E> $entityClassName */
332
                        $entityClassName = static::getEntityClassNames()[0];
7 ✔
333
                        $this->entityClassName = $entityClassName;
7 ✔
334
                }
335

336
                return $this->entityClassName;
7 ✔
337
        }
338

339

340
        public function getConditionParser(): ConditionParser
341
        {
342
                if ($this->conditionParser === null) {
7 ✔
343
                        $this->conditionParser = new ConditionParser();
7 ✔
344
                }
345
                return $this->conditionParser;
7 ✔
346
        }
347

348

349
        public function persist(IEntity $entity, bool $withCascade = true): IEntity
350
        {
351
                $this->identityMap->check($entity);
7 ✔
352
                $this->getModel()->persist($entity, $withCascade);
7 ✔
353
                return $entity;
7 ✔
354
        }
355

356

357
        public function doPersist(IEntity $entity): void
358
        {
359
                if (!$entity->isModified()) {
7 ✔
360
                        return;
7 ✔
361
                }
362

363
                $isPersisted = $entity->isPersisted();
7 ✔
364
                if ($isPersisted) {
7 ✔
365
                        $this->onBeforeUpdate($entity);
7 ✔
366
                        $this->identityMap->remove($entity->getPersistedId()); // id can change in composite key
7 ✔
367
                } else {
368
                        $this->onBeforeInsert($entity);
7 ✔
369
                }
370

371
                $this->mapper->persist($entity);
7 ✔
372
                $this->identityMap->add($entity);
7 ✔
373
                $this->entitiesToFlush[0][] = $entity;
7 ✔
374

375
                if ($isPersisted) {
7 ✔
376
                        $this->onAfterUpdate($entity);
7 ✔
377
                } else {
378
                        $this->onAfterInsert($entity);
7 ✔
379
                }
380
                $this->onAfterPersist($entity);
7 ✔
381
        }
7 ✔
382

383

384
        public function remove(IEntity $entity, bool $withCascade = true): IEntity
385
        {
386
                $this->identityMap->check($entity);
7 ✔
387
                return $this->getModel()->remove($entity, $withCascade);
7 ✔
388
        }
389

390

391
        public function doRemove(IEntity $entity): void
392
        {
393
                $this->detach($entity);
7 ✔
394
                if (!$entity->isPersisted()) {
7 ✔
395
                        return;
×
396
                }
397

398
                $this->mapper->remove($entity);
7 ✔
399
                $this->identityMap->remove($entity->getPersistedId());
7 ✔
400
                $this->entitiesToFlush[1][] = $entity;
7 ✔
401
                $this->onAfterRemove($entity);
7 ✔
402
        }
7 ✔
403

404

405
        public function flush(): void
406
        {
407
                $this->getModel()->flush();
7 ✔
408
        }
7 ✔
409

410

411
        public function persistAndFlush(IEntity $entity, bool $withCascade = true): IEntity
412
        {
413
                $this->persist($entity, $withCascade);
7 ✔
414
                $this->flush();
7 ✔
415
                return $entity;
7 ✔
416
        }
417

418

419
        public function removeAndFlush(IEntity $entity, bool $withCascade = true): IEntity
420
        {
421
                $this->remove($entity, $withCascade);
7 ✔
422
                $this->flush();
7 ✔
423
                return $entity;
7 ✔
424
        }
425

426

427
        public function doFlush(bool $keepRollbackState = false): array
428
        {
429
                $this->mapper->flush();
7 ✔
430
                $this->onFlush($this->entitiesToFlush[0], $this->entitiesToFlush[1]);
7 ✔
431
                $entities = $this->entitiesToFlush;
7 ✔
432
                $this->entitiesToFlush = [[], []];
7 ✔
433
                if (!$keepRollbackState) {
7 ✔
434
                        $this->doFinalizeTransaction();
7 ✔
435
                }
436
                return $entities;
7 ✔
437
        }
438

439

440
        public function doFinalizeTransaction(): void
441
        {
442
                $this->entitiesToRollback = [];
7 ✔
443
        }
7 ✔
444

445

446
        public function doClear(): void
447
        {
448
                $managedIds = [];
7 ✔
449
                foreach ($this->identityMap->getAll() as $entity) {
7 ✔
450
                        $managedIds[spl_object_id($entity)] = true;
7 ✔
451
                }
452
                $pending = array_merge($this->entitiesToRollback, $this->entitiesToFlush[0], $this->entitiesToFlush[1]);
7 ✔
453
                $this->entitiesToFlush = [[], []];
7 ✔
454
                $this->entitiesToRollback = [];
7 ✔
455
                $this->collectionFunctions = [];
7 ✔
456
                $errors = [];
7 ✔
457
                try {
458
                        $this->identityMap->destroyAllEntities();
7 ✔
NEW
459
                } catch (Throwable $e) {
×
NEW
460
                        $errors[] = $e;
×
461
                }
462
                foreach ($pending as $entity) {
7 ✔
463
                        $id = spl_object_id($entity);
7 ✔
464
                        if (isset($managedIds[$id]) || ($entity->isAttached() && $entity->getRepository() !== $this)) {
7 ✔
465
                                continue;
7 ✔
466
                        }
467
                        $managedIds[$id] = true;
7 ✔
468
                        try {
469
                                $this->detach($entity);
7 ✔
470
                                $entity->onFree();
7 ✔
NEW
471
                        } catch (Throwable $e) {
×
NEW
472
                                $errors[] = $e;
×
473
                        }
474
                }
475
                try {
476
                        $this->mapper->clearCache();
7 ✔
NEW
477
                } catch (Throwable $e) {
×
NEW
478
                        $errors[] = $e;
×
479
                }
480
                if ($errors !== []) {
7 ✔
NEW
481
                        throw new RollbackException($errors);
×
482
                }
483
        }
7 ✔
484

485

486
        /**
487
         * @param mixed[] $args
488
         * @return mixed
489
         */
490
        public function __call(string $method, array $args)
491
        {
492
                if (isset($this->proxyMethods[strtolower($method)])) {
7 ✔
493
                        $callback = [$this->mapper, $method];
7 ✔
494
                        assert(is_callable($callback));
495
                        return $callback(...$args);
7 ✔
496
                } else {
497
                        $class = static::class;
×
498
                        throw new MemberAccessException("Undefined $class::$method() (proxy)method.");
×
499
                }
500
        }
501

502

503
        public function doRefreshAll(bool $allowOverwrite): void
504
        {
505
                $ids = [];
7 ✔
506
                $entities = $this->identityMap->getAll();
7 ✔
507
                foreach ($entities as $entity) {
7 ✔
508
                        if (!$entity->isPersisted()) {
7 ✔
509
                                continue;
×
510
                        } elseif (!$allowOverwrite && $entity->isModified()) {
7 ✔
511
                                throw new InvalidStateException('Cannot refresh modified entity, flush changes first or set $allowOverwrite flag to true.');
7 ✔
512
                        }
513
                        $this->identityMap->markForRefresh($entity);
7 ✔
514
                        $ids[] = $entity->getPersistedId();
7 ✔
515
                }
516
                if ($ids !== []) {
7 ✔
517
                        sort($ids); // make ids sorted deterministically
7 ✔
518
                        // the fetch itself refreshes the entities in the identity map
519
                        $_ = $this->findByIds($ids)->fetchAll();
7 ✔
520
                }
521
                foreach ($entities as $entity) {
7 ✔
522
                        if (!$this->identityMap->isMarkedForRefresh($entity)) {
7 ✔
523
                                continue;
7 ✔
524
                        }
525
                        $this->detach($entity);
7 ✔
526
                        $this->identityMap->remove($entity->getPersistedId());
7 ✔
527
                        $this->onAfterRemove($entity);
7 ✔
528
                }
529
                $this->mapper->clearCache();
7 ✔
530
        }
7 ✔
531

532

533
        public function onBeforePersist(IEntity $entity): void
534
        {
535
                $this->entitiesToRollback[] = $entity;
7 ✔
536
                $entity->onBeforePersist();
7 ✔
537
                foreach ($this->onBeforePersist as $handler) {
7 ✔
538
                        $handler($entity);
7 ✔
539
                }
540
        }
7 ✔
541

542

543
        public function onAfterPersist(IEntity $entity): void
544
        {
545
                $entity->onAfterPersist();
7 ✔
546
                foreach ($this->onAfterPersist as $handler) {
7 ✔
547
                        $handler($entity);
×
548
                }
549
        }
7 ✔
550

551

552
        public function onBeforeInsert(IEntity $entity): void
553
        {
554
                $entity->onBeforeInsert();
7 ✔
555
                foreach ($this->onBeforeInsert as $handler) {
7 ✔
556
                        $handler($entity);
×
557
                }
558
        }
7 ✔
559

560

561
        public function onAfterInsert(IEntity $entity): void
562
        {
563
                $entity->onAfterInsert();
7 ✔
564
                foreach ($this->onAfterInsert as $handler) {
7 ✔
565
                        $handler($entity);
7 ✔
566
                }
567
        }
7 ✔
568

569

570
        public function onBeforeUpdate(IEntity $entity): void
571
        {
572
                $entity->onBeforeUpdate();
7 ✔
573
                foreach ($this->onBeforeUpdate as $handler) {
7 ✔
574
                        $handler($entity);
×
575
                }
576
        }
7 ✔
577

578

579
        public function onAfterUpdate(IEntity $entity): void
580
        {
581
                $entity->onAfterUpdate();
7 ✔
582
                foreach ($this->onAfterUpdate as $handler) {
7 ✔
583
                        $handler($entity);
×
584
                }
585
        }
7 ✔
586

587

588
        public function onBeforeRemove(IEntity $entity): void
589
        {
590
                $this->entitiesToRollback[] = $entity;
7 ✔
591
                $entity->onBeforeRemove();
7 ✔
592
                foreach ($this->onBeforeRemove as $handler) {
7 ✔
593
                        $handler($entity);
×
594
                }
595
        }
7 ✔
596

597

598
        public function onAfterRemove(IEntity $entity): void
599
        {
600
                $entity->onAfterRemove();
7 ✔
601
                foreach ($this->onAfterRemove as $handler) {
7 ✔
602
                        $handler($entity);
×
603
                }
604
        }
7 ✔
605

606

607
        public function onFlush(array $persistedEntities, array $removedEntities): void
608
        {
609
                foreach ($this->onFlush as $handler) {
7 ✔
610
                        $handler($persistedEntities, $removedEntities);
7 ✔
611
                }
612
        }
7 ✔
613
}
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