Debian Codegraph @

vendor/wikimedia/json-codec/src/JsonCodec.php

raw
1 <?php
2 declare( strict_types=1 );
3
4 /**
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 namespace Wikimedia\JsonCodec;
24
25 use Exception;
26 use InvalidArgumentException;
27 use Psr\Container\ContainerInterface;
28 use Psr\Container\NotFoundExceptionInterface;
29 use ReflectionClass;
30 use stdClass;
31
32 /**
33 * Helper class to serialize/unserialize things to/from JSON.
34 */
35 class JsonCodec implements JsonCodecInterface {
36 /** @var ContainerInterface Service container */
37 protected ContainerInterface $serviceContainer;
38
39 /** @var array<class-string,JsonClassCodec> Class codecs */
40 protected array $codecs;
41
42 /**
43 * Name of the property where class information is stored; it also
44 * is used to mark "complex" arrays, and as a place to store the contents
45 * of any pre-existing array property that happened to have the same name.
46 */
47 protected const TYPE_ANNOTATION = '_type_';
48
49 /**
50 * @param ?ContainerInterface $serviceContainer
51 */
52 public function __construct( ?ContainerInterface $serviceContainer = null ) {
53 $this->serviceContainer = $serviceContainer ??
54 // Use an empty container if none is provided.
55 new class implements ContainerInterface {
56 /**
57 * @param string $id
58 * @return never
59 */
60 public function get( $id ) {
61 throw new class( "not found" ) extends Exception implements NotFoundExceptionInterface {
62 };
63 }
64
65 /** @inheritDoc */
66 public function has( string $id ): bool {
67 return false;
68 }
69 };
70 $this->addCodecFor(
71 stdClass::class, JsonStdClassCodec::getInstance()
72 );
73 }
74
75 /**
76 * Recursively converts a given object to a JSON-encoded string.
77 * While serializing the $value JsonCodec delegates to the appropriate
78 * JsonClassCodecs of any classes which implement JsonCodecable.
79 *
80 * If a $classHint is provided and matches the type of the value,
81 * then type information will not be included in the generated JSON;
82 * otherwise an appropriate class name will be added to the JSON to
83 * guide deserialization.
84 *
85 * @param mixed|null $value
86 * @param class-string|Hint|null $classHint An optional hint to
87 * the type of the encoded object. If this is provided and matches
88 * the type of $value, then explicit type information will be omitted
89 * from the generated JSON, which saves some space.
90 * @return string
91 */
92 public function toJsonString( $value, $classHint = null ): string {
93 return json_encode(
94 $this->toJsonArray( $value, $classHint ),
95 JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE |
96 JSON_HEX_TAG | JSON_HEX_AMP
97 );
98 }
99
100 /**
101 * Recursively converts a JSON-encoded string to an object value or scalar.
102 * While deserializing the $json JsonCodec delegates to the appropriate
103 * JsonClassCodecs of any classes which implement JsonCodecable.
104 *
105 * For objects encoded using implicit class information, a "class hint"
106 * can be provided to guide deserialization; this is unnecessary for
107 * objects serialized with explicit classes.
108 *
109 * @param string $json A JSON-encoded string
110 * @param class-string|Hint|null $classHint An optional hint to
111 * the type of the encoded object. In the absence of explicit
112 * type information in the JSON, this will be used as the type of
113 * the created object.
114 * @return mixed|null
115 */
116 public function newFromJsonString( $json, $classHint = null ) {
117 return $this->newFromJsonArray(
118 json_decode( $json, true ), $classHint
119 );
120 }
121
122 /**
123 * Maintain a cache giving the codec for a given class name.
124 *
125 * Reusing this JsonCodec object will also reuse this cache, which
126 * could improve performance somewhat.
127 *
128 * @param class-string $className
129 * @return ?JsonClassCodec a codec for the class, or null if the class is
130 * not serializable.
131 */
132 protected function codecFor( string $className ): ?JsonClassCodec {
133 $codec = $this->codecs[$className] ?? null;
134 if ( $codec !== null ) {
135 return $codec;
136 }
137 // Check for class aliases to ensure we don't use split codecs
138 $trueName = ( new ReflectionClass( $className ) )->getName();
139 if ( $trueName !== $className ) {
140 $codec = $this->codecs[$trueName] ?? null;
141 if ( $codec !== null ) {
142 $this->codecs[$className] = $codec;
143 return $codec;
144 }
145 $className = $trueName;
146 }
147 if ( is_a( $className, JsonCodecable::class, true ) ) {
148 $codec = $className::jsonClassCodec( $this, $this->serviceContainer );
149 $this->codecs[$className] = $codec;
150 }
151 return $codec;
152 }
153
154 /**
155 * Allow the use of a customized encoding for the given class; the given
156 * className need not be a JsonCodecable and if it *does* correspond to
157 * a JsonCodecable it will override the class codec specified by the
158 * JsonCodecable.
159 * @param class-string $className
160 * @param JsonClassCodec $codec A codec to use for $className
161 */
162 public function addCodecFor( string $className, JsonClassCodec $codec ): void {
163 // Resolve aliases
164 $className = ( new ReflectionClass( $className ) )->getName();
165 // Sanity check
166 if ( isset( $this->codecs[$className] ) ) {
167 throw new InvalidArgumentException(
168 "Codec already present for $className"
169 );
170 }
171 $this->codecs[$className] = $codec;
172 }
173
174 /**
175 * Recursively converts a given object to an associative array
176 * which can be json-encoded. (When embedding an object into
177 * another context it is sometimes useful to have the array
178 * representation rather than the string JSON form of the array;
179 * this can also be useful if you want to pretty-print the result,
180 * etc.) While converting $value the JsonCodec delegates to the
181 * appropriate JsonClassCodecs of any classes which implement
182 * JsonCodecable.
183 *
184 * If a $classHint is provided and matches the type of the value,
185 * then type information will not be included in the generated JSON;
186 * otherwise an appropriate class name will be added to the JSON to
187 * guide deserialization.
188 *
189 * @param mixed|null $value
190 * @param class-string|Hint|null $classHint An optional hint to
191 * the type of the encoded object. If this is provided and matches
192 * the type of $value, then explicit type information will be omitted
193 * from the generated JSON, which saves some space.
194 * @return mixed|null
195 */
196 public function toJsonArray( $value, $classHint = null ) {
197 $is_complex = false;
198 $className = 'array';
199 $codec = null;
200
201 // Process class hints
202 $arrayClassHint = null;
203 $forceBraces = null;
204 $allowInherited = false;
205 if ( is_string( $classHint ) && str_ends_with( $classHint, '[]' ) ) {
206 // back-compat
207 $classHint = new Hint( substr( $classHint, 0, -2 ), Hint::LIST );
208 }
209 while ( $classHint instanceof Hint ) {
210 if ( $classHint->modifier === Hint::USE_SQUARE ) {
211 // Allow list-like serializations to use []
212 $classHint = $classHint->parent;
213 $forceBraces = false;
214 } elseif ( $classHint->modifier === Hint::ALLOW_OBJECT ) {
215 // Force empty arrays to serialize as {}
216 $classHint = $classHint->parent;
217 $forceBraces = true;
218 } elseif ( $classHint->modifier === Hint::LIST ) {
219 // Array whose values are the hinted type
220 $arrayClassHint = $classHint->parent;
221 $classHint = 'array';
222 } elseif ( $classHint->modifier === Hint::STDCLASS ) {
223 // stdClass whose values are the hinted type
224 $arrayClassHint = $classHint->parent;
225 $classHint = stdClass::class;
226 } elseif ( $classHint->modifier === Hint::INHERITED ) {
227 // Allow the hint to match subclasses of the hinted class
228 $classHint = $classHint->parent;
229 $allowInherited = true;
230 } elseif ( $classHint->modifier === Hint::ONLY_FOR_DECODE ) {
231 // Don't use this hint for serialization.
232 $classHint = null;
233 } elseif ( $classHint->modifier === Hint::DEFAULT ) {
234 // No-op, included for completeness
235 $classHint = $classHint->parent;
236 } else {
237 throw new InvalidArgumentException( 'bad hint modifier: ' . $classHint->modifier );
238 }
239 }
240 if ( is_object( $value ) ) {
241 $className = get_class( $value );
242 $codec = $this->codecFor( $className );
243 if ( $codec !== null ) {
244 $value = $codec->toJsonArray( $value );
245 $is_complex = true;
246 }
247 // Tweak the codec used for class hints if $allowInherited is true
248 // in order to match the codec we would use for deserialization.
249 if (
250 $allowInherited &&
251 $classHint !== null &&
252 is_a( $className, $classHint, true ) &&
253 // extra comparison to let phan know $classHint is not 'array'
254 $classHint !== 'array'
255 ) {
256 $className = $classHint;
257 $codec = $this->codecFor( $className );
258 }
259 } elseif (
260 is_array( $value ) && $this->isArrayMarked( $value )
261 ) {
262 $is_complex = true;
263 }
264 if ( is_array( $value ) ) {
265 // Recursively convert array values to serializable form
266 foreach ( $value as $key => &$v ) {
267 if ( is_object( $v ) || is_array( $v ) ) {
268 $propClassHint = $arrayClassHint;
269 $propClassHint ??= ( $codec === null ? null :
270 // phan can't tell that $codec is null when $className is 'array'
271 // @phan-suppress-next-line PhanUndeclaredClassReference
272 $codec->jsonClassHintFor( $className, (string)$key )
273 );
274 $v = $this->toJsonArray( $v, $propClassHint );
275 if (
276 $propClassHint !== null ||
277 $this->isArrayMarked( $v )
278 ) {
279 // an array which contains complex components is
280 // itself complex.
281 $is_complex = true;
282 }
283 }
284 }
285 // Ok, now mark the array, being careful to transfer away
286 // any fields with the same names as our markers.
287 if ( $is_complex || $classHint !== null ) {
288 if (
289 $forceBraces === null &&
290 $className !== 'array' &&
291 array_is_list( $value )
292 ) {
293 // Include the type annotation (by clearing the
294 // hint) if $forceBraces isn't false and it is
295 // necessary to break up a list. This ensures that
296 // all objects have a JSON encoding in the `{...}`
297 // style, even if they happen to have all-numeric
298 // keys.
299 $classHint = null;
300 }
301 // Even if $className === $classHint we may need to record this
302 // array as "complex" (ie, requires recursion to process
303 // individual values during deserialization)
304 // @phan-suppress-next-line PhanUndeclaredClassReference 'array'
305 $this->markArray(
306 $value, $className, $classHint
307 );
308 if ( $forceBraces === true && array_is_list( $value ) ) {
309 // It is somewhat surprising for ::toJsonArray() to return
310 // an object (rather than an array), but allow this case
311 // if the class hint expressly asked for it.
312 $value = (object)$value;
313 }
314 }
315 } elseif ( !is_scalar( $value ) && $value !== null ) {
316 throw new InvalidArgumentException(
317 'Unable to serialize JSON: ' . get_debug_type( $value )
318 );
319 }
320 return $value;
321 }
322
323 /**
324 * Recursively converts an associative array (or scalar) to an
325 * object value (or scalar). While converting this value JsonCodec
326 * delegates to the appropriate JsonClassCodecs of any classes which
327 * implement JsonCodecable.
328 *
329 * For objects encoded using implicit class information, a "class hint"
330 * can be provided to guide deserialization; this is unnecessary for
331 * objects serialized with explicit classes.
332 *
333 * @param mixed|null $json
334 * @param class-string|Hint|null $classHint An optional hint to
335 * the type of the encoded object. In the absence of explicit
336 * type information in the JSON, this will be used as the type of
337 * the created object.
338 * @return mixed|null
339 */
340 public function newFromJsonArray( $json, $classHint = null ) {
341 if ( $json instanceof stdClass ) {
342 // We *shouldn't* be given an object... but we might.
343 $json = (array)$json;
344 }
345
346 // Process class hints
347 $arrayClassHint = null;
348 if ( is_string( $classHint ) && str_ends_with( $classHint, '[]' ) ) {
349 // back-compat
350 $classHint = new Hint( substr( $classHint, 0, -2 ), Hint::LIST );
351 }
352 while ( $classHint instanceof Hint ) {
353 if ( $classHint->modifier === Hint::LIST ) {
354 $arrayClassHint = $classHint->parent;
355 $classHint = 'array';
356 } elseif ( $classHint->modifier === Hint::STDCLASS ) {
357 $arrayClassHint = $classHint->parent;
358 $classHint = stdClass::class;
359 } else {
360 $classHint = $classHint->parent;
361 }
362 }
363
364 // Is this an array containing a complex value?
365 if (
366 is_array( $json ) && (
367 $this->isArrayMarked( $json ) || $classHint !== null
368 )
369 ) {
370 // Read out our metadata
371 // @phan-suppress-next-line PhanUndeclaredClassReference 'array'
372 $className = $this->unmarkArray( $json, $classHint );
373 // Create appropriate codec
374 $codec = null;
375 if ( $className !== 'array' ) {
376 $codec = $this->codecFor( $className );
377 if ( $codec === null ) {
378 throw new InvalidArgumentException(
379 "Unable to deserialize JSON for $className"
380 );
381 }
382 }
383 // Recursively unserialize the array contents.
384 $unserialized = [];
385 foreach ( $json as $key => $value ) {
386 $propClassHint = $arrayClassHint;
387 $propClassHint ??= ( $codec === null ? null :
388 // phan can't tell that $codec is null when $className is 'array'
389 // @phan-suppress-next-line PhanUndeclaredClassReference
390 $codec->jsonClassHintFor( $className, (string)$key )
391 );
392 if ( $value instanceof stdClass ) {
393 // Again, we *shouldn't* be given an object... but we might.
394 $value = (array)$value;
395 }
396 if (
397 is_array( $value ) && (
398 $this->isArrayMarked( $value ) || $propClassHint !== null
399 )
400 ) {
401 $unserialized[$key] = $this->newFromJsonArray( $value, $propClassHint );
402 } else {
403 $unserialized[$key] = $value;
404 }
405 }
406 // Use a JsonCodec to create the object instance if appropriate.
407 if ( $className === 'array' ) {
408 $json = $unserialized;
409 } else {
410 $json = $codec->newFromJsonArray( $className, $unserialized );
411 }
412 }
413 return $json;
414 }
415
416 // Functions to mark/unmark arrays and record a class name using a
417 // single reserved field, named by self::TYPE_ANNOTATION. A
418 // subclass can provide alternate implementations of these methods
419 // if it wants to use a different reserved field or else wishes to
420 // reserve more fields/encode certain types more compactly/flag
421 // certain types of values. For example: a subclass could choose
422 // to discard all hints in `markArray` in order to explicitly mark
423 // all types in preparation for a format change; or all values of
424 // type DocumentFragment might get a marker flag added so they can
425 // be identified without knowledge of the class hint; or perhaps a
426 // separate schema can be used to record class names more
427 // compactly.
428
429 /**
430 * Determine if the given value is "marked"; that is, either
431 * represents a object type encoded using a JsonClassCodec or else
432 * is an array which contains values (or contains arrays
433 * containing values, etc) which are object types. The values of
434 * unmarked arrays are not decoded, in order to speed up the
435 * decoding process. Arrays may also be marked even if they do
436 * not represent object types (or an array recursively containing
437 * them) if they contain keys that need to be escaped ("false
438 * marks"); as such this method is called both on the raw results
439 * of JsonClassCodec (to check for "false marks") as well as on
440 * encoded arrays (to find "true marks").
441 *
442 * Arrays do not have to be marked if the decoder has a class hint.
443 *
444 * @param array $value An array result from `JsonClassCodec::toJsonArray()`,
445 * or an array result from `::markArray()`
446 * @return bool Whether the $value is marked
447 */
448 protected function isArrayMarked( array $value ): bool {
449 return array_key_exists( self::TYPE_ANNOTATION, $value );
450 }
451
452 /**
453 * Record a mark in the array, reversibly.
454 *
455 * The mark should record the class name, if it is different from
456 * the class hint. The result does not need to trigger
457 * `::isArrayMarked` if there is an accurate class hint present,
458 * but otherwise the result should register as marked. The
459 * provided value may be a "complex" array (one that recursively
460 * contains encoded object) or an array with a "false mark"; in
461 * both cases the provided $className will be `array`.
462 *
463 * @param array &$value An array result from `JsonClassCodec::toJsonArray()`
464 * or a "complex" array
465 * @param 'array'|class-string $className The name of the class encoded
466 * by the codec, or else `array` if $value is a "complex" array or a
467 * "false mark"
468 * @param 'array'|class-string|null $classHint The class name provided as
469 * a hint to the encoder, and which will be in turn provided as a hint
470 * to the decoder, or `null` if no hint was provided. The class hint
471 * will be `array` when the array is a homogeneous list of objects.
472 */
473 protected function markArray( array &$value, string $className, ?string $classHint ): void {
474 // We're going to use an array key, but first we have to see whether it
475 // was already present in the array we've been given, in which case
476 // we need to escape it (by hoisting into a child array).
477 if ( array_key_exists( self::TYPE_ANNOTATION, $value ) ) {
478 // @phan-suppress-next-line PhanUndeclaredClassReference 'array'
479 if ( !self::classEquals( $className, $classHint ) ) {
480 $value[self::TYPE_ANNOTATION] = [ $value[self::TYPE_ANNOTATION], $className ];
481 } else {
482 // Omit $className since it matches the $classHint, but we still
483 // need to escape the field to make it clear it was marked.
484 // (If the class hint hadn't matched, the proper class name
485 // would be here in an array, and we need to distinguish that
486 // case from the case where the "actual value" is an array.)
487 $value[self::TYPE_ANNOTATION] = [ $value[self::TYPE_ANNOTATION] ];
488 }
489 } elseif (
490 // @phan-suppress-next-line PhanUndeclaredClassReference 'array'
491 !self::classEquals( $className, $classHint )
492 ) {
493 // Include the type annotation if it doesn't match the hint
494 $value[self::TYPE_ANNOTATION] = $className;
495 }
496 }
497
498 /**
499 * Remove a mark from an encoded array, and return an
500 * encoded class name if present.
501 *
502 * The provided array may not trigger `::isArrayMarked` is there
503 * was a class hint provided.
504 *
505 * If the provided array had a "false mark" or recursively
506 * contained objects, the returned class name should be 'array'.
507 *
508 * @param array &$value An encoded array
509 * @param 'array'|class-string|null $classHint The class name provided as a hint to
510 * the decoder, which was previously provided as a hint to the encoder,
511 * or `null` if no hint was provided.
512 * @return 'array'|class-string The class name to be used for decoding, or
513 * 'array' if the value was a "complex" or "false mark" array.
514 */
515 protected function unmarkArray( array &$value, ?string $classHint ): string {
516 $className = $value[self::TYPE_ANNOTATION] ?? $classHint;
517 // Remove our marker and restore the previous state of the
518 // json array (restoring a pre-existing field if needed)
519 if ( is_array( $className ) ) {
520 $value[self::TYPE_ANNOTATION] = $className[0];
521 $className = $className[1] ?? $classHint;
522 } else {
523 unset( $value[self::TYPE_ANNOTATION] );
524 }
525 return $className;
526 }
527
528 /**
529 * Helper function to test two class strings for equality in the presence
530 * of class aliases.
531 *
532 * @param 'array'|class-string $class1
533 * @param 'array'|class-string|null $class2
534 * @return bool True if the arguments refer to the same class
535 */
536 private static function classEquals( string $class1, ?string $class2 ): bool {
537 if ( $class1 === $class2 ) {
538 // Fast path
539 return true;
540 }
541 if ( $class2 === null || $class1 === 'array' || $class2 === 'array' ) {
542 return false;
543 }
544 if ( is_a( $class1, $class2, true ) && is_a( $class2, $class1, true ) ) {
545 // Check aliases
546 return true;
547 }
548 return false;
549 }
550 }