Skip to content

Commit 251bd6c

Browse files
committed
update: 获取未分配字段名列表
1 parent 3e025b4 commit 251bd6c

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

src/DataModel.php

+20
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,32 @@ abstract class DataModel
3434

3535
private array $readonlyPropsVal = [];
3636

37+
private array $signedFieldNames = [];
38+
3739
private string $className;
3840

3941
public function __construct(private array $data = [])
4042
{
4143
$this->assignProps();
4244
}
4345

46+
/**
47+
* 返回未分配给属性的数据字段名列表.
48+
*
49+
* @return array
50+
*/
51+
public function getUnsignedFieldNames(): array
52+
{
53+
$data = $this->getRawData();
54+
foreach ($this->signedFieldNames as $eachField) {
55+
if (array_key_exists($eachField, $this->data)) {
56+
unset($data[$eachField]);
57+
}
58+
}
59+
60+
return array_keys($data);
61+
}
62+
4463
public function getRawData(): array
4564
{
4665
return $this->data;
@@ -184,6 +203,7 @@ private function doAssign()
184203
$this->readonlyPropsVal[$propName] = $this->$propName;
185204
unset($this->$propName);
186205
}
206+
$this->signedFieldNames[] = $fieldName;
187207
}
188208
}
189209

tests/DataModelTest.php

+41
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,47 @@ public function testSetReadonlyProp_ExpectError()
7070
}
7171
}
7272

73+
public function testGetUnsignedFieldNames()
74+
{
75+
$d1 = new BasicDataModel([
76+
'aa' => 3,
77+
'ro' => 'greeting',
78+
'cc' => false,
79+
'dd' => 2.5,
80+
'ee' => ['b' => 'b'],
81+
'ff' => null,
82+
'gg' => null,
83+
]);
84+
$this->assertEmpty($d1->getUnsignedFieldNames());
85+
86+
$d2 = new BasicDataModel([
87+
'aa' => 3,
88+
'ro' => 'greeting',
89+
'cc' => false,
90+
'dd' => 2.5,
91+
'ee' => ['b' => 'b'],
92+
'ff' => 1,
93+
'gg' => 1,
94+
'xxxxx' => 123,
95+
'ggggg' => 456,
96+
]);
97+
$this->assertEquals(['xxxxx', 'ggggg'], $d2->getUnsignedFieldNames());
98+
99+
$d3 = new BasicDataModel([
100+
'aa' => 3,
101+
'hhhhh' => null,
102+
'yyyyy' => 123,
103+
]);
104+
$this->assertEquals(['hhhhh', 'yyyyy'], $d3->getUnsignedFieldNames());
105+
106+
$d4 = new BasicDataModel([
107+
'bbbbb' => false,
108+
'zzzzz' => 123,
109+
'iiiii' => null,
110+
]);
111+
$this->assertEquals(['bbbbb', 'zzzzz', 'iiiii'], $d4->getUnsignedFieldNames());
112+
}
113+
73114
public function testSetPrivateProp_ExpectError()
74115
{
75116
$this->expectException(RuntimeException::class);

0 commit comments

Comments
 (0)