-
-
Notifications
You must be signed in to change notification settings - Fork 138
/
Result.php
621 lines (495 loc) · 12.6 KB
/
Result.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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
<?php
/**
* This file is part of the Dibi, smart database abstraction layer (https://dibiphp.com)
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Dibi;
/**
* Query result.
*
* @property-read int $rowCount
*/
class Result implements IDataSource
{
private ?Drivers\Result $driver;
/** Translate table */
private array $types = [];
private ?Reflection\Result $meta;
/** Already fetched? Used for allowance for first seek(0) */
private bool $fetched = false;
/** returned object class */
private ?string $rowClass = Row::class;
/** @var callable|null returned object factory */
private $rowFactory;
private array $formats = [];
public function __construct(Drivers\Result $driver, bool $normalize = true)
{
$this->driver = $driver;
if ($normalize) {
$this->detectTypes();
}
}
/**
* Frees the resources allocated for this result set.
*/
final public function free(): void
{
if ($this->driver !== null) {
$this->driver->free();
$this->driver = $this->meta = null;
}
}
/**
* Safe access to property $driver.
* @throws \RuntimeException
*/
final public function getResultDriver(): Drivers\Result
{
if ($this->driver === null) {
throw new \RuntimeException('Result-set was released from memory.');
}
return $this->driver;
}
/********************* rows ****************d*g**/
/**
* Moves cursor position without fetching row.
* @throws Exception
*/
final public function seek(int $row): bool
{
return ($row !== 0 || $this->fetched)
? $this->getResultDriver()->seek($row)
: true;
}
/**
* Required by the Countable interface.
*/
final public function count(): int
{
return $this->getResultDriver()->getRowCount();
}
/**
* Returns the number of rows in a result set.
*/
final public function getRowCount(): int
{
return $this->getResultDriver()->getRowCount();
}
/**
* Required by the IteratorAggregate interface.
*/
final public function getIterator(): ResultIterator
{
return new ResultIterator($this);
}
/**
* Returns the number of columns in a result set.
*/
final public function getColumnCount(): int
{
return count($this->types);
}
/********************* fetching rows ****************d*g**/
/**
* Set fetched object class. This class should extend the Row class.
*/
public function setRowClass(?string $class): static
{
$this->rowClass = $class;
return $this;
}
/**
* Returns fetched object class name.
*/
public function getRowClass(): ?string
{
return $this->rowClass;
}
/**
* Set a factory to create fetched object instances. These should extend the Row class.
*/
public function setRowFactory(callable $callback): static
{
$this->rowFactory = $callback;
return $this;
}
/**
* Fetches the row at current position, process optional type conversion.
* and moves the internal cursor to the next position
*/
final public function fetch(): mixed
{
$row = $this->getResultDriver()->fetch(true);
if ($row === null) {
return null;
}
$this->fetched = true;
$this->normalize($row);
if ($this->rowFactory) {
return ($this->rowFactory)($row);
} elseif ($this->rowClass) {
return new $this->rowClass($row);
}
return $row;
}
/**
* Like fetch(), but returns only first field.
* Returns value on success, null if no next record
*/
final public function fetchSingle(): mixed
{
$row = $this->getResultDriver()->fetch(true);
if ($row === null) {
return null;
}
$this->fetched = true;
$this->normalize($row);
return reset($row);
}
/**
* Fetches all records from table.
* @return Row[]|array[]
*/
final public function fetchAll(?int $offset = null, ?int $limit = null): array
{
$limit ??= -1;
$this->seek($offset ?: 0);
$row = $this->fetch();
if (!$row) {
return []; // empty result set
}
$data = [];
do {
if ($limit === 0) {
break;
}
$limit--;
$data[] = $row;
} while ($row = $this->fetch());
return $data;
}
/**
* Fetches all records from table and returns associative tree.
* Examples:
* - associative descriptor: col1[]col2->col3
* builds a tree: $tree[$val1][$index][$val2]->col3[$val3] = {record}
* - associative descriptor: col1|col2->col3=col4
* builds a tree: $tree[$val1][$val2]->col3[$val3] = val4
* @throws \InvalidArgumentException
*/
final public function fetchAssoc(string $assoc): array
{
if (str_contains($assoc, ',')) {
return $this->oldFetchAssoc($assoc);
}
$this->seek(0);
$row = $this->fetch();
if (!$row) {
return []; // empty result set
}
$data = null;
$assoc = preg_split('#(\[\]|->|=|\|)#', $assoc, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
if (!$assoc) {
throw new \InvalidArgumentException("Invalid descriptor '$assoc'.");
}
// check columns
foreach ($assoc as $as) {
// offsetExists ignores null in PHP 5.2.1, isset() surprisingly null accepts
if ($as !== '[]' && $as !== '=' && $as !== '->' && $as !== '|' && !property_exists($row, $as)) {
throw new \InvalidArgumentException("Unknown column '$as' in associative descriptor.");
}
}
if ($as === '->') { // must not be last
array_pop($assoc);
}
if (empty($assoc)) {
$assoc[] = '[]';
}
// make associative tree
do {
$x = &$data;
// iterative deepening
foreach ($assoc as $i => $as) {
if ($as === '[]') { // indexed-array node
$x = &$x[];
} elseif ($as === '=') { // "value" node
$x = $row->{$assoc[$i + 1]};
continue 2;
} elseif ($as === '->') { // "object" node
if ($x === null) {
$x = clone $row;
$x = &$x->{$assoc[$i + 1]};
$x = null; // prepare child node
} else {
$x = &$x->{$assoc[$i + 1]};
}
} elseif ($as !== '|') { // associative-array node
$x = &$x[(string) $row->$as];
}
}
if ($x === null) { // build leaf
$x = $row;
}
} while ($row = $this->fetch());
unset($x);
/** @var mixed[] $data */
return $data;
}
/** @deprecated */
private function oldFetchAssoc(string $assoc)
{
$this->seek(0);
$row = $this->fetch();
if (!$row) {
return []; // empty result set
}
$data = null;
$assoc = explode(',', $assoc);
// strip leading = and @
$leaf = '@'; // gap
$last = count($assoc) - 1;
while ($assoc[$last] === '=' || $assoc[$last] === '@') {
$leaf = $assoc[$last];
unset($assoc[$last]);
$last--;
if ($last < 0) {
$assoc[] = '#';
break;
}
}
do {
$x = &$data;
foreach ($assoc as $i => $as) {
if ($as === '#') { // indexed-array node
$x = &$x[];
} elseif ($as === '=') { // "record" node
if ($x === null) {
$x = $row->toArray();
$x = &$x[$assoc[$i + 1]];
$x = null; // prepare child node
} else {
$x = &$x[$assoc[$i + 1]];
}
} elseif ($as === '@') { // "object" node
if ($x === null) {
$x = clone $row;
$x = &$x->{$assoc[$i + 1]};
$x = null; // prepare child node
} else {
$x = &$x->{$assoc[$i + 1]};
}
} else { // associative-array node
$x = &$x[(string) $row->$as];
}
}
if ($x === null) { // build leaf
$x = $leaf === '='
? $row->toArray()
: $row;
}
} while ($row = $this->fetch());
unset($x);
return $data;
}
/**
* Fetches all records from table like $key => $value pairs.
* @throws \InvalidArgumentException
*/
final public function fetchPairs(?string $key = null, ?string $value = null): array
{
$this->seek(0);
$row = $this->fetch();
if (!$row) {
return []; // empty result set
}
$data = [];
if ($value === null) {
if ($key !== null) {
throw new \InvalidArgumentException('Either none or both columns must be specified.');
}
// autodetect
$tmp = array_keys($row->toArray());
$key = $tmp[0];
if (count($row) < 2) { // indexed-array
do {
$data[] = $row[$key];
} while ($row = $this->fetch());
return $data;
}
$value = $tmp[1];
} else {
if (!property_exists($row, $value)) {
throw new \InvalidArgumentException("Unknown value column '$value'.");
}
if ($key === null) { // indexed-array
do {
$data[] = $row[$value];
} while ($row = $this->fetch());
return $data;
}
if (!property_exists($row, $key)) {
throw new \InvalidArgumentException("Unknown key column '$key'.");
}
}
do {
$data[(string) $row[$key]] = $row[$value];
} while ($row = $this->fetch());
return $data;
}
/********************* column types ****************d*g**/
/**
* Autodetect column types.
*/
private function detectTypes(): void
{
$cache = Helpers::getTypeCache();
try {
foreach ($this->getResultDriver()->getResultColumns() as $col) {
$this->types[$col['name']] = $col['type'] ?? $cache->{$col['nativetype']};
}
} catch (NotSupportedException $e) {
}
}
/**
* Converts values to specified type and format.
*/
private function normalize(array &$row): void
{
foreach ($this->types as $key => $type) {
if (!isset($row[$key])) { // null
continue;
}
$value = $row[$key];
$format = $this->formats[$type] ?? null;
if ($type === null || $format === 'native') {
$row[$key] = $value;
} elseif ($type === Type::Text) {
$row[$key] = (string) $value;
} elseif ($type === Type::Integer) {
$row[$key] = is_float($tmp = $value * 1)
? (is_string($value) ? $value : (int) $value)
: $tmp;
} elseif ($type === Type::Float) {
if (!is_string($value)) {
$row[$key] = (float) $value;
continue;
}
$negative = ($value[0] ?? null) === '-';
$value = ltrim($value, '0-');
$p = strpos($value, '.');
$e = strpos($value, 'e');
if ($p !== false && $e === false) {
$value = rtrim(rtrim($value, '0'), '.');
} elseif ($p !== false && $e !== false) {
$value = rtrim($value, '.');
}
if ($value === '' || $value[0] === '.') {
$value = '0' . $value;
}
if ($negative) {
$value = '-' . $value;
}
$row[$key] = $value === str_replace(',', '.', (string) ($float = (float) $value))
? $float
: $value;
} elseif ($type === Type::Bool) {
$row[$key] = ((bool) $value) && $value !== 'f' && $value !== 'F';
} elseif ($type === Type::DateTime || $type === Type::Date || $type === Type::Time) {
if ($value && !str_starts_with((string) $value, '0000-00')) { // '', null, false, '0000-00-00', ...
$value = new DateTime($value);
$row[$key] = $format ? $value->format($format) : $value;
} else {
$row[$key] = null;
}
} elseif ($type === Type::TimeInterval) {
preg_match('#^(-?)(\d+)\D(\d+)\D(\d+)\z#', $value, $m);
$value = new \DateInterval("PT$m[2]H$m[3]M$m[4]S");
$value->invert = (int) (bool) $m[1];
$row[$key] = $format ? $value->format($format) : $value;
} elseif ($type === Type::Binary) {
$row[$key] = is_string($value)
? $this->getResultDriver()->unescapeBinary($value)
: $value;
} elseif ($type === Type::JSON) {
if ($format === 'string') { // back compatibility with 'native'
$row[$key] = $value;
} else {
$row[$key] = json_decode($value, $format === 'array');
}
} else {
throw new \RuntimeException('Unexpected type ' . $type);
}
}
}
/**
* Define column type.
* @param string|null $type use constant Type::*
*/
final public function setType(string $column, ?string $type): static
{
$this->types[$column] = $type;
return $this;
}
/**
* Returns column type.
*/
final public function getType(string $column): ?string
{
return $this->types[$column] ?? null;
}
/**
* Returns columns type.
*/
final public function getTypes(): array
{
return $this->types;
}
/**
* Sets type format.
*/
final public function setFormat(string $type, ?string $format): static
{
$this->formats[$type] = $format;
return $this;
}
/**
* Sets type formats.
*/
final public function setFormats(array $formats): static
{
$this->formats = $formats;
return $this;
}
/**
* Returns data format.
*/
final public function getFormat(string $type): ?string
{
return $this->formats[$type] ?? null;
}
/********************* meta info ****************d*g**/
/**
* Returns a meta information about the current result set.
*/
public function getInfo(): Reflection\Result
{
if (!isset($this->meta)) {
$this->meta = new Reflection\Result($this->getResultDriver());
}
return $this->meta;
}
/** @return Reflection\Column[] */
final public function getColumns(): array
{
return $this->getInfo()->getColumns();
}
/********************* misc tools ****************d*g**/
/**
* Displays complete result set as HTML or text table for debug purposes.
*/
final public function dump(): void
{
echo Helpers::dump($this);
}
}