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

nextras / orm / 41909495460

04 Nov 2026 08:44PM UTC coverage: 92.015% (-0.002%) from 92.017%
41909495460

push

github

web-flow
Merge pull request #842 from nextras/js/dresscode

Setup DressCode

288 of 347 new or added lines in 66 files covered. (83.0%)

14 existing lines in 9 files now uncovered.

4402 of 4784 relevant lines covered (92.02%)

6.29 hits per line

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

90.67
/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\Mapper\IMapper;
39
use Nextras\Orm\Model\IModel;
40
use Nextras\Orm\Model\MetadataStorage;
41
use ReflectionClass;
42
use function sort;
43

44

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

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

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

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

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

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

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

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

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

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

81
        private IModel|null $model = null;
82
        private ConditionParser|null $conditionParser = null;
83

84
        /** @var IdentityMap<E> */
85
        private IdentityMap $identityMap;
86

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

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

93
        /** @var array<string, CollectionFunction> Collection functions cache */
94
        private array $collectionFunctions = [];
95

96

97
        public function __construct(
5 ✔
98
                /** @var IMapper<E> */
99
                protected readonly IMapper $mapper,
2 ✔
100
                protected readonly IDependencyProvider|null $dependencyProvider = null,
2 ✔
101
        )
102
        {
103
                $this->mapper->setRepository($this);
7 ✔
104

105
                /** @var IdentityMap<E> $identityMap */
106
                $identityMap = new IdentityMap($this);
7 ✔
107
                $this->identityMap = $identityMap;
7 ✔
108

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

121

122
        #[\NoDiscard]
123
        public function getModel(): IModel
124
        {
125
                if ($this->model === null) {
7 ✔
126
                        throw new InvalidStateException('Repository is not attached to model.');
×
127
                }
128

129
                return $this->model;
7 ✔
130
        }
131

132

133
        public function setModel(IModel $model): void
134
        {
135
                if ($this->model !== null && $this->model !== $model) {
7 ✔
136
                        throw new InvalidStateException('Repository is already attached.');
×
137
                }
138

139
                $this->model = $model;
7 ✔
140
        }
7 ✔
141

142

143
        #[\NoDiscard]
144
        public function getMapper(): IMapper
145
        {
146
                return $this->mapper;
7 ✔
147
        }
148

149

150
        #[\NoDiscard]
151
        public function getBy(array $conds): IEntity|null
152
        {
153
                return $this->findAll()->getBy($conds);
7 ✔
154
        }
155

156

157
        #[\NoDiscard]
158
        public function getByChecked(array $conds): IEntity
159
        {
160
                $entity = $this->getBy($conds);
7 ✔
161
                if ($entity === null) {
7 ✔
162
                        throw new NoResultException();
×
163
                }
164
                return $entity;
7 ✔
165
        }
166

167

168
        #[\NoDiscard]
169
        public function getById($id): IEntity|null
170
        {
171
                if ($id === null) {
7 ✔
172
                        return null;
×
173
                }
174

175
                $entity = $this->identityMap->getById($id);
7 ✔
176
                if ($entity === false) { // entity was removed
7 ✔
177
                        return null;
×
178
                } elseif ($entity instanceof IEntity) {
7 ✔
179
                        return $entity;
7 ✔
180
                }
181

182
                $entity = $this->findAll()->getBy(['id' => $id]);
7 ✔
183
                if ($entity === null) {
7 ✔
184
                        $this->identityMap->remove($id);
7 ✔
185
                }
186

187
                return $entity;
7 ✔
188
        }
189

190

191
        #[\NoDiscard]
192
        public function getByIdChecked($id): IEntity
193
        {
194
                $entity = $this->getById($id);
7 ✔
195
                if ($entity === null) {
7 ✔
196
                        throw new NoResultException();
×
197
                }
198
                return $entity;
7 ✔
199
        }
200

201

202
        #[\NoDiscard]
203
        public function findAll(): ICollection
204
        {
205
                return $this->mapper->findAll();
7 ✔
206
        }
207

208

209
        #[\NoDiscard]
210
        public function findBy(array $conds): ICollection
211
        {
212
                return $this->findAll()->findBy($conds);
7 ✔
213
        }
214

215

216
        #[\NoDiscard]
217
        public function findByIds(array $ids): ICollection
218
        {
219
                $entities = [];
7 ✔
220
                $missingEntities = false;
7 ✔
221

222
                foreach ($ids as $id) {
7 ✔
223
                        $entity = $this->identityMap->getById($id);
7 ✔
224
                        if ($entity === null || $entity === false) {
7 ✔
225
                                $missingEntities = true;
7 ✔
226
                                break;
7 ✔
227
                        }
228
                        $entities[] = $entity;
7 ✔
229
                }
230

231
                if (!$missingEntities) {
7 ✔
232
                        return new ArrayCollection($entities, $this);
7 ✔
233
                }
234

235
                return $this->findAll()->findBy(['id' => $ids]);
7 ✔
236
        }
237

238

239
        #[\NoDiscard]
240
        public function getCollectionFunction(string $name): CollectionFunction
241
        {
242
                if (!isset($this->collectionFunctions[$name])) {
7 ✔
243
                        $this->collectionFunctions[$name] = $this->createCollectionFunction($name);
7 ✔
244
                }
245
                return $this->collectionFunctions[$name];
7 ✔
246
        }
247

248

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

268
                if ($name === FetchPropertyFunction::class) {
7 ✔
269
                        return new FetchPropertyFunction($this, $this->mapper, $this->getModel());
7 ✔
270
                } elseif ($name === ConjunctionOperatorFunction::class) {
7 ✔
271
                        return new ConjunctionOperatorFunction($this->getConditionParser());
7 ✔
272
                } elseif ($name === DisjunctionOperatorFunction::class) {
7 ✔
273
                        return new DisjunctionOperatorFunction($this->getConditionParser());
7 ✔
274
                }
275

276
                if (isset($knownFunctions[$name])) {
7 ✔
277
                        $function = new $name();
7 ✔
278
                        assert($function instanceof CollectionFunction);
279
                        return $function;
7 ✔
280
                } else {
NEW
281
                        throw new NotImplementedException('Override ' . static::class . '::createCollectionFunction() to return an instance of ' . $name . ' collection function.');
×
282
                }
283
        }
284

285

286
        public function attach(IEntity $entity): void
287
        {
288
                if (!$entity->isAttached()) {
7 ✔
289
                        $entity->onAttach($this, MetadataStorage::get($entity::class));
7 ✔
290
                        if ($this->dependencyProvider !== null) {
7 ✔
291
                                $this->dependencyProvider->injectDependencies($entity);
7 ✔
292
                        }
293
                }
294
        }
7 ✔
295

296

297
        public function detach(IEntity $entity): void
298
        {
299
                if ($entity->isAttached()) {
7 ✔
300
                        $entity->onDetach();
7 ✔
301
                }
302
        }
7 ✔
303

304

305
        public function hydrateEntity(array $data): IEntity|null
306
        {
307
                return $this->identityMap->create($data);
7 ✔
308
        }
309

310

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

321

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

331
                return $this->entityClassName;
7 ✔
332
        }
333

334

335
        public function getConditionParser(): ConditionParser
336
        {
337
                if ($this->conditionParser === null) {
7 ✔
338
                        $this->conditionParser = new ConditionParser();
7 ✔
339
                }
340
                return $this->conditionParser;
7 ✔
341
        }
342

343

344
        public function persist(IEntity $entity, bool $withCascade = true): IEntity
345
        {
346
                $this->identityMap->check($entity);
7 ✔
347
                $this->getModel()->persist($entity, $withCascade);
7 ✔
348
                return $entity;
7 ✔
349
        }
350

351

352
        public function doPersist(IEntity $entity): void
353
        {
354
                if (!$entity->isModified()) {
7 ✔
355
                        return;
7 ✔
356
                }
357

358
                $isPersisted = $entity->isPersisted();
7 ✔
359
                if ($isPersisted) {
7 ✔
360
                        $this->onBeforeUpdate($entity);
7 ✔
361
                        $this->identityMap->remove($entity->getPersistedId()); // id can change in composite key
7 ✔
362
                } else {
363
                        $this->onBeforeInsert($entity);
7 ✔
364
                }
365

366
                $this->mapper->persist($entity);
7 ✔
367
                $this->identityMap->add($entity);
7 ✔
368
                $this->entitiesToFlush[0][] = $entity;
7 ✔
369

370
                if ($isPersisted) {
7 ✔
371
                        $this->onAfterUpdate($entity);
7 ✔
372
                } else {
373
                        $this->onAfterInsert($entity);
7 ✔
374
                }
375
                $this->onAfterPersist($entity);
7 ✔
376
        }
7 ✔
377

378

379
        public function remove(IEntity $entity, bool $withCascade = true): IEntity
380
        {
381
                $this->identityMap->check($entity);
7 ✔
382
                return $this->getModel()->remove($entity, $withCascade);
7 ✔
383
        }
384

385

386
        public function doRemove(IEntity $entity): void
387
        {
388
                $this->detach($entity);
7 ✔
389
                if (!$entity->isPersisted()) {
7 ✔
390
                        return;
×
391
                }
392

393
                $this->mapper->remove($entity);
7 ✔
394
                $this->identityMap->remove($entity->getPersistedId());
7 ✔
395
                $this->entitiesToFlush[1][] = $entity;
7 ✔
396
                $this->onAfterRemove($entity);
7 ✔
397
        }
7 ✔
398

399

400
        public function flush(): void
401
        {
402
                $this->getModel()->flush();
7 ✔
403
        }
7 ✔
404

405

406
        public function persistAndFlush(IEntity $entity, bool $withCascade = true): IEntity
407
        {
408
                $this->persist($entity, $withCascade);
7 ✔
409
                $this->flush();
7 ✔
410
                return $entity;
7 ✔
411
        }
412

413

414
        public function removeAndFlush(IEntity $entity, bool $withCascade = true): IEntity
415
        {
416
                $this->remove($entity, $withCascade);
7 ✔
417
                $this->flush();
7 ✔
418
                return $entity;
7 ✔
419
        }
420

421

422
        public function doFlush(): array
423
        {
424
                $this->mapper->flush();
7 ✔
425
                $this->onFlush($this->entitiesToFlush[0], $this->entitiesToFlush[1]);
7 ✔
426
                $entities = $this->entitiesToFlush;
7 ✔
427
                $this->entitiesToFlush = [[], []];
7 ✔
428
                return $entities;
7 ✔
429
        }
430

431

432
        public function doClear(): void
433
        {
434
                $this->identityMap->destroyAllEntities();
7 ✔
435
                $this->mapper->clearCache();
7 ✔
436
        }
7 ✔
437

438

439
        /**
440
         * @param mixed[] $args
441
         * @return mixed
442
         */
443
        public function __call(string $method, array $args)
444
        {
445
                if (isset($this->proxyMethods[strtolower($method)])) {
7 ✔
446
                        $callback = [$this->mapper, $method];
7 ✔
447
                        assert(is_callable($callback));
448
                        return $callback(...$args);
7 ✔
449
                } else {
NEW
450
                        $class = static::class;
×
451
                        throw new MemberAccessException("Undefined $class::$method() (proxy)method.");
×
452
                }
453
        }
454

455

456
        public function doRefreshAll(bool $allowOverwrite): void
457
        {
458
                $ids = [];
7 ✔
459
                $entities = $this->identityMap->getAll();
7 ✔
460
                foreach ($entities as $entity) {
7 ✔
461
                        if (!$entity->isPersisted()) {
7 ✔
462
                                continue;
×
463
                        } elseif (!$allowOverwrite && $entity->isModified()) {
7 ✔
464
                                throw new InvalidStateException('Cannot refresh modified entity, flush changes first or set $allowOverwrite flag to true.');
7 ✔
465
                        }
466
                        $this->identityMap->markForRefresh($entity);
7 ✔
467
                        $ids[] = $entity->getPersistedId();
7 ✔
468
                }
469
                if ($ids !== []) {
7 ✔
470
                        sort($ids); // make ids sorted deterministically
7 ✔
471
                        // the fetch itself refreshes the entities in the identity map
472
                        $_ = $this->findByIds($ids)->fetchAll();
7 ✔
473
                }
474
                foreach ($entities as $entity) {
7 ✔
475
                        if (!$this->identityMap->isMarkedForRefresh($entity)) {
7 ✔
476
                                continue;
7 ✔
477
                        }
478
                        $this->detach($entity);
7 ✔
479
                        $this->identityMap->remove($entity->getPersistedId());
7 ✔
480
                        $this->onAfterRemove($entity);
7 ✔
481
                }
482
                $this->mapper->clearCache();
7 ✔
483
        }
7 ✔
484

485

486
        public function onBeforePersist(IEntity $entity): void
487
        {
488
                $entity->onBeforePersist();
7 ✔
489
                foreach ($this->onBeforePersist as $handler) {
7 ✔
490
                        $handler($entity);
7 ✔
491
                }
492
        }
7 ✔
493

494

495
        public function onAfterPersist(IEntity $entity): void
496
        {
497
                $entity->onAfterPersist();
7 ✔
498
                foreach ($this->onAfterPersist as $handler) {
7 ✔
NEW
499
                        $handler($entity);
×
500
                }
501
        }
7 ✔
502

503

504
        public function onBeforeInsert(IEntity $entity): void
505
        {
506
                $entity->onBeforeInsert();
7 ✔
507
                foreach ($this->onBeforeInsert as $handler) {
7 ✔
NEW
508
                        $handler($entity);
×
509
                }
510
        }
7 ✔
511

512

513
        public function onAfterInsert(IEntity $entity): void
514
        {
515
                $entity->onAfterInsert();
7 ✔
516
                foreach ($this->onAfterInsert as $handler) {
7 ✔
517
                        $handler($entity);
7 ✔
518
                }
519
        }
7 ✔
520

521

522
        public function onBeforeUpdate(IEntity $entity): void
523
        {
524
                $entity->onBeforeUpdate();
7 ✔
525
                foreach ($this->onBeforeUpdate as $handler) {
7 ✔
NEW
526
                        $handler($entity);
×
527
                }
528
        }
7 ✔
529

530

531
        public function onAfterUpdate(IEntity $entity): void
532
        {
533
                $entity->onAfterUpdate();
7 ✔
534
                foreach ($this->onAfterUpdate as $handler) {
7 ✔
NEW
535
                        $handler($entity);
×
536
                }
537
        }
7 ✔
538

539

540
        public function onBeforeRemove(IEntity $entity): void
541
        {
542
                $entity->onBeforeRemove();
7 ✔
543
                foreach ($this->onBeforeRemove as $handler) {
7 ✔
NEW
544
                        $handler($entity);
×
545
                }
546
        }
7 ✔
547

548

549
        public function onAfterRemove(IEntity $entity): void
550
        {
551
                $entity->onAfterRemove();
7 ✔
552
                foreach ($this->onAfterRemove as $handler) {
7 ✔
NEW
553
                        $handler($entity);
×
554
                }
555
        }
7 ✔
556

557

558
        public function onFlush(array $persistedEntities, array $removedEntities): void
559
        {
560
                foreach ($this->onFlush as $handler) {
7 ✔
561
                        $handler($persistedEntities, $removedEntities);
7 ✔
562
                }
563
        }
7 ✔
564
}
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