MediaWiki master
AbstractSchemaValidator.php
Go to the documentation of this file.
1<?php
2
22namespace MediaWiki\DB;
23
24use JsonSchema\Validator;
25use Seld\JsonLint\DuplicateKeyException;
26use Seld\JsonLint\JsonParser;
27use Seld\JsonLint\ParsingException;
28use function class_exists;
29use function file_get_contents;
30use function is_array;
31use function is_object;
32
45 public function __construct() {
46 if ( !class_exists( Validator::class ) ) {
48 'The JsonSchema library cannot be found, please install it through composer.'
49 );
50 }
51
52 if ( !class_exists( JsonParser::class ) ) {
54 'The JSON lint library cannot be found, please install it through composer.'
55 );
56 }
57 }
58
64 public function validate( string $path ): bool {
65 $contents = file_get_contents( $path );
66 $jsonParser = new JsonParser();
67 try {
68 $data = $jsonParser->parse( $contents, JsonParser::DETECT_KEY_CONFLICTS );
69 } catch ( DuplicateKeyException $e ) {
70 throw new AbstractSchemaValidationError( $e->getMessage(), $e->getCode(), $e );
71 } catch ( ParsingException $e ) {
72 throw new AbstractSchemaValidationError( "$path is not valid JSON", $e->getCode(), $e );
73 }
74
75 // Regular schema's are arrays, schema changes are objects.
76 if ( is_array( $data ) ) {
77 $schemaPath = __DIR__ . '/../../docs/abstract-schema.schema.json';
78 } elseif ( is_object( $data ) ) {
79 $schemaPath = __DIR__ . '/../../docs/abstract-schema-changes.schema.json';
80 } else {
81 throw new AbstractSchemaValidationError( "$path is not a supported JSON object" );
82 }
83
84 $validator = new Validator;
85 $validator->check( $data, (object)[ '$ref' => 'file://' . $schemaPath ] );
86 if ( $validator->isValid() ) {
87 // All good.
88 return true;
89 }
90
91 $out = "$path did not pass validation.\n";
92 foreach ( $validator->getErrors() as $error ) {
93 $out .= "[{$error['property']}] {$error['message']}\n";
94 }
95 throw new AbstractSchemaValidationError( $out );
96 }
97}
Validate abstract schema json files against their JSON schema.