-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathArray_.php
507 lines (417 loc) · 15.5 KB
/
Array_.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
<?php
declare(strict_types=1);
namespace Atk4\Data\Persistence;
use Atk4\Data\Exception;
use Atk4\Data\Field;
use Atk4\Data\Model;
use Atk4\Data\Persistence;
use Atk4\Data\Persistence\Array_\Action;
use Atk4\Data\Persistence\Array_\Action\RenameColumnIterator;
use Atk4\Data\Persistence\Array_\Db\Row;
use Atk4\Data\Persistence\Array_\Db\Table;
/**
* Implements persistence driver that can save data into array and load
* from array. This basic driver only offers the load/save support based
* around ID, you can't use conditions, order or limit.
*/
class Array_ extends Persistence
{
/** @var array<string, array<int|string, mixed>> */
private $seedData;
/** @var array<string, Table> */
private $data;
/** @var array<string, int> */
protected $maxSeenIdByTable = [];
/** @var array<string, int|string> */
protected $lastInsertIdByTable = [];
/** @var string */
protected $lastInsertIdTable;
/**
* @param array<int|string, mixed> $data
*/
public function __construct(array $data = [])
{
$this->seedData = $data;
// if there is no model table specified, then create fake one named 'data'
// and put all persistence data in there 1/2
if (count($this->seedData) > 0 && !isset($this->seedData['data'])) {
$rowSample = reset($this->seedData);
if (is_array($rowSample) && $rowSample !== [] && !is_array(reset($rowSample))) {
$this->seedData = ['data' => $this->seedData];
}
}
}
private function seedData(Model $model): void
{
$tableName = $model->table;
if (isset($this->data[$tableName])) {
return;
}
$this->data[$tableName] = new Table($tableName);
if (isset($this->seedData[$tableName])) {
$rows = $this->seedData[$tableName];
unset($this->seedData[$tableName]);
foreach ($rows as $id => $row) {
$this->saveRow($model, $row, $id);
}
}
// for array persistence join which accept table directly (without model initialization)
foreach ($model->getFields() as $field) {
if ($field->hasJoin()) {
$join = $field->getJoin();
$joinTableName = \Closure::bind(function () use ($join) {
return $join->foreignTable;
}, null, Array_\Join::class)();
if (isset($this->seedData[$joinTableName])) {
$dummyJoinModel = new Model($this, ['table' => $joinTableName]);
$dummyJoinModel->setPersistence($this);
}
}
}
}
private function seedDataAndGetTable(Model $model): Table
{
$this->seedData($model);
return $this->data[$model->table];
}
/**
* @return array<mixed, array<string, mixed>>
*
* @deprecated TODO temporary for these:
* - https://github.com/atk4/data/blob/90ab68ac063b8fc2c72dcd66115f1bd3f70a3a92/src/Reference/ContainsOne.php#L119
* - https://github.com/atk4/data/blob/90ab68ac063b8fc2c72dcd66115f1bd3f70a3a92/src/Reference/ContainsMany.php#L66
* remove once fixed/no longer needed
*/
public function getRawDataByTable(Model $model, string $table): array
{
if (!is_object($model->table)) {
$this->seedData($model);
}
$rows = [];
foreach ($this->data[$table]->getRows() as $row) {
$rows[$row->getValue($model->idField)] = $row->getData();
}
return $rows;
}
/**
* @param int|string|null $idFromRow
* @param int|string $id
*/
private function assertNoIdMismatch(Model $model, $idFromRow, $id): void
{
if ($idFromRow !== null && !$model->getField($model->idField)->compare($idFromRow, $id)) {
throw (new Exception('Row constains ID column, but it does not match the row ID'))
->addMoreInfo('idFromKey', $id)
->addMoreInfo('idFromData', $idFromRow);
}
}
/**
* @param array<string, mixed> $rowData
* @param mixed $id
*/
private function saveRow(Model $model, array $rowData, $id): void
{
if ($model->idField) {
$idField = $model->getField($model->idField);
$id = $idField->normalize($id);
$idColumnName = $idField->getPersistenceName();
if (array_key_exists($idColumnName, $rowData)) {
$this->assertNoIdMismatch($model, $rowData[$idColumnName], $id);
unset($rowData[$idColumnName]);
}
$rowData = [$idColumnName => $id] + $rowData;
}
if ($id > ($this->maxSeenIdByTable[$model->table] ?? 0)) {
$this->maxSeenIdByTable[$model->table] = $id;
}
$table = $this->data[$model->table];
$row = $table->getRowById($model, $id);
if ($row !== null) {
foreach (array_keys($rowData) as $columnName) {
if (!$table->hasColumnName($columnName)) {
$table->addColumnName($columnName);
}
}
$row->updateValues($rowData);
} else {
$row = $table->addRow(Row::class, $rowData);
}
}
/**
* @param array<string, mixed> $defaults
*/
public function add(Model $model, array $defaults = []): void
{
$defaults = array_merge([
'_defaultSeedJoin' => [Array_\Join::class],
], $defaults);
parent::add($model, $defaults);
// if there is no model table specified, then create fake one named 'data'
// and put all persistence data in there 2/2
if (!$model->table) {
$model->table = 'data';
}
if ($model->idField) {
$f = $model->getField($model->idField);
if ($f->type === null) {
$f->type = 'integer';
}
}
if (!is_object($model->table)) {
$this->seedData($model);
}
}
/**
* @return array<string, string>
*/
private function getPersistenceNameToNameMap(Model $model): array
{
return array_flip(array_map(fn (Field $f) => $f->getPersistenceName(), $model->getFields()));
}
/**
* @param array<string, mixed> $rowDataRaw
*
* @return array<string, mixed>
*/
private function filterRowDataOnlyModelFields(Model $model, array $rowDataRaw): array
{
return array_intersect_key($rowDataRaw, $this->getPersistenceNameToNameMap($model));
}
/**
* @param array<string, mixed> $row
*
* @return array<string, mixed>
*/
private function remapLoadRow(Model $model, array $row): array
{
$rowRemapped = [];
$map = $this->getPersistenceNameToNameMap($model);
foreach ($row as $k => $v) {
$rowRemapped[$map[$k]] = $v;
}
return $rowRemapped;
}
public function tryLoad(Model $model, $id): ?array
{
$model->assertIsModel();
if ($id === self::ID_LOAD_ONE || $id === self::ID_LOAD_ANY) {
$action = $this->action($model, 'select');
$action->limit($id === self::ID_LOAD_ANY ? 1 : 2);
$rowsRaw = $action->getRows();
if (count($rowsRaw) === 0) {
return null;
} elseif (count($rowsRaw) !== 1) {
throw (new Exception('Ambiguous conditions, more than one record can be loaded'))
->addMoreInfo('model', $model)
->addMoreInfo('id', null);
}
$idRaw = reset($rowsRaw)[$model->idField];
$row = $this->tryLoad($model, $idRaw);
return $row;
}
if (is_object($model->table)) {
$action = $this->action($model, 'select');
$condition = new Model\Scope\Condition('', $id);
$condition->key = $model->getField($model->idField);
$condition->setOwner($model->createEntity()); // TODO needed for typecasting to apply
$action->filter($condition);
$rowData = $action->getRow();
if ($rowData === null) {
return null;
}
} else {
$table = $this->seedDataAndGetTable($model);
$row = $table->getRowById($model, $id);
if ($row === null) {
return null;
}
$rowData = $this->remapLoadRow($model, $this->filterRowDataOnlyModelFields($model, $row->getData()));
}
return $this->typecastLoadRow($model, $rowData);
}
protected function insertRaw(Model $model, array $dataRaw)
{
$this->seedData($model);
$idRaw = $dataRaw[$model->idField] ?? $this->generateNewId($model);
$this->saveRow($model, $dataRaw, $idRaw);
return $idRaw;
}
protected function updateRaw(Model $model, $idRaw, array $dataRaw): void
{
$table = $this->seedDataAndGetTable($model);
$this->saveRow($model, array_merge($this->filterRowDataOnlyModelFields($model, $table->getRowById($model, $idRaw)->getData()), $dataRaw), $idRaw);
}
protected function deleteRaw(Model $model, $idRaw): void
{
$table = $this->seedDataAndGetTable($model);
$table->deleteRow($table->getRowById($model, $idRaw));
}
/**
* Generates new record ID.
*
* @return string
*/
public function generateNewId(Model $model)
{
$this->seedData($model);
$type = $model->idField ? $model->getField($model->idField)->type : 'integer';
switch ($type) {
case 'integer':
$nextId = ($this->maxSeenIdByTable[$model->table] ?? 0) + 1;
$this->maxSeenIdByTable[$model->table] = $nextId;
break;
case 'string':
$nextId = uniqid();
break;
default:
throw (new Exception('Unsupported id field type. Array supports type=integer or type=string only'))
->addMoreInfo('type', $type);
}
$this->lastInsertIdByTable[$model->table] = $nextId;
$this->lastInsertIdTable = $model->table;
return $nextId;
}
/**
* Last ID inserted.
*
* @return mixed
*/
public function lastInsertId(Model $model = null)
{
if ($model) {
return $this->lastInsertIdByTable[$model->table] ?? null;
}
return $this->lastInsertIdByTable[$this->lastInsertIdTable] ?? null;
}
/**
* @return \Traversable<array<string, mixed>>
*/
public function prepareIterator(Model $model): \Traversable
{
return $model->action('select')->generator; // @phpstan-ignore-line
}
/**
* Export all DataSet.
*
* @param array<int, string>|null $fields
*
* @return array<int, array<string, mixed>>
*/
public function export(Model $model, array $fields = null, bool $typecast = true): array
{
$data = $model->action('select', [$fields])->getRows();
if ($typecast) {
$data = array_map(function (array $row) use ($model) {
return $this->typecastLoadRow($model, $row);
}, $data);
}
return $data;
}
/**
* Typecast data and return Action of data array.
*
* @param array<int, string>|null $fields
*/
public function initAction(Model $model, array $fields = null): Action
{
if (is_object($model->table)) {
$tableAction = $this->action($model->table, 'select');
$rows = $tableAction->getRows();
} else {
$table = $this->seedDataAndGetTable($model);
$rows = [];
foreach ($table->getRows() as $row) {
$rows[$row->getValue($model->getField($model->idField)->getPersistenceName())] = $row->getData();
}
}
foreach ($rows as $rowIndex => $row) {
$rows[$rowIndex] = $this->remapLoadRow($model, $this->filterRowDataOnlyModelFields($model, $row));
}
if ($fields !== null) {
$rows = array_map(function (array $row) use ($fields) {
return array_intersect_key($row, array_flip($fields));
}, $rows);
}
return new Action($rows);
}
/**
* Will set limit defined inside $model onto Action.
*/
protected function setLimitOrder(Model $model, Action $action): void
{
// first order by
if (count($model->order) > 0) {
$action->order($model->order);
}
// then set limit
if ($model->limit[0] !== null || $model->limit[1] !== 0) {
$action->limit($model->limit[0] ?? \PHP_INT_MAX, $model->limit[1]);
}
}
/**
* Will apply conditions defined inside $model onto Action.
*/
protected function applyScope(Model $model, Action $action): void
{
$scope = $model->getModel(true)->scope();
// add entity ID to scope to allow easy traversal
if ($model->isEntity() && $model->idField && $model->getId() !== null) {
$scope = new Model\Scope([$scope]);
$scope->addCondition($model->getField($model->idField), $model->getId());
}
$action->filter($scope);
}
/**
* Various actions possible here, mostly for compatibility with SQLs.
*
* @param array<mixed> $args
*
* @return Action
*/
public function action(Model $model, string $type, array $args = [])
{
switch ($type) {
case 'select':
$action = $this->initAction($model, $args[0] ?? null);
$this->applyScope($model, $action);
$this->setLimitOrder($model, $action);
return $action;
case 'count':
$action = $this->initAction($model, $args[0] ?? null);
$this->applyScope($model, $action);
$this->setLimitOrder($model, $action);
return $action->count();
case 'exists':
$action = $this->initAction($model, $args[0] ?? null);
$this->applyScope($model, $action);
return $action->exists();
case 'field':
if (!isset($args[0])) {
throw (new Exception('This action requires one argument with field name'))
->addMoreInfo('action', $type);
}
$field = is_string($args[0]) ? $args[0] : $args[0][0];
$action = $this->initAction($model, [$field]);
$this->applyScope($model, $action);
$this->setLimitOrder($model, $action);
if (isset($args['alias'])) {
$action->generator = new RenameColumnIterator($action->generator, $field, $args['alias']);
}
return $action;
case 'fx':
case 'fx0':
if (!isset($args[0]) || !isset($args[1])) {
throw (new Exception('fx action needs 2 arguments, eg: [\'sum\', \'amount\']'))
->addMoreInfo('action', $type);
}
[$fx, $field] = $args;
$action = $this->initAction($model, [$field]);
$this->applyScope($model, $action);
$this->setLimitOrder($model, $action);
return $action->aggregate($fx, $field, $type === 'fx0');
default:
throw (new Exception('Unsupported action mode'))
->addMoreInfo('type', $type);
}
}
}