-
Notifications
You must be signed in to change notification settings - Fork 18
/
ResultSet.php
560 lines (487 loc) · 14.9 KB
/
ResultSet.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\ORM;
use Cake\Collection\Collection;
use Cake\Collection\CollectionTrait;
use Cake\Database\Exception\DatabaseException;
use Cake\Database\StatementInterface;
use Cake\Datasource\EntityInterface;
use Cake\Datasource\ResultSetInterface;
use SplFixedArray;
/**
* Represents the results obtained after executing a query for a specific table
* This object is responsible for correctly nesting result keys reported from
* the query, casting each field to the correct type and executing the extra
* queries required for eager loading external associations.
*/
class ResultSet implements ResultSetInterface
{
use CollectionTrait;
/**
* Database statement holding the results
*
* @var \Cake\Database\StatementInterface
*/
protected $_statement;
/**
* Points to the next record number that should be fetched
*
* @var int
*/
protected $_index = 0;
/**
* Last record fetched from the statement
*
* @var array|object
*/
protected $_current;
/**
* Default table instance
*
* @var \Cake\ORM\Table
*/
protected $_defaultTable;
/**
* The default table alias
*
* @var string
*/
protected $_defaultAlias;
/**
* List of associations that should be placed under the `_matchingData`
* result key.
*
* @var array
*/
protected $_matchingMap = [];
/**
* List of associations that should be eager loaded.
*
* @var array
*/
protected $_containMap = [];
/**
* Map of fields that are fetched from the statement with
* their type and the table they belong to
*
* @var array
*/
protected $_map = [];
/**
* List of matching associations and the column keys to expect
* from each of them.
*
* @var array
*/
protected $_matchingMapColumns = [];
/**
* Results that have been fetched or hydrated into the results.
*
* @var array|\SplFixedArray
*/
protected $_results = [];
/**
* Whether to hydrate results into objects or not
*
* @var bool
*/
protected $_hydrate = true;
/**
* Tracks value of $_autoFields property of $query passed to constructor.
*
* @var bool|null
*/
protected $_autoFields;
/**
* The fully namespaced name of the class to use for hydrating results
*
* @var string
*/
protected $_entityClass;
/**
* Whether or not to buffer results fetched from the statement
*
* @var bool
*/
protected $_useBuffering = true;
/**
* Holds the count of records in this result set
*
* @var int
*/
protected $_count;
/**
* The Database driver object.
*
* Cached in a property to avoid multiple calls to the same function.
*
* @var \Cake\Database\DriverInterface
*/
protected $_driver;
/**
* Constructor
*
* @param \Cake\ORM\Query $query Query from where results come
* @param \Cake\Database\StatementInterface $statement The statement to fetch from
*/
public function __construct(Query $query, StatementInterface $statement)
{
$repository = $query->getRepository();
$this->_statement = $statement;
$this->_driver = $query->getConnection()->getDriver();
$this->_defaultTable = $repository;
$this->_calculateAssociationMap($query);
$this->_hydrate = $query->isHydrationEnabled();
$this->_entityClass = $repository->getEntityClass();
$this->_useBuffering = $query->isBufferedResultsEnabled();
$this->_defaultAlias = $this->_defaultTable->getAlias();
$this->_calculateColumnMap($query);
$this->_autoFields = $query->isAutoFieldsEnabled();
if ($this->_useBuffering) {
$count = $this->count();
$this->_results = new SplFixedArray($count);
}
}
/**
* Returns the current record in the result iterator
*
* Part of Iterator interface.
*
* @return array|object
*/
public function current()
{
return $this->_current;
}
/**
* Returns the key of the current record in the iterator
*
* Part of Iterator interface.
*
* @return int
*/
public function key(): int
{
return $this->_index;
}
/**
* Advances the iterator pointer to the next record
*
* Part of Iterator interface.
*
* @return void
*/
public function next(): void
{
$this->_index++;
}
/**
* Rewinds a ResultSet.
*
* Part of Iterator interface.
*
* @throws \Cake\Database\Exception\DatabaseException
* @return void
*/
public function rewind(): void
{
if ($this->_index === 0) {
return;
}
if (!$this->_useBuffering) {
$msg = 'You cannot rewind an un-buffered ResultSet. '
. 'Use Query::bufferResults() to get a buffered ResultSet.';
throw new DatabaseException($msg);
}
$this->_index = 0;
}
/**
* Whether there are more results to be fetched from the iterator
*
* Part of Iterator interface.
*
* @return bool
*/
public function valid(): bool
{
if ($this->_useBuffering) {
$valid = $this->_index < $this->_count;
if ($valid && $this->_results[$this->_index] !== null) {
$this->_current = $this->_results[$this->_index];
return true;
}
if (!$valid) {
return $valid;
}
}
$this->_current = $this->_fetchResult();
$valid = $this->_current !== false;
if ($valid && $this->_useBuffering) {
$this->_results[$this->_index] = $this->_current;
}
if (!$valid && $this->_statement !== null) {
$this->_statement->closeCursor();
}
return $valid;
}
/**
* Get the first record from a result set.
*
* This method will also close the underlying statement cursor.
*
* @return array|object|null
*/
public function first()
{
foreach ($this as $result) {
if ($this->_statement !== null && !$this->_useBuffering) {
$this->_statement->closeCursor();
}
return $result;
}
return null;
}
/**
* Serializes a resultset.
*
* Part of Serializable interface.
*
* @return string Serialized object
*/
public function serialize(): string
{
if (!$this->_useBuffering) {
$msg = 'You cannot serialize an un-buffered ResultSet. '
. 'Use Query::bufferResults() to get a buffered ResultSet.';
throw new DatabaseException($msg);
}
while ($this->valid()) {
$this->next();
}
if ($this->_results instanceof SplFixedArray) {
return serialize($this->_results->toArray());
}
return serialize($this->_results);
}
/**
* Unserializes a resultset.
*
* Part of Serializable interface.
*
* @param string $serialized Serialized object
* @return void
*/
public function unserialize($serialized)
{
$results = (array)(unserialize($serialized) ?: []);
$this->_results = SplFixedArray::fromArray($results);
$this->_useBuffering = true;
$this->_count = $this->_results->count();
}
/**
* Gives the number of rows in the result set.
*
* Part of the Countable interface.
*
* @return int
*/
public function count(): int
{
if ($this->_count !== null) {
return $this->_count;
}
if ($this->_statement !== null) {
return $this->_count = $this->_statement->rowCount();
}
if ($this->_results instanceof SplFixedArray) {
$this->_count = $this->_results->count();
} else {
$this->_count = count($this->_results);
}
return $this->_count;
}
/**
* Calculates the list of associations that should get eager loaded
* when fetching each record
*
* @param \Cake\ORM\Query $query The query from where to derive the associations
* @return void
*/
protected function _calculateAssociationMap(Query $query): void
{
$map = $query->getEagerLoader()->associationsMap($this->_defaultTable);
$this->_matchingMap = (new Collection($map))
->match(['matching' => true])
->indexBy('alias')
->toArray();
$this->_containMap = (new Collection(array_reverse($map)))
->match(['matching' => false])
->indexBy('nestKey')
->toArray();
}
/**
* Creates a map of row keys out of the query select clause that can be
* used to hydrate nested result sets more quickly.
*
* @param \Cake\ORM\Query $query The query from where to derive the column map
* @return void
*/
protected function _calculateColumnMap(Query $query): void
{
$map = [];
foreach ($query->clause('select') as $key => $field) {
$key = trim($key, '"`[]');
if (strpos($key, '__') <= 0) {
$map[$this->_defaultAlias][$key] = $key;
continue;
}
$parts = explode('__', $key, 2);
$map[$parts[0]][$key] = $parts[1];
}
foreach ($this->_matchingMap as $alias => $assoc) {
if (!isset($map[$alias])) {
continue;
}
$this->_matchingMapColumns[$alias] = $map[$alias];
unset($map[$alias]);
}
$this->_map = $map;
}
/**
* Helper function to fetch the next result from the statement or
* seeded results.
*
* @return mixed
*/
protected function _fetchResult()
{
if ($this->_statement === null) {
return false;
}
$row = $this->_statement->fetch('assoc');
if ($row === false) {
return $row;
}
return $this->_groupResult($row);
}
/**
* Correctly nests results keys including those coming from associations
*
* @param array $row Array containing columns and values or false if there is no results
* @return array|\Cake\Datasource\EntityInterface Results
*/
protected function _groupResult(array $row)
{
$defaultAlias = $this->_defaultAlias;
$results = $presentAliases = [];
$options = [
'useSetters' => false,
'markClean' => true,
'markNew' => false,
'guard' => false,
];
foreach ($this->_matchingMapColumns as $alias => $keys) {
$matching = $this->_matchingMap[$alias];
$results['_matchingData'][$alias] = array_combine(
$keys,
array_intersect_key($row, $keys)
);
if ($this->_hydrate) {
/** @var \Cake\ORM\Table $table */
$table = $matching['instance'];
$options['source'] = $table->getRegistryAlias();
/** @var \Cake\Datasource\EntityInterface $entity */
$entity = new $matching['entityClass']($results['_matchingData'][$alias], $options);
$results['_matchingData'][$alias] = $entity;
}
}
foreach ($this->_map as $table => $keys) {
$results[$table] = array_combine($keys, array_intersect_key($row, $keys));
$presentAliases[$table] = true;
}
// If the default table is not in the results, set
// it to an empty array so that any contained
// associations hydrate correctly.
if (!isset($results[$defaultAlias])) {
$results[$defaultAlias] = [];
}
unset($presentAliases[$defaultAlias]);
foreach ($this->_containMap as $assoc) {
$alias = $assoc['nestKey'];
if ($assoc['canBeJoined'] && empty($this->_map[$alias])) {
continue;
}
/** @var \Cake\ORM\Association $instance */
$instance = $assoc['instance'];
if (!$assoc['canBeJoined'] && !isset($row[$alias])) {
$results = $instance->defaultRowValue($results, $assoc['canBeJoined']);
continue;
}
if (!$assoc['canBeJoined']) {
$results[$alias] = $row[$alias];
}
$target = $instance->getTarget();
$options['source'] = $target->getRegistryAlias();
unset($presentAliases[$alias]);
if ($assoc['canBeJoined'] && $this->_autoFields !== false) {
$hasData = false;
foreach ($results[$alias] as $v) {
if ($v !== null && $v !== []) {
$hasData = true;
break;
}
}
if (!$hasData) {
$results[$alias] = null;
}
}
if ($this->_hydrate && $results[$alias] !== null && $assoc['canBeJoined']) {
$entity = new $assoc['entityClass']($results[$alias], $options);
$results[$alias] = $entity;
}
$results = $instance->transformRow($results, $alias, $assoc['canBeJoined'], $assoc['targetProperty']);
}
foreach ($presentAliases as $alias => $present) {
if (!isset($results[$alias])) {
continue;
}
$results[$defaultAlias][$alias] = $results[$alias];
}
if (isset($results['_matchingData'])) {
$results[$defaultAlias]['_matchingData'] = $results['_matchingData'];
}
$options['source'] = $this->_defaultTable->getRegistryAlias();
if (isset($results[$defaultAlias])) {
$results = $results[$defaultAlias];
}
if ($this->_hydrate && !($results instanceof EntityInterface)) {
$results = new $this->_entityClass($results, $options);
}
return $results;
}
/**
* Returns an array that can be used to describe the internal state of this
* object.
*
* @return array
*/
public function __debugInfo()
{
return [
'items' => $this->toArray(),
];
}
}