aboutsummaryrefslogtreecommitdiffstats
path: root/includes/json/JsonCodec.php
diff options
context:
space:
mode:
authorPetr Pchelko <ppchelko@wikimedia.org>2020-11-17 17:26:53 -0700
committerPetr Pchelko <ppchelko@wikimedia.org>2020-11-19 08:32:21 -0700
commitdbdc2a3cd339991abaf918c3390614bb0221ece4 (patch)
treea594ae727b75b4348cf5dab6322c9bb4be7bf7de /includes/json/JsonCodec.php
parent6e5c7e97b4e9ffc320371fba684954f72c6dce04 (diff)
downloadmediawikicore-dbdc2a3cd339991abaf918c3390614bb0221ece4.tar.gz
mediawikicore-dbdc2a3cd339991abaf918c3390614bb0221ece4.zip
Introduce JsonCodec to help with serialization/deserialization
Change-Id: I5433090ae8e2b3f2a4590cc404baf838025546ce
Diffstat (limited to 'includes/json/JsonCodec.php')
-rw-r--r--includes/json/JsonCodec.php186
1 files changed, 186 insertions, 0 deletions
diff --git a/includes/json/JsonCodec.php b/includes/json/JsonCodec.php
new file mode 100644
index 000000000000..d9fe4a34a07c
--- /dev/null
+++ b/includes/json/JsonCodec.php
@@ -0,0 +1,186 @@
+<?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 FormatJson;
+use InvalidArgumentException;
+use JsonSerializable;
+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( 'object|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() ) {
+ // TODO: in PHP 7.3, we can use JsonException
+ throw new InvalidArgumentException( "Bad JSON: {$jsonStatus}" );
+ }
+ $json = $jsonStatus->getValue();
+ }
+
+ if ( is_object( $json ) ) {
+ $json = (array)$json;
+ }
+
+ if ( !$this->canMakeNewFromValue( $json ) ) {
+ if ( $expectedClass ) {
+ throw new InvalidArgumentException( 'JSON did not have ' . JsonConstants::TYPE_ANNOTATION );
+ }
+ return $json;
+ }
+
+ $class = $json[JsonConstants::TYPE_ANNOTATION];
+ if ( !class_exists( $class ) || !is_subclass_of( $class, JsonUnserializable::class ) ) {
+ throw new InvalidArgumentException( "Invalid target class {$class}" );
+ }
+
+ $obj = $class::newFromJsonArray( $this, $json );
+
+ // Check we haven't accidentally unserialized a godzilla if we were told we are not expecting it.
+ if ( $expectedClass && !$obj instanceof $expectedClass ) {
+ $actualClass = get_class( $obj );
+ throw new InvalidArgumentException( "Expected {$expectedClass}, got {$actualClass}" );
+ }
+ return $obj;
+ }
+
+ public function unserializeArray( array $array ) : array {
+ $unserializedExtensionData = [];
+ foreach ( $array as $key => $value ) {
+ if ( $this->canMakeNewFromValue( $value ) ) {
+ $unserializedExtensionData[$key] = $this->unserialize( $value );
+ } else {
+ $unserializedExtensionData[$key] = $value;
+ }
+ }
+ return $unserializedExtensionData;
+ }
+
+ public function serialize( $value ) {
+ if ( $value instanceof JsonSerializable ) {
+ $value = $value->jsonSerialize();
+ }
+ $json = FormatJson::encode( $value, false, FormatJson::ALL_OK );
+ if ( !$json ) {
+ // TODO: make it JsonException
+ throw new InvalidArgumentException(
+ 'Failed to encode JSON. Error ' . json_last_error_msg()
+ );
+ }
+
+ // Detect if the array contained any properties non-serializable
+ // to json. We will not be able to deserialize the value correctly
+ // anyway, so return null. This is done after calling FormatJson::encode
+ // to avoid walking over circular structures.
+ // TODO: make detectNonSerializableData not choke on cyclic structures.
+ $unserializablePath = $this->detectNonSerializableData( $value, true );
+ if ( $unserializablePath ) {
+ // TODO: Make it JsonException
+ throw new InvalidArgumentException(
+ "Non-unserializable property set at {$unserializablePath}"
+ );
+ }
+
+ 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 );
+ }
+
+ if ( is_object( $json ) ) {
+ return $json->$classAnnotation;
+ }
+ return false;
+ }
+
+ /**
+ * Recursive check for ability to serialize $value to JSON via FormatJson::encode().
+ *
+ * @param mixed $value
+ * @param bool $expectUnserialize
+ * @param string $accumulatedPath
+ * @return string|null JSON path to first encountered non-serializable property or null.
+ */
+ private function detectNonSerializableDataInternal(
+ $value,
+ bool $expectUnserialize,
+ string $accumulatedPath
+ ) : ?string {
+ if ( is_array( $value ) ||
+ ( is_object( $value ) && get_class( $value ) === 'stdClass' ) ) {
+ foreach ( $value as $key => $propValue ) {
+ $propValueNonSerializablePath = $this->detectNonSerializableDataInternal(
+ $propValue,
+ $expectUnserialize,
+ $accumulatedPath . '.' . $key
+ );
+ if ( $propValueNonSerializablePath ) {
+ return $propValueNonSerializablePath;
+ }
+ }
+ } elseif ( ( $expectUnserialize && $value instanceof JsonUnserializable )
+ // Trust that JsonSerializable will correctly serialize.
+ || ( !$expectUnserialize && $value instanceof JsonSerializable )
+ ) {
+ return null;
+ // Instances of classes other the \stdClass or JsonSerializable can not be serialized to JSON.
+ } elseif ( !is_scalar( $value ) && $value !== null ) {
+ return $accumulatedPath;
+ }
+ 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, '$' );
+ }
+}