aboutsummaryrefslogtreecommitdiffstats
path: root/includes/Settings/Source/JsonSchemaTrait.php
blob: ef3dd0547f3f4839e1b7dd5765b5711aeabf71db (plain) (blame)
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
<?php

namespace MediaWiki\Settings\Source;

use InvalidArgumentException;

/**
 * Trait for dealing with JSON Schema structures and types.
 *
 * @since 1.39
 */
trait JsonSchemaTrait {

	/**
	 * Converts a JSON Schema type to a PHPDoc type.
	 *
	 * @param string|string[] $jsonSchemaType A JSON Schema type
	 *
	 * @return string A PHPDoc type
	 */
	private static function jsonToPhpDoc( $jsonSchemaType ) {
		static $phpTypes = [
			'array' => 'array',
			'object' => 'array', // could be optional
			'number' => 'float',
			'double' => 'float', // for good measure
			'boolean' => 'bool',
			'integer' => 'int',
		];

		if ( $jsonSchemaType === null ) {
			throw new InvalidArgumentException( 'The type name cannot be null! Use "null" instead.' );
		}

		$nullable = false;
		if ( is_array( $jsonSchemaType ) ) {
			$nullIndex = array_search( 'null', $jsonSchemaType );
			if ( $nullIndex !== false ) {
				$nullable = true;
				unset( $jsonSchemaType[$nullIndex] );
			}

			$jsonSchemaType = array_map( [ self::class, 'jsonToPhpDoc' ], $jsonSchemaType );
			$type = implode( '|', $jsonSchemaType );
		} else {
			$type = $phpTypes[ strtolower( $jsonSchemaType ) ] ?? $jsonSchemaType;
		}

		if ( $nullable ) {
			$type = "?$type";
		}

		return $type;
	}

	/**
	 * @param string|string[] $phpDocType The PHPDoc type
	 *
	 * @return string|string[] A JSON Schema type
	 */
	private static function phpDocToJson( $phpDocType ) {
		static $jsonTypes = [
			'list' => 'array',
			'dict' => 'object',
			'map' => 'object',
			'stdclass' => 'object',
			'int' => 'integer',
			'float' => 'number',
			'bool' => 'boolean',
			'false' => 'boolean',
		];

		if ( $phpDocType === null ) {
			throw new InvalidArgumentException( 'The type name cannot be null! Use "null" instead.' );
		}

		if ( is_array( $phpDocType ) ) {
			$types = $phpDocType;
		} else {
			$types = explode( '|', trim( $phpDocType ) );
		}

		$nullable = false;
		foreach ( $types as $i => $t ) {
			if ( str_starts_with( $t, '?' ) ) {
				$nullable = true;
				$t = substr( $t, 1 );
			}

			$types[$i] = $jsonTypes[ strtolower( $t ) ] ?? $t;
		}

		if ( $nullable ) {
			$types[] = 'null';
		}

		$types = array_unique( $types );

		if ( count( $types ) === 1 ) {
			return reset( $types );
		}

		return $types;
	}

	/**
	 * Applies phpDocToJson() to type declarations in a JSON schema.
	 *
	 * @param array $schema JSON Schema structure with PHPDoc types
	 * @param array &$defs List of definitions (JSON schemas) referenced in the schema
	 * @param string $source An identifier for the source schema being reflected, used
	 * for error descriptions.
	 * @param string $propertyName The name of the property the schema belongs to, used for error descriptions.
	 * @return array JSON Schema structure using only proper JSON types
	 */
	private static function normalizeJsonSchema(
		array $schema,
		array &$defs,
		string $source,
		string $propertyName,
		bool $inlineReferences = false
	): array {
		$traversedReferences = [];
		return self::doNormalizeJsonSchema(
			$schema, $defs, $source, $propertyName, $inlineReferences, $traversedReferences
		);
	}

	/**
	 * Recursively applies phpDocToJson() to type declarations in a JSON schema.
	 *
	 * @param array $schema JSON Schema structure with PHPDoc types
	 * @param array &$defs List of definitions (JSON schemas) referenced in the schema
	 * @param string $source An identifier for the source schema being reflected, used
	 * for error descriptions.
	 * @param string $propertyName The name of the property the schema belongs to, used for error descriptions.
	 * @param bool $inlineReferences Whether references in the schema should be inlined or not.
	 * @param array $traversedReferences An accumulator for the resolved references within a schema normalization,
	 * used for cycle detection.
	 * @return array JSON Schema structure using only proper JSON types
	 */
	private static function doNormalizeJsonSchema(
		array $schema,
		array &$defs,
		string $source,
		string $propertyName,
		bool $inlineReferences,
		array $traversedReferences
	): array {
		if ( isset( $schema['type'] ) ) {
			// Support PHP Doc style types, for convenience.
			$schema['type'] = self::phpDocToJson( $schema['type'] );
		}

		if ( isset( $schema['additionalProperties'] ) && is_array( $schema['additionalProperties'] ) ) {
			$schema['additionalProperties'] =
				self::doNormalizeJsonSchema(
					$schema['additionalProperties'],
					$defs,
					$source,
					$propertyName,
					$inlineReferences,
					$traversedReferences
				);
		}

		if ( isset( $schema['items'] ) && is_array( $schema['items'] ) ) {
			$schema['items'] = self::doNormalizeJsonSchema(
				$schema['items'],
				$defs,
				$source,
				$propertyName,
				$inlineReferences,
				$traversedReferences
			);
		}

		if ( isset( $schema['properties'] ) && is_array( $schema['properties'] ) ) {
			foreach ( $schema['properties'] as $name => $propSchema ) {
				$schema['properties'][$name] = self::doNormalizeJsonSchema(
					$propSchema,
					$defs,
					$source,
					$propertyName,
					$inlineReferences,
					$traversedReferences
				);
			}
		}

		if ( isset( $schema['$ref'] ) ) {
			$definitionName = JsonSchemaReferenceResolver::getDefinitionName( $schema[ '$ref' ] );
			if ( array_key_exists( $definitionName, $traversedReferences ) ) {
				throw new RefLoopException(
					"Found a loop while resolving reference $definitionName in $propertyName." .
					" Root schema location: $source"
				);
			}
			$def = JsonSchemaReferenceResolver::resolveRef( $schema['$ref'], $source );
			if ( $def ) {
				if ( !isset( $defs[$definitionName] ) ) {
					$traversedReferences[$definitionName] = true;
					$normalizedDefinition = self::doNormalizeJsonSchema(
						$def,
						$defs,
						$source,
						$propertyName,
						$inlineReferences,
						$traversedReferences
					);
					if ( !$inlineReferences ) {
						$defs[$definitionName] = $normalizedDefinition;
					}
				} else {
					$normalizedDefinition = $defs[$definitionName];
				}
				// Normalize reference after resolving it since JsonSchemaReferenceResolver expects
				// the $ref to be an array with: [ "class" => "Some\\Class", "field" => "someField" ]
				if ( $inlineReferences ) {
					$schema = $normalizedDefinition;
				} else {
					$schema['$ref'] = JsonSchemaReferenceResolver::normalizeRef( $schema['$ref'] );
				}
			}
		}

		return $schema;
	}

	/**
	 * Returns the default value from the given schema structure.
	 * If the schema defines properties, the default value of each
	 * property is determined recursively, and the collected into a
	 * the top level default, which in that case will be a map
	 * (that is, a JSON object).
	 *
	 * @param array $schema
	 * @return mixed The default specified by $schema, or null if no default
	 *         is defined.
	 */
	private static function getDefaultFromJsonSchema( array $schema ) {
		$default = $schema['default'] ?? null;

		foreach ( $schema['properties'] ?? [] as $name => $sch ) {
			$def = self::getDefaultFromJsonSchema( $sch );

			$default[$name] = $def;
		}

		return $default;
	}

}