MediaWiki  master
AbstractSchemaValidator.php
Go to the documentation of this file.
1 <?php
2 
22 namespace MediaWiki\DB;
23 
24 use JsonSchema\Validator;
25 use Seld\JsonLint\DuplicateKeyException;
26 use Seld\JsonLint\JsonParser;
27 use Seld\JsonLint\ParsingException;
28 use function class_exists;
29 use function file_get_contents;
30 use function is_array;
31 use function is_object;
32 
48  private $missingDepCallback;
49 
53  public function __construct( callable $missingDepCallback ) {
54  $this->missingDepCallback = $missingDepCallback;
55  }
56 
61  public function checkDependencies(): bool {
62  if ( !class_exists( Validator::class ) ) {
63  ( $this->missingDepCallback )(
64  'The JsonSchema library cannot be found, please install it through composer.'
65  );
66  return false;
67  }
68 
69  if ( !class_exists( JsonParser::class ) ) {
70  ( $this->missingDepCallback )(
71  'The JSON lint library cannot be found, please install it through composer.'
72  );
73  return false;
74  }
75 
76  return true;
77  }
78 
84  public function validate( string $path ): bool {
85  $contents = file_get_contents( $path );
86  $jsonParser = new JsonParser();
87  try {
88  $data = $jsonParser->parse( $contents, JsonParser::DETECT_KEY_CONFLICTS );
89  } catch ( DuplicateKeyException $e ) {
90  throw new AbstractSchemaValidationError( $e->getMessage(), $e->getCode(), $e );
91  } catch ( ParsingException $e ) {
92  throw new AbstractSchemaValidationError( "$path is not valid JSON", $e->getCode(), $e );
93  }
94 
95  // Regular schema's are arrays, schema changes are objects.
96  if ( is_array( $data ) ) {
97  $schemaPath = __DIR__ . '/../../docs/abstract-schema.schema.json';
98  } elseif ( is_object( $data ) ) {
99  $schemaPath = __DIR__ . '/../../docs/abstract-schema-changes.schema.json';
100  } else {
101  throw new AbstractSchemaValidationError( "$path is not a supported JSON object" );
102  }
103 
104  $validator = new Validator;
105  $validator->check( $data, (object)[ '$ref' => 'file://' . $schemaPath ] );
106  if ( $validator->isValid() ) {
107  // All good.
108  return true;
109  }
110 
111  $out = "$path did not pass validation.\n";
112  foreach ( $validator->getErrors() as $error ) {
113  $out .= "[{$error['property']}] {$error['message']}\n";
114  }
115  throw new AbstractSchemaValidationError( $out );
116  }
117 }
if(!defined('MW_SETUP_CALLBACK'))
Definition: WebStart.php:88
Validate abstract schema json files against their JSON schema.
callable(string) __construct(callable $missingDepCallback)