summaryrefslogtreecommitdiff
blob: 2db96ca1b59ec40ab4515f88faa76641dd52ba3e (plain)
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
<?php
declare( strict_types = 1 );

namespace MediaWiki\Extension\Translate\Utilities\Json;

use FormatJson;

/**
 * Can be used by classes that want to serialize / deserialize
 * Remove once we need to support only MW >= 1.36
 * See Change-Id: I5433090ae8e2b3f2a4590cc404baf838025546ce
 *
 * @license GPL-2.0-or-later
 * @since 2020.12
 */
trait JsonUnserializableTrait {
	public function jsonSerialize() {
		return $this->annotateJsonForDeserialization(
			$this->toJsonArray()
		);
	}

	/** Annotate the $json array with class metadata. */
	private function annotateJsonForDeserialization( array $json ): string {
		$json[JsonCodec::TYPE_ANNOTATION] = get_class( $this );
		return FormatJson::encode( $json, false, FormatJson::ALL_OK );
	}

	/**
	 * Prepare this object for JSON serialization.
	 * The returned array will be passed to self::newFromJsonArray
	 * upon JSON deserialization.
	 */
	abstract protected function toJsonArray(): array;
}

class_alias( JsonUnserializableTrait::class, '\MediaWiki\Extensions\Translate\JsonUnserializableTrait' );