Skip to content

Commit

Permalink
add option to disable ignore unknown properties
Browse files Browse the repository at this point in the history
  • Loading branch information
chriskapp committed Jul 21, 2024
1 parent 0af6c51 commit 445a86f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/SchemaTraverser.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,12 @@ class SchemaTraverser
{
private array $pathStack = [];
private bool $assertConstraints;
private bool $ignoreUnknown;

public function __construct(bool $assertConstraints = true)
public function __construct(bool $assertConstraints = true, bool $ignoreUnknown = true)
{
$this->assertConstraints = $assertConstraints;
$this->ignoreUnknown = $ignoreUnknown;
}

/**
Expand Down Expand Up @@ -218,6 +220,14 @@ protected function traverseStruct(\stdClass $data, StructType $type, Definitions

array_pop($this->pathStack);
}

if ($this->ignoreUnknown === false) {
foreach ($data as $key => $value) {
if (!array_key_exists($key, $properties)) {
throw new ValidationException($this->getCurrentPath() . ' property "' . $key . '" is unknown', 'properties', $this->pathStack);
}
}
}
}

return $visitor->visitStruct($result, $type, $this->getCurrentPath());
Expand Down
19 changes: 19 additions & 0 deletions tests/SchemaTraverserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,25 @@ public function testTraverseExtends()
$this->assertEquals('foo', $result->getParent()->getType());
}

public function testTraverseUnknownProperties()
{
$this->expectException(ValidationException::class);
$this->expectExceptionMessage('/ property "foo" is unknown');

$schema = $this->schemaManager->getSchema(Form_Element_Input::class);
$data = <<<JSON
{
"element": "text",
"name": "foo",
"type": "bar",
"foo": "bar"
}
JSON;

$traverser = new SchemaTraverser(ignoreUnknown: false);
$traverser->traverse(\json_decode($data), $schema, new TypeVisitor());
}

protected function getData()
{
return json_decode(file_get_contents(__DIR__ . '/SchemaTraverser/expected.json'));
Expand Down

0 comments on commit 445a86f

Please sign in to comment.