File: ArrayDef.php

package info (click to toggle)
mediawiki 1%3A1.43.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 417,464 kB
  • sloc: php: 1,062,949; javascript: 664,290; sql: 9,714; python: 5,458; xml: 3,489; sh: 1,131; makefile: 64
file content (224 lines) | stat: -rw-r--r-- 7,339 bytes parent folder | download
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
<?php

namespace MediaWiki\ParamValidator\TypeDef;

use InvalidArgumentException;
use JsonSchema\Constraints\Constraint;
use JsonSchema\Validator;
use LogicException;
use Wikimedia\Message\DataMessageValue;
use Wikimedia\ParamValidator\TypeDef;

/**
 * Type definition for array structures, typically
 * used for validating JSON request bodies.
 *
 * Failure codes:
 *  - 'notarray': The value is not an array.
 *
 * @since 1.42
 */
class ArrayDef extends TypeDef {

	/**
	 * (object) Schema settings.
	 *
	 */
	public const PARAM_SCHEMA = 'param-schema';

	public function supportsArrays() {
		return true;
	}

	public function validate( $name, $value, array $settings, array $options ) {
		if ( !is_array( $value ) ) {
			// Message used: paramvalidator-notarray
			$this->failure( 'notarray', $name, $value, $settings, $options );
		}

		if ( isset( $settings[ self::PARAM_SCHEMA ] ) ) {
			$schema = $settings[ self::PARAM_SCHEMA ];

			if ( !isset( $schema[ 'type' ] ) ) {
				throw new InvalidArgumentException( "Schema type not set " );
			}

			$types = (array)$schema['type'];
			foreach ( $types as $type ) {
				// @todo:  start using JsonSchemaTrait::normalizeJsonSchema
				// so we can also support the "list" and "map" types
				if ( ( $type !== 'object' ) && ( $type !== 'array' ) ) {
					throw new LogicException( 'Invalid data type' );
				}
			}

			$validator = new Validator();
			$validator->validate(
				$value, $schema,
				Constraint::CHECK_MODE_TYPE_CAST | Constraint::CHECK_MODE_APPLY_DEFAULTS );
			if ( !$validator->isValid() ) {
				$errorCode = 'schema-validation-failed';
				foreach ( $validator->getErrors() as $error ) {
					$message = DataMessageValue::new(
						"paramvalidator-$errorCode",
						[ $error[ 'message' ] ],
						$errorCode,
						[ 'schema-validation-error' => $error ]
					);
					$this->failure( $message, $name, $value, $settings, $options );
				}
			}
		}
		return $value;
	}

	public function stringifyValue( $name, $value, array $settings, array $options ) {
		if ( !is_array( $value ) ) {
			return parent::stringifyValue( $name, $value, $settings, $options );
		}

		return json_encode( $value );
	}

	/**
	 * Returns a JSON Schema of type array, with the input schema for each array item.
	 *
	 * If $itemSchema is a string, it must be a valid JSON type, and all list entries will be
	 * validated to be of that type.
	 *
	 * If $itemSchema is an array, it must represent a valid schema, and all list entries will
	 * be validated to be of that schema. Nested lists are supported, as are lists of maps and
	 * more complicated schemas.
	 *
	 * Examples:
	 *  A list of integers, like [ 1, 2, 3 ]
	 *   ArrayDef::makeListSchema( "integer" )
	 *  A list of strings, where each value must be either "a" or "b", like [ "a", "a", "b", "b" ]
	 * *   ArrayDef::makeListSchema( [ 'enum' => [ 'a', 'b' ] ] )
	 *  A list of lists of strings, like [ [ "foo", 'bar" ], [ "baz", "qux" ] ]
	 *   ArrayDef::makeListSchema( ArrayDef::makeListSchema( "string" ) )
	 *
	 * @since 1.43
	 *
	 * @param array|string $itemSchema
	 *
	 * @return array
	 */
	public static function makeListSchema( $itemSchema ): array {
		return [
			'type' => 'array',
			'items' => static::normalizeSchema( $itemSchema )
		];
	}

	/**
	 * Returns a JSON Schema of type object, with the input schema for each array item.
	 *
	 * If $entrySchema is a string, it must be a valid JSON type, and all map entries will be
	 * validated to be of that type.
	 *
	 * If $entrySchema is an array, it must represent a valid schema, and all map entries will
	 * be validated to be of that schema. Nested maps are supported, as are maps of lists and
	 * more complicated schemas
	 *
	 * Examples:
	 *  A map of integers, like [ 'key1' => 1, 'key2' => 2, 'key3' => 3 ]
	 *   ArrayDef::makeMapSchema( "integer" )
	 *  A map of where each value must be 0 or 1, like [ 'key1' => 1, 'key2' => 1, 'key3' => 0 ]
	 *   ArrayDef::makeMapSchema( [ 'enum' => [ 0, 1 ] ] )
	 *  A map of maps, like [ 'k1' => [ 'k2' => 'a' ], 'k3' => [ 'k4' => 'b', 'k5' => 'c' ] ]
	 *   ArrayDef::makeMapSchema( ArrayDef::makeMapSchema( "string" ) )
	 *
	 * @since 1.43
	 *
	 * @param array|string $entrySchema
	 *
	 * @return array
	 */
	public static function makeMapSchema( $entrySchema ): array {
		return [
			'type' => 'object',
			'additionalProperties' => static::normalizeSchema( $entrySchema )
		];
	}

	/**
	 * Returns a JSON Schema of type object, with properties defined by the function params.
	 *
	 * Any input schemas must either be a string corresponding to valid JSON types, or valid
	 * schemas. Nested schemas are supported.
	 *
	 * Examples:
	 *  An object with required parameters "a" and "b", where "a" must be an integer and "b" can
	 *  have one of the values "x", "y", or "z", no optional parameters, and additional parameters
	 *  are disallowed:
	 *   ArrayDef::makeObjectSchema( [ 'a' => 'integer', 'b' => [ 'enum' => [ 'x', 'y', 'z' ] ] ] )
	 *  The same object, but parameter "b" is optional:
	 *   ArrayDef::makeObjectSchema( [ 'a' => 'integer' ], [ 'b' => [ 'enum' => [ 'x', 'y', 'z' ] ] ] )
	 *  An object with no required properties, an optional property "a" of type string, with
	 *  arbitrary additional properties allowed (effectively, an arbitrary object, but if "a"
	 *  is present, it must be a string):
	 *   ArrayDef::makeObjectSchema( [ ], [ 'a' => 'string' ], true )
	 * @since 1.43
	 *
	 * @param array $required properties that are required to be present, as name/schema pairs
	 * @param array $optional properties that may or may not be present, as name/schema pairs
	 * @param array|bool|string $additional schema additional properties must match, or false
	 * 	to disallow additional properties, or true to allow arbitrary additional properties
	 *
	 * @return array
	 */
	public static function makeObjectSchema(
		array $required = [], array $optional = [], $additional = false
	): array {
		$schema = [ 'type' => 'object' ];

		if ( $required ) {
			foreach ( $required as $propertyName => $propertySchema ) {
				$schema['required'][] = $propertyName;
				$schema['properties'][$propertyName] = static::normalizeSchema( $propertySchema );
			}
		}

		if ( $optional ) {
			foreach ( $optional as $propertyName => $propertySchema ) {
				if ( isset( $schema['properties'][$propertyName] ) ) {
					throw new InvalidArgumentException(
						"Property {$propertyName} defined as both required and optional"
					);
				}
				$schema['properties'][$propertyName] = static::normalizeSchema( $propertySchema );
			}
		}

		// The easiest way to allow all extra properties is to not specify additionalProperties
		if ( $additional !== true ) {
			// A value of false disallows additional properties
			if ( $additional === false ) {
				$schema['additionalProperties'] = false;
			} else {
				$schema['additionalProperties'] = static::normalizeSchema( $additional );
			}
		}

		return $schema;
	}

	/**
	 * Returns a representation of the input schema
	 *
	 * If $schema is a string, it must be a valid JSON type.
	 * If $schema is an array, it must represent a valid schema.
	 *
	 * @param array|string $schema
	 *
	 * @return array
	 */
	private static function normalizeSchema( $schema ): array {
		if ( is_array( $schema ) ) {
			return $schema;
		} else {
			return [ 'type' => $schema ];
		}
	}
}