Skip to content

Commit

Permalink
Avoid empty oneOf keyword
Browse files Browse the repository at this point in the history
If `oneOf` is set to an empty array this will result in an exception
thrown on schema validation.
  • Loading branch information
Dominic Tubach committed Feb 6, 2024
1 parent f0c13f5 commit 3bdace4
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,16 @@ public function createSchema(AbstractFormField $field): JsonSchema {
/** @var \Civi\RemoteTools\Form\FormSpec\Field\AbstractOptionField $field */
$keywords = [
'type' => ['string', 'integer'],
'oneOf' => JsonSchemaUtil::buildTitledOneOf($field->getOptions()),
];

// 'oneOf' must not be empty.
if ($field->getOptions() !== []) {
$keywords['oneOf'] = JsonSchemaUtil::buildTitledOneOf($field->getOptions());
}
elseif (!$field->isNullable()) {
$keywords['oneOf'] = JsonSchema::fromArray(['const' => NULL]);
}

if ($field->isNullable()) {
$keywords['type'][] = 'null';
$keywords['oneOf'][] = JsonSchema::fromArray(['const' => NULL]);
Expand Down
6 changes: 4 additions & 2 deletions Civi/RemoteTools/JsonSchema/Util/JsonSchemaUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@
final class JsonSchemaUtil {

/**
* @phpstan-param array<int|string, string> $titles
* The 'oneOf' keyword must not be empty.
*
* @phpstan-param non-empty-array<int|string, string> $titles
* Allowed values mapped to titles.
*
* @phpstan-return array<JsonSchema> To be used as value of "oneOf" keyword.
* @phpstan-return non-empty-array<JsonSchema> To be used as value of "oneOf" keyword.
*/
public static function buildTitledOneOf(array $titles): array {
$oneOf = [];
Expand Down

0 comments on commit 3bdace4

Please sign in to comment.