Debian Codegraph @

includes/json/JsonCodec.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Json
20 */
21
22 namespace MediaWiki\Json;
23
24 use InvalidArgumentException;
25 use JsonException;
26 use JsonSerializable;
27 use Psr\Container\ContainerInterface;
28 use ReflectionClass;
29 use stdClass;
30 use Wikimedia\Assert\Assert;
31 use Wikimedia\JsonCodec\JsonClassCodec;
32 use Wikimedia\JsonCodec\JsonCodecable;
33 use Wikimedia\Parsoid\Core\PageBundle;
34
35 /**
36 * Helper class to serialize/deserialize things to/from JSON.
37 *
38 * @stable to type
39 * @since 1.36
40 * @package MediaWiki\Json
41 */
42 class JsonCodec
43 extends \Wikimedia\JsonCodec\JsonCodec
44 implements JsonDeserializer, JsonSerializer
45 {
46
47 /**
48 * When true, add extra properties to the serialized output for
49 * backwards compatibility. This will eventually be made a
50 * configuration variable and/or removed. (T367584)
51 */
52 private bool $backCompat = true;
53
54 /**
55 * Create a new JsonCodec, with optional access to the provided services.
56 */
57 public function __construct( ?ContainerInterface $services = null ) {
58 parent::__construct( $services );
59 // Forward-compatibility with MW 1.44: ensure Parsoid PageBundle is
60 // codecable
61 $this->addCodecFor( PageBundle::class, new class implements JsonClassCodec {
62 /** @inheritDoc */
63 public function toJsonArray( $obj ): array {
64 '@phan-var PageBundle $obj'; /** @var PageBundle $obj */
65 return [
66 'html' => $obj->html,
67 'parsoid' => $obj->parsoid,
68 'mw' => $obj->mw,
69 'version' => $obj->version,
70 'headers' => $obj->headers,
71 'contentmodel' => $obj->contentmodel,
72 ];
73 }
74
75 /** @inheritDoc */
76 public function newFromJsonArray( string $className, array $json ) {
77 // @phan-suppress-next-line PhanTypeMismatchReturn
78 return new PageBundle(
79 $json['html'] ?? '',
80 $json['parsoid'] ?? null,
81 $json['mw'] ?? null,
82 $json['version'] ?? null,
83 $json['headers'] ?? null,
84 $json['contentmodel'] ?? null
85 );
86 }
87
88 /** @inheritDoc */
89 public function jsonClassHintFor( string $className, string $keyName ) {
90 return null;
91 }
92 } );
93 }
94
95 /**
96 * Support the JsonCodecable interface by maintaining a mapping of
97 * class names to codecs.
98 * @param class-string $className
99 * @return ?JsonClassCodec
100 */
101 protected function codecFor( string $className ): ?JsonClassCodec {
102 static $deserializableCodec = null;
103 static $serializableCodec = null;
104 $codec = parent::codecFor( $className );
105 if ( $codec !== null ) {
106 return $codec;
107 }
108 // Resolve class aliases to ensure we don't use split codecs
109 $className = ( new ReflectionClass( $className ) )->getName();
110 // Provide a codec for JsonDeserializable objects
111 if ( is_a( $className, JsonDeserializable::class, true ) ) {
112 if ( $deserializableCodec === null ) {
113 $deserializableCodec = new JsonDeserializableCodec( $this );
114 }
115 $codec = $deserializableCodec;
116 $this->addCodecFor( $className, $codec );
117 return $codec;
118 }
119 // Provide a codec for JsonSerializable objects:
120 // NOTE this is for compatibility only and does not deserialize!
121 if ( is_a( $className, JsonSerializable::class, true ) ) {
122 $codec = JsonSerializableCodec::getInstance();
123 $this->addCodecFor( $className, $codec );
124 return $codec;
125 }
126 return null;
127 }
128
129 /** @inheritDoc */
130 protected function markArray( array &$value, string $className, ?string $classHint ): void {
131 parent::markArray( $value, $className, $classHint );
132 // Temporarily for backward compatibility add COMPLEX_ANNOTATION as well
133 if ( $this->backCompat ) {
134 $value[JsonConstants::COMPLEX_ANNOTATION] = true;
135 if ( ( $value[JsonConstants::TYPE_ANNOTATION] ?? null ) === 'array' ) {
136 unset( $value[JsonConstants::TYPE_ANNOTATION] );
137 }
138 }
139 }
140
141 /** @inheritDoc */
142 protected function isArrayMarked( array $value ): bool {
143 // Temporarily for backward compatibility look for COMPLEX_ANNOTATION as well
144 if ( $this->backCompat && array_key_exists( JsonConstants::COMPLEX_ANNOTATION, $value ) ) {
145 return true;
146 }
147 if ( ( $value['_type_'] ?? null ) === 'string' ) {
148 // T313818: see ParserOutput::detectAndEncodeBinary()
149 return false;
150 }
151 return parent::isArrayMarked( $value );
152 }
153
154 /** @inheritDoc */
155 protected function unmarkArray( array &$value, ?string $classHint ): string {
156 // Temporarily use the presence of COMPLEX_ANNOTATION as a hint that
157 // the type is 'array'
158 if (
159 $this->backCompat &&
160 $classHint === null &&
161 array_key_exists( JsonConstants::COMPLEX_ANNOTATION, $value )
162 ) {
163 $classHint = 'array';
164 }
165 // @phan-suppress-next-line PhanUndeclaredClassReference 'array'
166 $className = parent::unmarkArray( $value, $classHint );
167 // Remove the temporarily-added COMPLEX_ANNOTATION
168 if ( $this->backCompat ) {
169 unset( $value[JsonConstants::COMPLEX_ANNOTATION] );
170 }
171 return $className;
172 }
173
174 /** @deprecated since 1.43; use ::deserialize() */
175 public function unserialize( $json, ?string $expectedClass = null ) {
176 return $this->deserialize( $json, $expectedClass );
177 }
178
179 public function deserialize( $json, ?string $expectedClass = null ) {
180 Assert::parameterType( [ 'stdClass', 'array', 'string' ], $json, '$json' );
181 Assert::precondition(
182 !$expectedClass ||
183 is_subclass_of( $expectedClass, JsonDeserializable::class ) ||
184 is_subclass_of( $expectedClass, JsonCodecable::class ),
185 '$expectedClass parameter must be subclass of JsonDeserializable or JsonCodecable, got ' . $expectedClass
186 );
187 if ( is_string( $json ) ) {
188 $jsonStatus = FormatJson::parse( $json, FormatJson::FORCE_ASSOC );
189 if ( !$jsonStatus->isGood() ) {
190 throw new JsonException( "Bad JSON: {$jsonStatus}" );
191 }
192 $json = $jsonStatus->getValue();
193 }
194
195 if ( $json instanceof stdClass ) {
196 $json = (array)$json;
197 }
198
199 if ( $expectedClass !== null ) {
200 // Make copy of $json to avoid unmarking the 'real thing'
201 $jsonCopy = $json;
202 if ( is_array( $jsonCopy ) && $this->isArrayMarked( $jsonCopy ) ) {
203 $got = $this->unmarkArray( $jsonCopy, $expectedClass );
204 // Compare $got to $expectedClass in a way that works in the
205 // presence of aliases
206 if ( is_a( $got, $expectedClass, true ) ) {
207 // Everything ok!
208 } else {
209 throw new JsonException( "Expected {$expectedClass} got {$got}" );
210 }
211 } else {
212 $got = get_debug_type( $json );
213 throw new JsonException( "Expected {$expectedClass} got {$got}" );
214 }
215 }
216 try {
217 $result = is_array( $json ) ? $this->newFromJsonArray( $json ) : $json;
218 } catch ( InvalidArgumentException $e ) {
219 throw new JsonException( $e->getMessage() );
220 }
221 if ( $expectedClass && !is_a( $result, $expectedClass, false ) ) {
222 throw new JsonException( "Unexpected class: {$expectedClass}" );
223 }
224 return $result;
225 }
226
227 /** @deprecated since 1.43; use ::deserializeArray() */
228 public function unserializeArray( array $array ): array {
229 return $this->deserializeArray( $array );
230 }
231
232 public function deserializeArray( array $array ): array {
233 try {
234 // Pass a class hint here to ensure we recurse into the array.
235 // @phan-suppress-next-line PhanUndeclaredClassReference 'array'
236 return $this->newFromJsonArray( $array, 'array' );
237 } catch ( InvalidArgumentException $e ) {
238 throw new JsonException( $e->getMessage() );
239 }
240 }
241
242 public function serialize( $value ) {
243 // Recursively convert stdClass, JsonSerializable, and JsonCodecable
244 // to serializable arrays
245 try {
246 $value = $this->toJsonArray( $value );
247 } catch ( InvalidArgumentException $e ) {
248 throw new JsonException( $e->getMessage() );
249 }
250 // Format as JSON
251 $json = FormatJson::encode( $value, false, FormatJson::ALL_OK );
252 if ( !$json ) {
253 try {
254 // Try to collect more information on the failure.
255 $details = $this->detectNonSerializableData( $value );
256 } catch ( \Throwable $t ) {
257 $details = $t->getMessage();
258 }
259 throw new JsonException(
260 'Failed to encode JSON. ' .
261 'Error: ' . json_last_error_msg() . '. ' .
262 'Details: ' . $details
263 );
264 }
265
266 return $json;
267 }
268
269 // The code below this point is used only for diagnostics; in particular
270 // for the ::detectNonSerializableData() method which is used to provide
271 // debugging information in the event of a serialization failure.
272
273 /**
274 * Recursive check for ability to serialize $value to JSON via FormatJson::encode().
275 *
276 * @param mixed $value
277 * @param bool $expectDeserialize
278 * @param string $accumulatedPath
279 * @param bool $exhaustive Whether to (slowly) completely traverse the
280 * $value in order to find the precise location of a problem
281 * @return string|null JSON path to first encountered non-serializable property or null.
282 */
283 private function detectNonSerializableDataInternal(
284 $value,
285 bool $expectDeserialize,
286 string $accumulatedPath,
287 bool $exhaustive = false
288 ): ?string {
289 if (
290 ( is_array( $value ) && $this->isArrayMarked( $value ) ) ||
291 ( $value instanceof stdClass && $this->isArrayMarked( (array)$value ) )
292 ) {
293 // Contains a conflicting use of JsonConstants::TYPE_ANNOTATION or
294 // JsonConstants::COMPLEX_ANNOTATION; in the future we might use
295 // an alternative encoding for these objects to allow them.
296 return $accumulatedPath . ': conflicting use of protected property';
297 }
298 if ( is_object( $value ) ) {
299 if ( get_class( $value ) === stdClass::class ) {
300 $value = (array)$value;
301 } elseif ( $value instanceof JsonCodecable ) {
302 if ( $exhaustive ) {
303 // Call the appropriate serialization method and recurse to
304 // ensure contents are also serializable.
305 $codec = $this->codecFor( get_class( $value ) );
306 $value = $codec->toJsonArray( $value );
307 } else {
308 // Assume that serializable objects contain 100%
309 // serializable contents in their representation.
310 return null;
311 }
312 } elseif (
313 $expectDeserialize ?
314 $value instanceof JsonDeserializable :
315 $value instanceof JsonSerializable
316 ) {
317 if ( $exhaustive ) {
318 // Call the appropriate serialization method and recurse to
319 // ensure contents are also serializable.
320 '@phan-var JsonSerializable $value';
321 $value = $value->jsonSerialize();
322 if ( !is_array( $value ) ) {
323 return $accumulatedPath . ": jsonSerialize didn't return array";
324 }
325 } else {
326 // Assume that serializable objects contain 100%
327 // serializable contents in their representation.
328 return null;
329 }
330 } else {
331 // Instances of classes other the \stdClass or JsonSerializable can not be serialized to JSON.
332 return $accumulatedPath . ': ' . get_debug_type( $value );
333 }
334 }
335 if ( is_array( $value ) ) {
336 foreach ( $value as $key => $propValue ) {
337 $propValueNonSerializablePath = $this->detectNonSerializableDataInternal(
338 $propValue,
339 $expectDeserialize,
340 $accumulatedPath . '.' . $key,
341 $exhaustive
342 );
343 if ( $propValueNonSerializablePath !== null ) {
344 return $propValueNonSerializablePath;
345 }
346 }
347 } elseif ( !is_scalar( $value ) && $value !== null ) {
348 return $accumulatedPath . ': nonscalar ' . get_debug_type( $value );
349 }
350 return null;
351 }
352
353 /**
354 * Checks if the $value is JSON-serializable (contains only scalar values)
355 * and returns a JSON-path to the first non-serializable property encountered.
356 *
357 * @param mixed $value
358 * @param bool $expectDeserialize whether to expect the $value to be deserializable with JsonDeserializer.
359 * @return string|null JSON path to first encountered non-serializable property or null.
360 * @see JsonDeserializer
361 * @since 1.36
362 */
363 public function detectNonSerializableData( $value, bool $expectDeserialize = false ): ?string {
364 return $this->detectNonSerializableDataInternal( $value, $expectDeserialize, '$', true );
365 }
366 }