2 namespace MediaWiki\Tests\Json
;
4 use Wikimedia\Assert\Assert
;
5 use Wikimedia\JsonCodec\JsonCodecable
;
6 use Wikimedia\JsonCodec\JsonCodecableTrait
;
9 * Sample object which uses JsonCodecableTrait to directly implement
10 * serialization/deserialization.
12 class SampleObject
implements JsonCodecable
{
13 use JsonCodecableTrait
;
16 public string $property;
19 * Create a new SampleObject which stores $property.
20 * @param string $property
22 public function __construct( string $property ) {
23 $this->property
= $property;
26 // Implement JsonCodecable using the JsonCodecableTrait
29 public function toJsonArray(): array {
30 if ( $this->property
!== 'use _type_' ) {
31 // Allow testing both with and without the '_type_' special case
32 return [ 'property' => $this->property
];
35 'property' => $this->property
,
36 // Implementers shouldn't have to know which properties the
37 // codec is using for its own purposes; this will still work
39 '_type_' => 'check123',
44 public static function newFromJsonArray( array $json ): SampleObject
{
45 if ( $json['property'] === 'use _type_' ) {
46 Assert
::invariant( $json['_type_'] === 'check123', 'protected field' );
48 return new SampleObject( $json['property'] );
52 // This class_alias exists for testing alias support in JsonCodec and
53 // should not be removed.
54 class_alias( SampleObject
::class, 'MediaWiki\\Tests\\Json\\SampleObjectAlias' );