Skip to content

Commit 4c9de90

Browse files
author
Dominic Tubach
committed
ErrorCollector: Ignore additionalProperties error if there are other violations
If there are other violations `additionalProperties` might be a false positive. See opis/json-schema#148.
1 parent cfd10bb commit 4c9de90

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/Errors/ErrorCollector.php

+7
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,13 @@ public function addError(ValidationError $error): void
6565
array_map(fn (ValidationError $subError) => $this->addError($subError), $error->subErrors());
6666
}
6767

68+
if ('additionalProperties' === $error->keyword() && $this->hasErrors()) {
69+
// If there are other violations "additionalProperties" might be a
70+
// false positive.
71+
// See https://github.com/opis/json-schema/issues/148.
72+
return;
73+
}
74+
6875
$path = $this->pathToString($error->data()->fullPath());
6976
if (isset($this->errors[$path])) {
7077
$this->errors[$path][] = $error;

tests/CollectErrorsTest.php

+36
Original file line numberDiff line numberDiff line change
@@ -305,4 +305,40 @@ public function testIf(): void
305305
self::assertTrue($errorCollector->hasLeafErrorAt(['string']));
306306
self::assertSame(['/string'], array_keys($errorCollector->getLeafErrors()));
307307
}
308+
309+
/**
310+
* An error for "additionalProperties" should not be added if there are
311+
* other violations because of a possible false positive.
312+
* See https://github.com/opis/json-schema/issues/148.
313+
*/
314+
public function testAdditionalProperties(): void
315+
{
316+
$schema = <<<'JSON'
317+
318+
{
319+
"type": "object",
320+
"properties": {
321+
"boolean": { "type": "boolean" }
322+
},
323+
"additionalProperties": false
324+
}
325+
JSON;
326+
327+
$validator = new SystopiaValidator([], 10);
328+
329+
$errorCollector = new ErrorCollector();
330+
$globals = ['errorCollector' => $errorCollector];
331+
$validator->validate((object) ['boolean' => 123, 'foo' => 'bar'], $schema, $globals);
332+
self::assertCount(1, $errorCollector->getLeafErrors());
333+
self::assertTrue($errorCollector->hasLeafErrorAt('/boolean'));
334+
self::assertErrorKeyword('type', $errorCollector->getLeafErrorsAt('/boolean')[0]);
335+
336+
// Test that "additionalProperties" error is added if there's no other violation.
337+
$errorCollector = new ErrorCollector();
338+
$globals = ['errorCollector' => $errorCollector];
339+
$validator->validate((object) ['boolean' => true, 'foo' => 'bar'], $schema, $globals);
340+
self::assertCount(1, $errorCollector->getLeafErrors());
341+
self::assertTrue($errorCollector->hasLeafErrorAt('/'));
342+
self::assertErrorKeyword('additionalProperties', $errorCollector->getLeafErrorsAt('/')[0]);
343+
}
308344
}

0 commit comments

Comments
 (0)