Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions includes/Experiments/Abilities_Explorer/Ability_Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -345,13 +345,23 @@ private static function validate_property( string $prop_name, $value, array $pro
$errors = array();

if ( isset( $prop_schema['type'] ) ) {
$valid = self::validate_type( $value, $prop_schema['type'] );
// A type may also be a list of types, e.g. `array( 'string', 'object' )`, any of which can match.
$types = array_filter( (array) $prop_schema['type'], 'is_string' );
$valid = false;

foreach ( $types as $type ) {
if ( self::validate_type( $value, $type ) ) {
$valid = true;
break;
}
}

if ( ! $valid ) {
return array(
sprintf(
'Field "%s" should be of type "%s"',
$prop_name,
$prop_schema['type']
implode( '" or "', $types )
),
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,31 @@ public function test_validate_input_validates_integer_type() {
$this->assertFalse( $result['valid'] );
}

/**
* Test validate_input validates a list of types.
*
* JSON Schema allows a property to list several types, and a value matching any of them is valid.
*
* @since x.x.x
*/
public function test_validate_input_validates_type_list() {
$schema = array(
'properties' => array(
'title' => array( 'type' => array( 'string', 'object' ) ),
),
);

$result = Ability_Handler::validate_input( $schema, array( 'title' => 'Hello' ) );
$this->assertTrue( $result['valid'] );

$result = Ability_Handler::validate_input( $schema, array( 'title' => array( 'raw' => 'Hello' ) ) );
$this->assertTrue( $result['valid'] );

$result = Ability_Handler::validate_input( $schema, array( 'title' => 42 ) );
$this->assertFalse( $result['valid'] );
$this->assertSame( 'Field "title" should be of type "string" or "object"', $result['errors'][0] );
}

/**
* Test validate_input validates numeric minimum and maximum constraints.
*
Expand Down
Loading