Skip to content

Commit 754d600

Browse files
dktappscweiske
authored andcommitted
Enforce bStrictObjectTypeChecking on arrays
Simple types like strings in arrays that expect an object will throw an exception now when bStrictObjectTypeChecking is enabled. BC break! Resolves: #225
1 parent a068f7c commit 754d600

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/JsonMapper.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,6 +467,13 @@ public function mapArray($json, $array, $class = null, $parent_key = '')
467467
if ($this->isSimpleType($class)) {
468468
settype($jvalue, $class);
469469
$array[$key] = $jvalue;
470+
} else if ($this->bStrictObjectTypeChecking) {
471+
throw new JsonMapper_Exception(
472+
'JSON property'
473+
. ' "' . ($parent_key ? $parent_key : '?') . '"'
474+
. ' (array key "' . $key . '") must be an object, '
475+
. gettype($jvalue) . ' given'
476+
);
470477
} else {
471478
$array[$key] = $this->createInstance(
472479
$class, true, $jvalue

tests/ObjectTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,35 @@ public function testStrictTypeCheckingObjectError()
127127
);
128128
}
129129

130+
public function testStrictTypeCheckingObjectInArray()
131+
{
132+
$jm = new JsonMapper();
133+
$jm->bStrictObjectTypeChecking = true;
134+
$sn = $jm->mapArray(
135+
json_decode('[{"pStr":"abc"}]'),
136+
[],
137+
JsonMapperTest_PlainObject::class
138+
);
139+
140+
$this->assertContainsOnlyInstancesOf(JsonMapperTest_PlainObject::class, $sn);
141+
$this->assertSame('abc', $sn[0]->pStr);
142+
}
143+
144+
public function testStrictTypeCheckingObjectInArrayError()
145+
{
146+
$this->expectException(JsonMapper_Exception::class);
147+
$this->expectExceptionMessage(
148+
'JSON property "?" (array key "0") must be an object, string given'
149+
);
150+
$jm = new JsonMapper();
151+
$jm->bStrictObjectTypeChecking = true;
152+
$jm->mapArray(
153+
json_decode('["abc"]'),
154+
[],
155+
JsonMapperTest_Object::class
156+
);
157+
}
158+
130159
/**
131160
* Test for "@var object|null" with null value
132161
*/

0 commit comments

Comments
 (0)