Skip to content

Commit 5322df2

Browse files
committed
Normalize array persistence data on construct
1 parent 5574939 commit 5322df2

File tree

1 file changed

+32
-12
lines changed

1 file changed

+32
-12
lines changed

src/Persistence/Array_.php

+32-12
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,23 @@ class Array_ extends Persistence
2020

2121
public function __construct(array $data = [])
2222
{
23-
$this->data = $data;
23+
// if there is no model table specified, then create fake one named 'data'
24+
// and put all data in there
25+
foreach ($data as $rows) {
26+
foreach ($rows as $row) {
27+
if (!is_array($row)) {
28+
$data = ['data' => $data];
29+
30+
break 2;
31+
}
32+
}
33+
}
34+
35+
foreach ($data as $table => $rows) {
36+
foreach ($rows as $id => $row) {
37+
$this->_saveRow($row, $id, $table, 'id');
38+
}
39+
}
2440
}
2541

2642
/**
@@ -57,18 +73,26 @@ private function assertNoIdMismatch($idFromRow, $id): void
5773
}
5874
}
5975

76+
private function _saveRow(array $row, $id, string $table, ?string $idColumnName): void
77+
{
78+
if ($idColumnName !== null && array_key_exists($idColumnName, $row)) {
79+
$this->assertNoIdMismatch($row[$idColumnName], $id);
80+
unset($row[$idColumnName]);
81+
}
82+
83+
$this->data[$table][$id] = $row;
84+
}
85+
6086
private function saveRow(Model $model, array $row, $id, string $table): void
6187
{
6288
if ($model->id_field) {
6389
$idField = $model->getField($model->id_field);
6490
$idColumnName = $idField->actual ?? $idField->short_name;
65-
if (array_key_exists($idColumnName, $row)) {
66-
$this->assertNoIdMismatch($row[$idColumnName], $id);
67-
unset($row[$idColumnName]);
68-
}
91+
} else {
92+
$idColumnName = null;
6993
}
7094

71-
$this->data[$table][$id] = $row;
95+
$this->_saveRow($row, $id, $table, $idColumnName);
7296
}
7397

7498
private function addIdToLoadRow(Model $model, array &$row, $id): void
@@ -107,13 +131,9 @@ public function add(Model $model, array $defaults = []): Model
107131
}
108132
}
109133

110-
// if there is no model table specified, then create fake one named 'data'
111-
// and put all persistence data in there
134+
// if there is no model table specified, set it to 'data'
112135
if (!$model->table) {
113-
$model->table = 'data'; // fake table name 'data'
114-
if (!isset($this->data[$model->table]) || count($this->data) !== 1) {
115-
$this->data = [$model->table => $this->data];
116-
}
136+
$model->table = 'data';
117137
}
118138

119139
// if there is no such table in persistence, then create empty one

0 commit comments

Comments
 (0)