| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 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 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
class AbstractSchemaValidator { |
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
private $missingDepCallback; |
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
public function __construct( callable $missingDepCallback ) { |
| 54 |
$this->missingDepCallback = $missingDepCallback; |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 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 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 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 |
|
| 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 |
|
| 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 |
} |