MediaWiki REL1_39
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
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'))
The persistent session ID (if any) loaded at startup.
Definition WebStart.php:82
Validate abstract schema json files against their JSON schema.
callable(string) __construct(callable $missingDepCallback)