• 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

94.38
/src/Collection/DbalCollection.php
1
<?php declare(strict_types = 1);
2

3
namespace Nextras\Orm\Collection;
4

5

6
use Iterator;
7
use Nextras\Dbal\IConnection;
8
use Nextras\Dbal\Platforms\Data\Fqn;
9
use Nextras\Dbal\Platforms\MySqlPlatform;
10
use Nextras\Dbal\Platforms\SqlServerPlatform;
11
use Nextras\Dbal\QueryBuilder\QueryBuilder;
12
use Nextras\Orm\Collection\Expression\ExpressionContext;
13
use Nextras\Orm\Collection\Functions\Result\DbalExpressionResult;
14
use Nextras\Orm\Collection\Helpers\DbalQueryBuilderHelper;
15
use Nextras\Orm\Collection\Helpers\FetchPairsHelper;
16
use Nextras\Orm\Entity\IEntity;
17
use Nextras\Orm\Exception\InvalidStateException;
18
use Nextras\Orm\Exception\MemberAccessException;
19
use Nextras\Orm\Exception\NoResultException;
20
use Nextras\Orm\Mapper\Dbal\DbalMapper;
21
use Nextras\Orm\Mapper\IRelationshipMapper;
22
use function count;
23
use function is_array;
24

25

26
/**
27
 * @template E of IEntity
28
 * @implements ICollection<E>
29
 */
30
class DbalCollection implements ICollection
31
{
32
        /** @var list<callable(\Traversable<E> $entities): void> */
33
        public array $onEntityFetch = [];
34

35
        protected IRelationshipMapper|null $relationshipMapper = null;
36
        protected IEntity|null $relationshipParent = null;
37

38
        /** @var Iterator<E>|null */
39
        protected Iterator|null $fetchIterator = null;
40

41
        protected DbalQueryBuilderHelper|null $helper = null;
42

43
        /** @var list<E>|null */
44
        protected array|null $result = null;
45
        protected int|null $resultCount = null;
46
        protected bool $entityFetchEventTriggered = false;
47

48
        /** @var array<string, Fqn> GROUP BY columns contributed by findBy() filtering. */
49
        private array $filterGroupByColumns = [];
50

51
        /** @var array<string, Fqn> GROUP BY columns contributed by orderBy() expressions. */
52
        private array $orderGroupByColumns = [];
53

54
        /** @var array<string, Fqn> Columns referenced by orderBy() expressions; required in GROUP BY once grouping is active. */
55
        private array $orderColumns = [];
56

57
        /** @var array<string, true> */
58
        private array $mysqlGroupByWorkaroundApplied = [];
59

60

61
        public function __construct(
5 ✔
62
                /** @var DbalMapper<E> */
63
                protected readonly DbalMapper $mapper,
2 ✔
64
                protected readonly IConnection $connection,
2 ✔
65
                protected QueryBuilder $queryBuilder,
2 ✔
66
        )
67
        {
68
        }
7 ✔
69

70

71
        #[\NoDiscard]
72
        public function getBy(array $conds): IEntity|null
73
        {
74
                return $this->findBy($conds)->fetch();
7 ✔
75
        }
76

77

78
        #[\NoDiscard]
79
        public function getByChecked(array $conds): IEntity
80
        {
81
                return $this->findBy($conds)->fetchChecked();
7 ✔
82
        }
83

84

85
        #[\NoDiscard]
86
        public function getById($id): IEntity|null
87
        {
88
                return $this->getBy(['id' => $id]);
7 ✔
89
        }
90

91

92
        #[\NoDiscard]
93
        public function getByIdChecked($id): IEntity
94
        {
95
                $entity = $this->getById($id);
7 ✔
96
                if ($entity === null) {
7 ✔
97
                        throw new NoResultException();
7 ✔
98
                }
99
                return $entity;
7 ✔
100
        }
101

102

103
        #[\NoDiscard('Method returns a new collection instance, the original collection is not modified.')]
104
        public function findBy(array $conds): ICollection
105
        {
106
                $collection = clone $this;
7 ✔
107
                $expression = $collection->getHelper()->processExpression(
7 ✔
108
                        builder: $collection->queryBuilder,
7 ✔
109
                        expression: $conds,
110
                        aggregator: null,
7 ✔
111
                );
112
                $finalContext = $expression->havingExpression === null
7 ✔
113
                        ? ExpressionContext::FilterAnd
7 ✔
114
                        : ExpressionContext::FilterAndWithHavingClause;
7 ✔
115
                $expression = $expression->collect($finalContext);
7 ✔
116

117
                $collection->applyExpressionJoins($expression);
7 ✔
118
                if ($expression->expression !== null && $expression->args !== []) {
7 ✔
119
                        $collection->queryBuilder->andWhere($expression->expression, ...$expression->args);
7 ✔
120
                }
121
                if ($expression->havingExpression !== null && $expression->havingArgs !== []) {
7 ✔
122
                        $collection->queryBuilder->andHaving($expression->havingExpression, ...$expression->havingArgs);
7 ✔
123
                }
124
                $collection->filterGroupByColumns = $collection->mergeColumns($collection->filterGroupByColumns, $expression->groupBy);
7 ✔
125
                $collection->rebuildGroupBy();
7 ✔
126
                return $collection;
7 ✔
127
        }
128

129

130
        #[\NoDiscard('Method returns a new collection instance, the original collection is not modified.')]
131
        public function orderBy($expression, string $direction = ICollection::ASC): ICollection
132
        {
133
                $collection = clone $this;
7 ✔
134
                if (is_array($expression) && !isset($expression[0])) {
7 ✔
135
                        /** @var array<string, string> $expression */
136
                        $expression = $expression; // no-op for PHPStan
7 ✔
137

138
                        foreach ($expression as $subExpression => $subDirection) {
7 ✔
139
                                $collection->addOrderByExpression($subExpression, $subDirection);
7 ✔
140
                        }
141
                } else {
142
                        $collection->addOrderByExpression($expression, $direction);
7 ✔
143
                }
144
                return $collection;
7 ✔
145
        }
146

147

148
        #[\NoDiscard('Method returns a new collection instance, the original collection is not modified.')]
149
        public function resetOrderBy(): ICollection
150
        {
151
                $collection = clone $this;
7 ✔
152
                $collection->orderGroupByColumns = [];
7 ✔
153
                $collection->orderColumns = [];
7 ✔
154
                $collection->queryBuilder->orderBy();
7 ✔
155
                $collection->rebuildGroupBy();
7 ✔
156
                return $collection;
7 ✔
157
        }
158

159

160
        #[\NoDiscard('Method returns a new collection instance, the original collection is not modified.')]
161
        public function limitBy(int $limit, int|null $offset = null): ICollection
162
        {
163
                $collection = clone $this;
7 ✔
164
                $collection->queryBuilder->limitBy($limit, $offset);
7 ✔
165
                return $collection;
7 ✔
166
        }
167

168

169
        #[\NoDiscard]
170
        public function fetch(): IEntity|null
171
        {
172
                if ($this->fetchIterator === null) {
7 ✔
173
                        $this->fetchIterator = $this->getIterator();
7 ✔
174
                }
175

176
                if ($this->fetchIterator->valid()) {
7 ✔
177
                        $current = $this->fetchIterator->current();
7 ✔
178
                        $this->fetchIterator->next();
7 ✔
179
                        return $current;
7 ✔
180
                }
181

182
                return null;
7 ✔
183
        }
184

185

186
        #[\NoDiscard]
187
        public function fetchChecked(): IEntity
188
        {
189
                $entity = $this->fetch();
7 ✔
190
                if ($entity === null) {
7 ✔
191
                        throw new NoResultException();
7 ✔
192
                }
193
                return $entity;
7 ✔
194
        }
195

196

197
        #[\NoDiscard]
198
        public function fetchAll(): array
199
        {
200
                return iterator_to_array($this->getIterator(), preserve_keys: false);
7 ✔
201
        }
202

203

204
        #[\NoDiscard]
205
        public function fetchPairs(string|null $key = null, string|null $value = null): array
206
        {
207
                return FetchPairsHelper::process($this->getIterator(), $key, $value);
7 ✔
208
        }
209

210

211
        /**
212
         * @param mixed[] $args
213
         * @return never
214
         * @throws MemberAccessException
215
         */
216
        public function __call(string $name, array $args)
217
        {
NEW
218
                $class = static::class;
×
219
                throw new MemberAccessException("Call to undefined method $class::$name().");
×
220
        }
221

222

223
        /**
224
         * @return Iterator<int, E>
225
         */
226
        #[\NoDiscard]
227
        public function getIterator(): Iterator
228
        {
229
                if ($this->relationshipParent !== null && $this->relationshipMapper !== null) {
7 ✔
230
                        /** @var Iterator<E> $entityIterator */
231
                        $entityIterator = $this->relationshipMapper->getIterator($this->relationshipParent, $this);
7 ✔
232
                } else {
233
                        if ($this->result === null) {
7 ✔
234
                                $this->execute();
7 ✔
235
                        }
236

237
                        assert(is_array($this->result));
238
                        /** @var Iterator<E> $entityIterator */
239
                        $entityIterator = new EntityIterator($this->result);
7 ✔
240
                }
241

242
                if (!$this->entityFetchEventTriggered) {
7 ✔
243
                        foreach ($this->onEntityFetch as $entityFetchCallback) {
7 ✔
244
                                $entityFetchCallback($entityIterator);
7 ✔
245
                        }
246
                        $entityIterator->rewind();
7 ✔
247
                        $this->entityFetchEventTriggered = true;
7 ✔
248
                }
249

250
                return $entityIterator;
7 ✔
251
        }
252

253

254
        #[\NoDiscard]
255
        public function count(): int
256
        {
257
                return iterator_count($this->getIterator());
7 ✔
258
        }
259

260

261
        #[\NoDiscard]
262
        public function countStored(): int
263
        {
264
                if ($this->relationshipParent !== null && $this->relationshipMapper !== null) {
7 ✔
265
                        return $this->relationshipMapper->getIteratorCount($this->relationshipParent, $this);
7 ✔
266
                }
267

268
                return $this->getIteratorCount();
7 ✔
269
        }
270

271

272
        #[\NoDiscard]
273
        public function toMemoryCollection(): MemoryCollection
274
        {
275
                $collection = clone $this;
7 ✔
276
                $entities = $collection->fetchAll();
7 ✔
277
                return new ArrayCollection($entities, $this->mapper->getRepository());
7 ✔
278
        }
279

280

281
        public function setRelationshipMapper(IRelationshipMapper|null $mapper): ICollection
282
        {
283
                $this->relationshipMapper = $mapper;
7 ✔
284
                return $this;
7 ✔
285
        }
286

287

288
        #[\NoDiscard]
289
        public function getRelationshipMapper(): IRelationshipMapper|null
290
        {
291
                return $this->relationshipMapper;
7 ✔
292
        }
293

294

295
        #[\NoDiscard('Method returns a new collection instance, the original collection is not modified.')]
296
        public function setRelationshipParent(IEntity $parent): ICollection
297
        {
298
                $collection = clone $this;
7 ✔
299
                $collection->relationshipParent = $parent;
7 ✔
300
                return $collection;
7 ✔
301
        }
302

303

304
        public function subscribeOnEntityFetch(callable $callback): void
305
        {
306
                $this->onEntityFetch[] = $callback;
7 ✔
307
        }
7 ✔
308

309

310
        public function __clone()
311
        {
312
                $this->queryBuilder = clone $this->queryBuilder;
7 ✔
313
                $this->result = null;
7 ✔
314
                $this->resultCount = null;
7 ✔
315
                $this->fetchIterator = null;
7 ✔
316
                $this->entityFetchEventTriggered = false;
7 ✔
317
        }
7 ✔
318

319

320
        /**
321
         * Returns the live, mutable query builder backing this collection.
322
         *
323
         * Callers may further mutate the returned builder, therefore any already fetched result is discarded so that the
324
         * next fetch reflects the changes. Internal callers intentionally read {@see $queryBuilder} directly to avoid
325
         * invalidating an in-progress iteration.
326
         */
327
        #[\NoDiscard]
328
        public function getQueryBuilder(): QueryBuilder
329
        {
330
                $this->result = null;
7 ✔
331
                $this->resultCount = null;
7 ✔
332
                $this->fetchIterator = null;
7 ✔
333
                $this->entityFetchEventTriggered = false;
7 ✔
334
                return $this->queryBuilder;
7 ✔
335
        }
336

337

338
        protected function getIteratorCount(): int
339
        {
340
                if ($this->resultCount !== null) {
7 ✔
341
                        return $this->resultCount;
×
342
                }
343

344
                $builder = clone $this->queryBuilder;
7 ✔
345

346
                if ($this->connection->getPlatform()->getName() === SqlServerPlatform::NAME) {
7 ✔
347
                        if (!$builder->hasLimitOffsetClause()) {
7 ✔
348
                                $builder->orderBy();
7 ✔
349
                        }
350
                } else {
351
                        $builder->orderBy();
7 ✔
352
                }
353

354
                $select = $builder->getClause('select')[0];
7 ✔
355
                if (is_array($select) && count($select) === 1 && $select[0] === '%table.*') {
7 ✔
356
                        $builder->select();
7 ✔
357
                        foreach ($this->mapper->getConventions()->getStoragePrimaryKey() as $column) {
7 ✔
358
                                $builder->addSelect('%table.%column', $builder->getFromAlias(), $column);
7 ✔
359
                        }
360
                }
361
                $sql = 'SELECT COUNT(*) AS count FROM (' . $builder->getQuerySql() . ') temp';
7 ✔
362
                $args = $builder->getQueryParameters();
7 ✔
363

364
                $this->resultCount = $this->connection->queryArgs($sql, $args)->fetchField()
7 ✔
NEW
365
                        ?? throw new InvalidStateException('Unable to fetch collection count.');
×
366
                return $this->resultCount;
7 ✔
367
        }
368

369

370
        protected function execute(): void
371
        {
372
                $result = $this->connection->queryByQueryBuilder($this->queryBuilder);
7 ✔
373

374
                $this->result = [];
7 ✔
375
                while (($data = $result->fetch()) !== null) {
7 ✔
376
                        $entity = $this->mapper->hydrateEntity($data->toArray());
7 ✔
377
                        if ($entity === null) continue;
7 ✔
378
                        $this->result[] = $entity;
7 ✔
379
                }
380
        }
7 ✔
381

382

383
        protected function getHelper(): DbalQueryBuilderHelper
384
        {
385
                if ($this->helper === null) {
7 ✔
386
                        $repository = $this->mapper->getRepository();
7 ✔
387
                        $this->helper = new DbalQueryBuilderHelper($repository);
7 ✔
388
                }
389

390
                return $this->helper;
7 ✔
391
        }
392

393

394
        /**
395
         * @param array<mixed>|string $expression
396
         */
397
        private function addOrderByExpression(string|array $expression, string $direction): void
398
        {
399
                $expressionResult = $this->getHelper()->processExpression($this->queryBuilder, $expression, null);
7 ✔
400
                $this->applyExpressionJoins($expressionResult);
7 ✔
401

402
                $this->orderGroupByColumns = $this->mergeColumns($this->orderGroupByColumns, $expressionResult->groupBy);
7 ✔
403
                $this->orderColumns = $this->mergeColumns($this->orderColumns, $expressionResult->columns);
7 ✔
404
                $this->rebuildGroupBy();
7 ✔
405

406
                $orderByExpression = $this->getHelper()->processOrderDirection($expressionResult, $direction);
7 ✔
407
                $this->queryBuilder->addOrderBy('%ex', $orderByExpression);
7 ✔
408
        }
7 ✔
409

410

411
        /**
412
         * Merges the given columns into a keyed map (deduplicated by their unescaped Fqn), preserving order.
413
         *
414
         * @param array<string, Fqn> $target
415
         * @param list<Fqn> $columns
416
         * @return array<string, Fqn>
417
         */
418
        private function mergeColumns(array $target, array $columns): array
419
        {
420
                foreach ($columns as $fqn) {
7 ✔
421
                        $target[$fqn->getUnescaped()] ??= $fqn;
7 ✔
422
                }
423
                return $target;
7 ✔
424
        }
425

426

427
        /**
428
         * Rebuilds the whole GROUP BY clause from the tracked filtering and ordering columns.
429
         *
430
         * The clause is recomputed instead of mutated incrementally so that it does not depend on the order in which
431
         * findBy()/orderBy() were called, and so that resetOrderBy() can drop the ordering-induced columns again.
432
         * Order-by columns are added only when grouping is otherwise active, matching the SQL grouping requirements.
433
         */
434
        private function rebuildGroupBy(): void
435
        {
436
                $groupBy = $this->filterGroupByColumns + $this->orderGroupByColumns;
7 ✔
437
                if ($groupBy !== []) {
7 ✔
438
                        $groupBy += $this->orderColumns;
7 ✔
439
                }
440

441
                if ($groupBy === []) {
7 ✔
442
                        $this->queryBuilder->groupBy();
7 ✔
443
                        return;
7 ✔
444
                }
445

446
                $this->queryBuilder->groupBy('%column[]', array_values($groupBy));
7 ✔
447

448
                if ($this->mapper->getDatabasePlatform()->getName() === MySqlPlatform::NAME) {
7 ✔
449
                        $this->applyGroupByWithSameNamedColumnsWorkaround($this->queryBuilder, array_values($groupBy));
7 ✔
450
                }
451
        }
7 ✔
452

453

454
        private function applyExpressionJoins(DbalExpressionResult $expression): void
455
        {
456
                $mergedJoins = $this->getHelper()->mergeJoins('%and', $expression->joins);
7 ✔
457
                foreach ($mergedJoins as $join) {
7 ✔
458
                        $join->applyJoin($this->queryBuilder);
7 ✔
459
                }
460
        }
7 ✔
461

462

463
        /**
464
         * Apply workaround for MySQL that is not able to properly resolve columns when there are more same-named
465
         * columns in the GROUP BY clause, even though they are properly referenced to their tables. Orm workarounds
466
         * this by adding them to the SELECT clause and renames them not to conflict anywhere.
467
         *
468
         * @param list<Fqn> $groupBy
469
         */
470
        private function applyGroupByWithSameNamedColumnsWorkaround(QueryBuilder $queryBuilder, array $groupBy): void
471
        {
472
                $map = [];
7 ✔
473
                foreach ($groupBy as $fqn) {
7 ✔
474
                        $map[$fqn->name][$fqn->getUnescaped()] = $fqn;
7 ✔
475
                }
476

477
                foreach ($map as $fqns) {
7 ✔
478
                        if (count($fqns) > 1) {
7 ✔
479
                                foreach ($fqns as $key => $fqn) {
×
480
                                        if (isset($this->mysqlGroupByWorkaroundApplied[$key])) {
×
481
                                                continue;
×
482
                                        }
483

NEW
484
                                        $queryBuilder->addSelect('%column AS __nextras_fix_' . count($this->mysqlGroupByWorkaroundApplied), $fqn); // @phpstan-ignore-line
×
485
                                        $this->mysqlGroupByWorkaroundApplied[$key] = true;
×
486
                                }
487
                        }
488
                }
489
        }
7 ✔
490
}
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