summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/Utils/JsonSchemaValidator.php
blob: 8a849ef6afffc50935e601944f2ddce4a29d3616 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php

namespace SMW\Utils;

use JsonSchema\Exception\ResourceNotFoundException;
use JsonSchema\Validator as SchemaValidator;
use JsonSerializable;

/**
 * @license GNU GPL v2+
 * @since 3.0
 *
 * @author mwjames
 */
class JsonSchemaValidator {

	/**
	 * @var SchemaValidator
	 */
	private $schemaValidator;

	/**
	 * @var boolen
	 */
	private $isValid = true;

	/**
	 * @var []
	 */
	private $errors = [];

	/**
	 * @since 3.0
	 *
	 * @param SchemaValidator|null $schemaValidator
	 */
	public function __construct( SchemaValidator $schemaValidator = null ) {
		$this->schemaValidator = $schemaValidator;
	}

	/**
	 * @since 3.0
	 *
	 * @param JsonSerializable $data
	 * @param string|null $schemaLink
	 */
	public function validate( JsonSerializable $data, $schemaLink = null ) {

		if ( $this->schemaValidator === null || $schemaLink === null ) {
			return;
		}

		// https://github.com/justinrainbow/json-schema/issues/203
		$data = json_decode( $data->jsonSerialize() );

		// https://github.com/justinrainbow/json-schema
		try {
			$this->schemaValidator->check(
				$data,
				(object)[ '$ref' => 'file://' . $schemaLink ]
			);

			$this->isValid = $this->schemaValidator->isValid();
			$this->errors = $this->schemaValidator->getErrors();
		} catch ( ResourceNotFoundException $e ) {
			$this->isValid = false;
			$this->errors[] = $e->getMessage();
		}
	}

	/**
	 * @since 3.0
	 *
	 * @param boolean
	 */
	public function hasSchemaValidator() {
		return $this->schemaValidator !== null;
	}

	/**
	 * @since 3.0
	 *
	 * @param boolean
	 */
	public function isValid() {
		return $this->isValid;
	}

	/**
	 * @since 3.0
	 *
	 * @return []
	 */
	public function getErrors() {
		return $this->errors;
	}

}