| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
use JsonSchema\Constraints\Constraint; |
| 20 |
use JsonSchema\Constraints\Factory; |
| 21 |
use JsonSchema\Validator; |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
trait JsonSchemaAssertionTrait { |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
private static function loadJsonData( string $jsonFile ) { |
| 42 |
$json = file_get_contents( $jsonFile ); |
| 43 |
|
| 44 |
if ( $json === false ) { |
| 45 |
throw new InvalidArgumentException( "Unable to load content of $jsonFile" ); |
| 46 |
} |
| 47 |
|
| 48 |
return json_decode( $json, false, JSON_THROW_ON_ERROR ); |
| 49 |
} |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
private function assertMatchesJsonSchema( $schema, $json, array $resources = [] ): void { |
| 59 |
if ( is_string( $json ) ) { |
| 60 |
try { |
| 61 |
$json = json_decode( $json, false, JSON_THROW_ON_ERROR ); |
| 62 |
} catch ( JsonException $ex ) { |
| 63 |
self::fail( 'Invalid JSON: ' . $ex->getMessage() ); |
| 64 |
} |
| 65 |
} |
| 66 |
if ( is_string( $schema ) ) { |
| 67 |
|
| 68 |
|
| 69 |
$schema = self::loadJsonData( $schema ); |
| 70 |
} |
| 71 |
|
| 72 |
$factory = new Factory(); |
| 73 |
|
| 74 |
foreach ( $resources as $id => $rc ) { |
| 75 |
$factory->getSchemaStorage()->addSchema( |
| 76 |
rtrim( $id, '#' ), |
| 77 |
self::loadJsonData( $rc ) |
| 78 |
); |
| 79 |
} |
| 80 |
|
| 81 |
$validator = new Validator( $factory ); |
| 82 |
$validator->validate( |
| 83 |
$json, $schema, |
| 84 |
Constraint::CHECK_MODE_TYPE_CAST |
| 85 |
); |
| 86 |
|
| 87 |
if ( !$validator->isValid() ) { |
| 88 |
foreach ( $validator->getErrors() as $error ) { |
| 89 |
$error = json_encode( $error ); |
| 90 |
self::fail( "JSON schema validation failed: $error" ); |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
$this->addToAssertionCount( 1 ); |
| 95 |
} |
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
public function assertValidJsonSchema( array $schema ): void { |
| 106 |
|
| 107 |
$metaSchema = MW_INSTALL_PATH . '/vendor/justinrainbow/json-schema/dist/' . |
| 108 |
'schema/json-schema-draft-04.json'; |
| 109 |
|
| 110 |
self::assertMatchesJsonSchema( $metaSchema, $schema ); |
| 111 |
} |
| 112 |
|
| 113 |
} |