| 1 |
[![Latest Stable Version]](https://packagist.org/packages/wikimedia/json-codec) [![License]](https://packagist.org/packages/wikimedia/json-codec) |
| 2 |
|
| 3 |
JsonCodec |
| 4 |
===================== |
| 5 |
|
| 6 |
Interfaces to serialize and deserialize PHP objects to/from JSON. |
| 7 |
|
| 8 |
Additional documentation about this library can be found on |
| 9 |
[mediawiki.org](https://www.mediawiki.org/wiki/JsonCodec). |
| 10 |
|
| 11 |
|
| 12 |
Usage |
| 13 |
----- |
| 14 |
|
| 15 |
To make an object serializable/deserializable to/from JSON, the |
| 16 |
simplest way is to use the `JsonCodecableTrait` and implement two |
| 17 |
methods in your class, `toJsonArray()` and the static method |
| 18 |
`newFromJsonArray()`: |
| 19 |
```php |
| 20 |
use Wikimedia\JsonCodec\JsonCodecable; |
| 21 |
|
| 22 |
class SampleObject implements JsonCodecable { |
| 23 |
use JsonCodecableTrait; |
| 24 |
|
| 25 |
/** @var string */ |
| 26 |
public string $property; |
| 27 |
|
| 28 |
// .... |
| 29 |
|
| 30 |
// Implement JsonCodecable using the JsonCodecableTrait |
| 31 |
|
| 32 |
/** @inheritDoc */ |
| 33 |
public function toJsonArray(): array { |
| 34 |
return [ |
| 35 |
'property' => $this->property, |
| 36 |
]; |
| 37 |
} |
| 38 |
|
| 39 |
/** @inheritDoc */ |
| 40 |
public static function newFromJsonArray( array $json ): SampleObject { |
| 41 |
return new SampleObject( $json['property'] ); |
| 42 |
} |
| 43 |
} |
| 44 |
``` |
| 45 |
A slightly more complicated version of this example can be found in |
| 46 |
[`tests/SampleObject.php`](./tests/SampleObject.php). |
| 47 |
|
| 48 |
If your class requires explicit management -- for example, object |
| 49 |
instances need to be created using a factory service, you can |
| 50 |
implement `JsonCodecable` directly: |
| 51 |
```php |
| 52 |
use Wikimedia\JsonCodec\JsonCodecable; |
| 53 |
|
| 54 |
class ManagedObject implements JsonCodecable { |
| 55 |
public static function jsonClassCodec( ContainerInterface $serviceContainer ) { |
| 56 |
$factory = $serviceContainer->get( 'MyObjectFactory' ); |
| 57 |
return new class( $factory ) implements JsonClassCodec { |
| 58 |
// ... |
| 59 |
public function toJsonArray( $obj ): array { |
| 60 |
// ... |
| 61 |
} |
| 62 |
public function newFromJsonArray( string $className, array $json ): ManagedObject { |
| 63 |
return $this->factory->create( $json[....] ); |
| 64 |
} |
| 65 |
}; |
| 66 |
} |
| 67 |
} |
| 68 |
``` |
| 69 |
A full example can be found in |
| 70 |
[`tests/ManagedObject.php`](./tests/ManagedObject.php). |
| 71 |
|
| 72 |
Note that array returned by `toJsonArray()` can include other |
| 73 |
`JsonCodecable` objects, which will be recursively serialized. |
| 74 |
When `newFromJsonArray` is called during deserialization, all |
| 75 |
of these recursively included objects will already have been |
| 76 |
deserialized back into objects. |
| 77 |
|
| 78 |
To serialize an object to JSON, use [`JsonCodec`](./src/JsonCodec.php): |
| 79 |
```php |
| 80 |
use Wikimedia\JsonCodec\JsonCodec; |
| 81 |
|
| 82 |
$services = ... your global services object, or null ...; |
| 83 |
$codec = new JsonCodec( $services ); |
| 84 |
|
| 85 |
$string_result = $codec->toJsonString( $someComplexValue ); |
| 86 |
$someComplexValue = $codec->newFromJsonString( $string_result ); |
| 87 |
``` |
| 88 |
|
| 89 |
In some cases you want to embed this output into another context, |
| 90 |
or to pretty-print the output using non-default `json_encode` options. |
| 91 |
In these cases it can be useful to have access to methods which |
| 92 |
return or accept the array form of the encoding, just before |
| 93 |
json encoding/decoding: |
| 94 |
```php |
| 95 |
$array_result = $codec->toJsonArray( $someComplexValue ); |
| 96 |
var_export($array_result); // pretty-print |
| 97 |
$request->jsonResponse( [ 'error': false, 'embedded': $array_result ] ); |
| 98 |
|
| 99 |
$someComplexValue = $codec->fromJsonArray( $data['embedded'] ); |
| 100 |
``` |
| 101 |
|
| 102 |
### Handling "non-codecable" objects |
| 103 |
|
| 104 |
In some cases you want to be able to serialize/deserialize third-party |
| 105 |
objects which don't implement JsonCodecable. This can be done using |
| 106 |
the JsonCodec method `::addCodecFor()` which allows the creator of |
| 107 |
the `JsonCodec` instance to specify a `JsonClassCodec` to use for |
| 108 |
an arbitrary class name. For example: |
| 109 |
```php |
| 110 |
use Wikimedia\JsonCodec\JsonCodec; |
| 111 |
|
| 112 |
$codec = new JsonCodec( ...optional services object... ); |
| 113 |
$codec->addCodecFor( \DocumentFragment::class, new MyDOMSerializer() ); |
| 114 |
|
| 115 |
$string_result = $codec->toJsonString( $someComplexValue ); |
| 116 |
``` |
| 117 |
This is done by default to provide a serializer for `stdClass` objects. |
| 118 |
|
| 119 |
If adding class codecs one-by-one is not sufficient, for example if |
| 120 |
you wish to add support for all objects implementing some |
| 121 |
alternate serialization interface, you can subclass `JsonCodec` and |
| 122 |
override the protected `JsonCodec::codecFor()` method to return |
| 123 |
an appropriate codec. Your code should look like this: |
| 124 |
```php |
| 125 |
class MyCustomJsonCodec extends JsonCodec { |
| 126 |
protected function codecFor( string $className ): ?JsonClassCodec { |
| 127 |
$codec = parent::codecFor( $className ); |
| 128 |
if ($codec === null && is_a($className, MyOwnSerializationType::class, true)) { |
| 129 |
$codec = new MyCustomSerializer(); |
| 130 |
// Cache this for future use |
| 131 |
$this->addCodecFor( $className, $codec ); |
| 132 |
} |
| 133 |
return $codec; |
| 134 |
} |
| 135 |
} |
| 136 |
``` |
| 137 |
A full example can be found in |
| 138 |
[`tests/AlternateCodec.php`](./tests/AlternateCodec.php). |
| 139 |
|
| 140 |
### More concise output |
| 141 |
|
| 142 |
By default JsonCodec embeds the class name of the appropriate object |
| 143 |
type into the JSON output to enable reliable deserialization. In some |
| 144 |
applications, however, concise JSON output is desired. By providing |
| 145 |
an optional "class hint" to the top-level call to `::toJsonArray()` and |
| 146 |
`newFromJsonArray()` and implementing the `::jsonClassHintFor()` |
| 147 |
method in your class codec you can suppress unnecessary type |
| 148 |
information in the JSON when your provided hint matches what would |
| 149 |
have been added. For example: |
| 150 |
|
| 151 |
``` |
| 152 |
class SampleContainerObject implements JsonCodecable { |
| 153 |
use JsonCodecableTrait; |
| 154 |
|
| 155 |
/** @var mixed */ |
| 156 |
public $contents; |
| 157 |
/** @var list<Foo> */ |
| 158 |
public array $foos; |
| 159 |
|
| 160 |
// ... |
| 161 |
|
| 162 |
// Implement JsonCodecable using the JsonCodecableTrait |
| 163 |
|
| 164 |
/** @inheritDoc */ |
| 165 |
public function toJsonArray(): array { |
| 166 |
return [ 'contents' => $this->contents, 'foos' => $this->foos ]; |
| 167 |
} |
| 168 |
|
| 169 |
/** @inheritDoc */ |
| 170 |
public static function newFromJsonArray( array $json ): SampleContainerObject { |
| 171 |
return new SampleContainerObject( $json['contents'], $json['foos'] ); |
| 172 |
} |
| 173 |
|
| 174 |
/** @inheritDoc */ |
| 175 |
public static function jsonClassHintFor( string $keyName ) { |
| 176 |
if ( $keyName === 'contents' ) { |
| 177 |
// Hint that the contained value is a SampleObject. It might be! |
| 178 |
return SampleObject::class; |
| 179 |
} elseif ( $keyName === 'foos' ) { |
| 180 |
// A hint with a modifier |
| 181 |
return Hint::build( Foo::class, Hint::LIST ); |
| 182 |
} |
| 183 |
return null; |
| 184 |
} |
| 185 |
} |
| 186 |
``` |
| 187 |
|
| 188 |
You can then generate concise output by providing the proper hints |
| 189 |
when serializing and deserializing: |
| 190 |
``` |
| 191 |
use Wikimedia\JsonCodec\JsonCodec; |
| 192 |
|
| 193 |
$codec = new JsonCodec(); |
| 194 |
|
| 195 |
$value = new SampleContainerObject( new SampleObject( 'sample' ), ... ); |
| 196 |
$string_result = $codec->toJsonString( $value, SampleContainerObject::class ); |
| 197 |
|
| 198 |
// $string_result is now: |
| 199 |
// {"contents":{"property":"sample"},"foos":[...]}' |
| 200 |
// with no explicit type information. |
| 201 |
|
| 202 |
// But we need to provide the same class hint when deserializing: |
| 203 |
$value = $codec->newFromJsonString( $string_result, SampleContainerObject::class ); |
| 204 |
``` |
| 205 |
|
| 206 |
Note that the provided value is a *hint*. If we were to put a value |
| 207 |
other than a `SampleObject` into the `SampleContainerObject` the type |
| 208 |
of that value would be embedded into the JSON output, but it would not |
| 209 |
break serialization/deserialization. |
| 210 |
|
| 211 |
As illustrated with the `foos` property, to indicate a homogenous list |
| 212 |
or array of the given type, you can pass `Hint::build(...., |
| 213 |
Hint::LIST)` as the class hint. A `stdClass` object where properties |
| 214 |
are values of the given type can be hinted with `Hint::build(...., |
| 215 |
Hint::STDCLASS)`. |
| 216 |
|
| 217 |
A full example can be found in |
| 218 |
[`tests/SampleContainerObject.php`](./tests/SampleContainerObject.php). |
| 219 |
|
| 220 |
The `Hint::USE_SQUARE` modifier allows `::toJsonArray()` to |
| 221 |
return a list (see |
| 222 |
[`array_is_list`](https://www.php.net/manual/en/function.array-is-list.php)) |
| 223 |
and have that list encoded as a JSON array, with square `[]` brackets. |
| 224 |
|
| 225 |
The `Hint::ALLOW_OBJECT` modifier ensures that empty objects are |
| 226 |
serialized as `{}`. It has the side effect that `::toJsonArray()` may |
| 227 |
in some cases return an _object_ value instead of the _array_ value |
| 228 |
implied from the method name. |
| 229 |
|
| 230 |
The `USE_SQUARE` and `ALLOW_OBJECT` hints are necessary because |
| 231 |
normally `JsonCodec` attempts to encode all _object values_ with curly `{}` |
| 232 |
brackets by inserting a `_type_` property in the encoded result when |
| 233 |
necessary to ensure that the encoded array is never a list. |
| 234 |
PHP's `json_encode` will use `{}` notation for non-list arrays. If you |
| 235 |
don't want the added `_type_` property added to your encoded result, |
| 236 |
then you need to specify whether you prefer `[]` notation (`USE_SQUARE`) |
| 237 |
or `{}` notation (`ALLOW_OBJECT`) to be used in ambiguous cases. |
| 238 |
|
| 239 |
An example with hint modifiers can be found in |
| 240 |
[`tests/SampleList.php`](./tests/SampleList.php) and its associated |
| 241 |
test cases. |
| 242 |
|
| 243 |
Where a superclass codec can be used to instantiate objects of |
| 244 |
various subclasses the `Hint::INHERITED` modifier can be used. |
| 245 |
An example of this can be found in |
| 246 |
[`tests/Pet.php`](./tests/Pet.php), |
| 247 |
[`tests/Dog.php`](./tests/Dog.php), and |
| 248 |
[`tests/Cat.php`](./tests/Cat.php) |
| 249 |
and their associated test cases in |
| 250 |
[`tests/JsonCodecTest.php`](./tests/JsonCodecTest.php). |
| 251 |
|
| 252 |
For forward-compatibility with JSON serialized with hints, you |
| 253 |
may specify `Hint::ONLY_FOR_DECODE` to indicate that serialization |
| 254 |
should ignore the hint (encoding full class information) but that |
| 255 |
deserialization should take the hint into account, so that it is |
| 256 |
possible to read encodings produced either with or without a |
| 257 |
future hint. |
| 258 |
|
| 259 |
In some cases, `::jsonClassHintFor()` may be inadequate to describe |
| 260 |
the implicit typing of the JSON; for example tagged union values or |
| 261 |
implicitly-typed objects nested deeply or inside non-homogeneous |
| 262 |
arrays. For those use cases a `JsonCodecInterface` parameter is |
| 263 |
provided to the `::jsonClassCodec()` method. This allows the |
| 264 |
serialization/deserialization code to manually encode/decode portions |
| 265 |
of its JSON array using an implicit type. More details can be found |
| 266 |
in the interface documentation for |
| 267 |
[`src/JsonCodecInterface.php`](./src/JsonCodecInterface.php) and a |
| 268 |
full example can be found in |
| 269 |
[`tests/TaggedValue.php`](./tests/TaggedValue.php). |
| 270 |
|
| 271 |
Further customization of the encoding of class names and class hints |
| 272 |
is available using the protected methods `JsonCodec::isArrayMarked()`, |
| 273 |
`JsonCodec::markArray()` and `JsonCodec::unmarkArray()`. A full |
| 274 |
example can be found in |
| 275 |
[`tests/ReservedKeyCodec.php`](./tests/ReservedKeyCodec.php). |
| 276 |
|
| 277 |
Running tests |
| 278 |
------------- |
| 279 |
|
| 280 |
``` |
| 281 |
composer install |
| 282 |
composer test |
| 283 |
``` |
| 284 |
|
| 285 |
History |
| 286 |
------- |
| 287 |
The JsonCodec concept was first introduced in MediaWiki 1.36.0 ([dbdc2a3cd33](https://gerrit.wikimedia.org/r/c/mediawiki/core/+/641575/)). It was |
| 288 |
split out of the MediaWiki codebase and published as an independent library |
| 289 |
during the MediaWiki 1.41 development cycle, with changes to the API. |
| 290 |
|
| 291 |
--- |
| 292 |
[Latest Stable Version]: https://poser.pugx.org/wikimedia/json-codec/v/stable.svg |
| 293 |
[License]: https://poser.pugx.org/wikimedia/json-codec/license.svg |