Skip to content

Commit

Permalink
fix: 对于嵌套的模型列表,会丢失数组的key
Browse files Browse the repository at this point in the history
  • Loading branch information
hsldymq committed Apr 14, 2021
1 parent 60f3bef commit 8558e1e
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 4 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ $data = [
"name" => "Alice",
"age" => 8,
],
[
's' => [
"name" => "Bob",
"age" => 10,
]
Expand Down Expand Up @@ -199,6 +199,7 @@ $info = new Info($data);

assert(count($info->studentList) === 2);
assert($info->studentList[0]->name === 'Alice');
assert($info->studentList['s']->name === 'Bob');
assert($info->school->name === 'xxx');
```

Expand Down
4 changes: 2 additions & 2 deletions src/Converters/ModelListConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ public function convert(mixed $fieldValue, Property $property): array
}

$result = [];
foreach ($fieldValue as $each) {
foreach ($fieldValue as $key => $each) {
if (!is_array($each)) {
throw new TypeError("the element of {$property->getBoundFieldName()} should be a type of array");
}

$result[] = new $this->modelClass($each);
$result[$key] = new $this->modelClass($each);
}

return $result;
Expand Down
29 changes: 28 additions & 1 deletion tests/ModelConverterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public function testRecursiveDataModel()
['field' => 3],
['field' => 4],
],
]
],
],
]);

Expand All @@ -40,6 +40,33 @@ public function testRecursiveDataModel()
$this->assertEquals(3, $model->outerList[1]->innerList[0]->val);
$this->assertEquals(4, $model->outerList[1]->innerList[1]->val);


$model = new EmbedDataListModel([
'outers' => [
'outer1' => [
'inners' => [
'inner1_a' => ['field' => 1],
'inner1_b' => ['field' => 2],
],
],
'outer2' => [
'inners' => [
'inner2_a' => ['field' => 3],
'inner2_b' => ['field' => 4],
],
],
],
]);
$this->assertCount(2, $model->outerList);

$this->assertCount(2, $model->outerList['outer1']->innerList);
$this->assertEquals(1, $model->outerList['outer1']->innerList['inner1_a']->val);
$this->assertEquals(2, $model->outerList['outer1']->innerList['inner1_b']->val);

$this->assertCount(2, $model->outerList['outer2']->innerList);
$this->assertEquals(3, $model->outerList['outer2']->innerList['inner2_a']->val);
$this->assertEquals(4, $model->outerList['outer2']->innerList['inner2_b']->val);

}

public function testInvalidFieldType_ExpectError()
Expand Down

0 comments on commit 8558e1e

Please sign in to comment.