Skip to content

Commit

Permalink
Add method to make schema validation more flexible
Browse files Browse the repository at this point in the history
Add test
  • Loading branch information
trasher committed Jan 21, 2025
1 parent c791c6e commit 316ed39
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
48 changes: 48 additions & 0 deletions lib/php/Converter.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ class Converter
private array $extra_sub_properties = [];
/** @var array<string> */
private array $extra_itemtypes = [];
/** @var bool */
private bool $strict_schema = true;

/**
* @var array<string, array<int, string>>
Expand Down Expand Up @@ -289,6 +291,10 @@ public function buildSchema()
}
}

if ($this->strict_schema === false) {
$this->buildFlexibleSchema($schema->properties->content);
}

return $schema;
}

Expand Down Expand Up @@ -1796,4 +1802,46 @@ private function isNetworkDiscovery(array $data): bool
{
return isset($data['content']['device']) && $data['action'] == 'netdiscovery';
}

/**
* Set schema validation strict (no additional properties allowed anywhere)
*
* @return self
*/
public function setStrictSchema(): self
{
$this->strict_schema = true;
return $this;
}

/**
* Set schema validation strict (no additional properties allowed anywhere)
*
* @return self
*/
public function setFlexibleSchema(): self
{
$this->strict_schema = false;
return $this;
}

/**
* Build schema flexible (remove all additionalProperties)
*
* @param mixed $schemapart
*
* @return void
*/
private function buildFlexibleSchema(&$schemapart)
{
foreach ($schemapart as $key => $value) {
if (is_object($value) || is_array($value)) {
$this->buildFlexibleSchema($value);
} else {
if ($key == 'additionalProperties') {
unset($schemapart->$key);
}
}
}
}
}
12 changes: 12 additions & 0 deletions tests/Glpi/Inventory/tests/units/Converter.php
Original file line number Diff line number Diff line change
Expand Up @@ -981,5 +981,17 @@ public function testConvertMemoryCapacity($orig, $expected)
$this->assertSame($expected, $instance->convertMemory($orig));
}

public function testFlexibleSchema(): void
{
$json_additionnal = json_decode(json_encode(['deviceid' => 'myid', 'content' => ['versionclient' => 'GLPI-Agent_v1.0', 'additional' => ['name' => 'my extra data']]]));
$instance = new \Glpi\Inventory\Converter();
$instance->setFlexibleSchema();
$this->assertTrue($instance->validate($json_additionnal));

//tests same JSON fails with strict schema
$instance->setStrictSchema();
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Additional properties not allowed: additional');
$this->assertTrue($instance->validate($json_additionnal));
}
}

0 comments on commit 316ed39

Please sign in to comment.