aboutsummaryrefslogtreecommitdiffstats
path: root/includes/json/JsonCodec.php
blob: d23693add1c757b45bb30e601189996c8c07f19b (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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Json
 */

namespace MediaWiki\Json;

use JsonException;
use JsonSerializable;
use MediaWiki\Parser\ParserOutput;
use stdClass;
use Wikimedia\Assert\Assert;

/**
 * Helper class to serialize/unserialize things to/from JSON.
 *
 * @stable to type
 * @since 1.36
 * @package MediaWiki\Json
 */
class JsonCodec implements JsonUnserializer, JsonSerializer {

	public function unserialize( $json, string $expectedClass = null ) {
		Assert::parameterType( [ 'stdClass', 'array', 'string' ], $json, '$json' );
		Assert::precondition(
			!$expectedClass || is_subclass_of( $expectedClass, JsonUnserializable::class ),
			'$expectedClass parameter must be subclass of JsonUnserializable, got ' . $expectedClass
		);
		if ( is_string( $json ) ) {
			$jsonStatus = FormatJson::parse( $json, FormatJson::FORCE_ASSOC );
			if ( !$jsonStatus->isGood() ) {
				throw new JsonException( "Bad JSON: {$jsonStatus}" );
			}
			$json = $jsonStatus->getValue();
		}

		if ( $json instanceof stdClass ) {
			$json = (array)$json;
		}

		if ( $this->containsComplexValue( $json ) ) {
			// Recursively unserialize the array values before unserializing
			// the array itself.
			$json = $this->unserializeArray( $json );
		}

		if ( !$this->canMakeNewFromValue( $json ) ) {
			if ( $expectedClass ) {
				throw new JsonException( 'JSON did not have ' . JsonConstants::TYPE_ANNOTATION );
			}
			return $json;
		}

		$class = $json[JsonConstants::TYPE_ANNOTATION];
		if ( $class == "ParserOutput" || $class == "MediaWiki\\Parser\\ParserOutput" ) {
			$class = ParserOutput::class; // T353835
		} elseif ( $class !== stdClass::class &&
			!( class_exists( $class ) && is_subclass_of( $class, JsonUnserializable::class ) )
		) {
			throw new JsonException( "Invalid target class {$class}" );
		}

		if ( $expectedClass && $class !== $expectedClass && !is_subclass_of( $class, $expectedClass ) ) {
			throw new JsonException(
				"Refusing to unserialize: expected $expectedClass, got $class"
			);
		}
		if ( $class === stdClass::class ) {
			unset( $json[JsonConstants::TYPE_ANNOTATION] );
			return (object)$json;
		}
		return $class::newFromJsonArray( $this, $json );
	}

	public function unserializeArray( array $array ): array {
		$unserializedExtensionData = [];
		foreach ( $array as $key => $value ) {
			if ( $key === JsonConstants::COMPLEX_ANNOTATION ) {
				/* don't include this in the result */
			} elseif (
				$this->canMakeNewFromValue( $value ) ||
				$this->containsComplexValue( $value )
			) {
				$unserializedExtensionData[$key] = $this->unserialize( $value );
			} else {
				$unserializedExtensionData[$key] = $value;
			}
		}
		return $unserializedExtensionData;
	}

	private function serializeOne( &$value ) {
		if ( $value instanceof JsonSerializable ) {
			$value = $value->jsonSerialize();
			if ( !is_array( $value ) ) {
				// Although JsonSerializable doesn't /require/ the result to be
				// an array, JsonCodec and JsonUnserializableTrait do.
				throw new JsonException( "jsonSerialize didn't return array" );
			}
			$value[JsonConstants::COMPLEX_ANNOTATION] = true;
			// The returned array may still have instance of JsonSerializable,
			// stdClass, or array, so fall through to recursively handle these.
		} elseif ( is_object( $value ) && get_class( $value ) === stdClass::class ) {
			// T312589: if $value is stdObject, mark the type
			// so we unserialize as stdObject as well.
			$value = (array)$value;
			$value[JsonConstants::TYPE_ANNOTATION] = stdClass::class;
			$value[JsonConstants::COMPLEX_ANNOTATION] = true;
			// Fall through to handle the property values
		}
		if ( is_array( $value ) ) {
			$is_complex = false;
			// Recursively convert array values to serializable form
			foreach ( $value as &$v ) {
				if ( is_object( $v ) || is_array( $v ) ) {
					$v = $this->serializeOne( $v );
					if ( isset( $v[JsonConstants::COMPLEX_ANNOTATION] ) ) {
						$is_complex = true;
					}
				}
			}
			if ( $is_complex ) {
				$value[JsonConstants::COMPLEX_ANNOTATION] = true;
			}
		} elseif ( !is_scalar( $value ) && $value !== null ) {
			$details = is_object( $value ) ? get_class( $value ) : gettype( $value );
			throw new JsonException(
				'Unable to serialize JSON: ' . $details
			);
		}
		return $value;
	}

	public function serialize( $value ) {
		// Detect if the array contained any properties non-serializable
		// to json.
		// TODO: make detectNonSerializableData not choke on cyclic structures.
		$unserializablePath = $this->detectNonSerializableDataInternal(
			$value, false, '$', false
		);
		if ( $unserializablePath ) {
			throw new JsonException(
				"Non-unserializable property set at {$unserializablePath}"
			);
		}
		// Recursively convert stdClass and JsonSerializable
		// to serializable arrays
		$value = $this->serializeOne( $value );
		// Format as JSON
		$json = FormatJson::encode( $value, false, FormatJson::ALL_OK );
		if ( !$json ) {
			try {
				// Try to collect more information on the failure.
				$details = $this->detectNonSerializableData( $value );
			} catch ( \Throwable $t ) {
				$details = $t->getMessage();
			}
			throw new JsonException(
				'Failed to encode JSON. ' .
				'Error: ' . json_last_error_msg() . '. ' .
				'Details: ' . $details
			);
		}

		return $json;
	}

	/**
	 * Is it likely possible to make a new instance from $json serialization?
	 * @param mixed $json
	 * @return bool
	 */
	private function canMakeNewFromValue( $json ): bool {
		$classAnnotation = JsonConstants::TYPE_ANNOTATION;
		if ( is_array( $json ) ) {
			return array_key_exists( $classAnnotation, $json ) &&
				# T313818: conflict with ParserOutput::detectAndEncodeBinary()
				$json[$classAnnotation] !== 'string';
		}

		if ( is_object( $json ) ) {
			return property_exists( $json, $classAnnotation );
		}
		return false;
	}

	/**
	 * Does this serialized array contain a complex value (a serialized class
	 * or an array which itself contains a serialized class)?
	 * @param mixed $json
	 * @return bool
	 */
	private function containsComplexValue( $json ): bool {
		if ( is_array( $json ) ) {
			return array_key_exists( JsonConstants::COMPLEX_ANNOTATION, $json );
		}
		return false;
	}

	/**
	 * Recursive check for ability to serialize $value to JSON via FormatJson::encode().
	 *
	 * @param mixed $value
	 * @param bool $expectUnserialize
	 * @param string $accumulatedPath
	 * @param bool $exhaustive Whether to (slowly) completely traverse the
	 *  $value in order to find the precise location of a problem
	 * @return string|null JSON path to first encountered non-serializable property or null.
	 */
	private function detectNonSerializableDataInternal(
		$value,
		bool $expectUnserialize,
		string $accumulatedPath,
		bool $exhaustive = false
	): ?string {
		if (
			$this->canMakeNewFromValue( $value ) ||
			$this->containsComplexValue( $value )
		) {
			// Contains a conflicting use of JsonConstants::TYPE_ANNOTATION or
			// JsonConstants::COMPLEX_ANNOTATION; in the future we might use
			// an alternative encoding for these objects to allow them.
			return $accumulatedPath . ': conflicting use of protected property';
		}
		if ( is_object( $value ) ) {
			if ( get_class( $value ) === stdClass::class ) {
				$value = (array)$value;
			} elseif (
				$expectUnserialize ?
				$value instanceof JsonUnserializable :
				$value instanceof JsonSerializable
			) {
				if ( $exhaustive ) {
					// Call the appropriate serialization method and recurse to
					// ensure contents are also serializable.
					$value = $value->jsonSerialize();
					if ( !is_array( $value ) ) {
						return $accumulatedPath . ": jsonSerialize didn't return array";
					}
				} else {
					// Assume that serializable objects contain 100%
					// serializable contents in their representation.
					return null;
				}
			} else {
				// Instances of classes other the \stdClass or JsonSerializable can not be serialized to JSON.
				return $accumulatedPath . ': ' . get_class( $value );
			}
		}
		if ( is_array( $value ) ) {
			foreach ( $value as $key => $propValue ) {
				$propValueNonSerializablePath = $this->detectNonSerializableDataInternal(
					$propValue,
					$expectUnserialize,
					$accumulatedPath . '.' . $key,
					$exhaustive
				);
				if ( $propValueNonSerializablePath !== null ) {
					return $propValueNonSerializablePath;
				}
			}
		} elseif ( !is_scalar( $value ) && $value !== null ) {
			return $accumulatedPath . ': nonscalar ' . gettype( $value );
		}
		return null;
	}

	/**
	 * Checks if the $value is JSON-serializable (contains only scalar values)
	 * and returns a JSON-path to the first non-serializable property encountered.
	 *
	 * @param mixed $value
	 * @param bool $expectUnserialize whether to expect the $value to be unserializable with JsonUnserializer.
	 * @return string|null JSON path to first encountered non-serializable property or null.
	 * @see JsonUnserializer
	 * @since 1.36
	 */
	public function detectNonSerializableData( $value, bool $expectUnserialize = false ): ?string {
		return $this->detectNonSerializableDataInternal( $value, $expectUnserialize, '$', true );
	}
}