Skip to content

Commit a5a9bcc

Browse files
committed
Added nullable type support
1 parent 44731dc commit a5a9bcc

2 files changed

Lines changed: 60 additions & 0 deletions

File tree

src/Validator.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,13 @@ protected function matchObjectKeys($data, $definition)
236236

237237
protected function matchInternal($data, $type)
238238
{
239+
if (is_string($type) && $type[0] === '?') {
240+
if ($data === null) {
241+
return true;
242+
}
243+
$type = substr($type, 1);
244+
}
245+
239246
if (!is_string($type)) {
240247
$definition = $type;
241248
} else if (isset($this->types[$type])) {

tests/JsonTypeTest.php

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,4 +228,57 @@ public function testStrictMode($value, $type, $key, $message)
228228
$this->assertFalse($json->matches($value, $type));
229229
$this->assertEquals($message, $json->getErrors()[$key] ?? '');
230230
}
231+
232+
public function typeNullableData()
233+
{
234+
return [
235+
[
236+
[
237+
'name' => 'foo',
238+
'gender' => null,
239+
],
240+
[
241+
'name' => 'string',
242+
'gender' => '?string',
243+
],
244+
true,
245+
],
246+
[
247+
['foo', 'bar', null],
248+
['?string'],
249+
true,
250+
],
251+
[
252+
[
253+
'dt' => null,
254+
],
255+
[
256+
'dt' => '?timestamp',
257+
],
258+
true,
259+
],
260+
[
261+
'foo',
262+
'?integer',
263+
false,
264+
'$',
265+
'The path of \'$\' requires to be a integer, string is given',
266+
]
267+
];
268+
}
269+
270+
/**
271+
* @dataProvider typeNullableData
272+
*/
273+
public function testNullableTypes($value, $type, $matched, $key = null, $message = null)
274+
{
275+
$json = $this->createValidator(true);
276+
277+
$method = $matched ? 'assertTrue' : 'assertFalse';
278+
$this->$method($json->matches($value, $type));
279+
280+
if (!$matched) {
281+
$this->assertEquals($message, $json->getErrors()[$key] ?? null);
282+
}
283+
}
231284
}

0 commit comments

Comments
 (0)