| 1 |
<?php |
| 2 |
namespace MediaWiki\Tests\Json; |
| 3 |
|
| 4 |
use stdClass; |
| 5 |
use Wikimedia\Assert\Assert; |
| 6 |
use Wikimedia\JsonCodec\JsonCodecable; |
| 7 |
use Wikimedia\JsonCodec\JsonCodecableTrait; |
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
class SampleContainerObject implements JsonCodecable { |
| 14 |
use JsonCodecableTrait; |
| 15 |
|
| 16 |
|
| 17 |
public $contents; |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
public function __construct( $contents ) { |
| 24 |
$this->contents = $contents; |
| 25 |
} |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
public function toJsonArray(): array { |
| 31 |
return [ |
| 32 |
'contents' => $this->contents, |
| 33 |
|
| 34 |
'test' => (object)[], |
| 35 |
|
| 36 |
'array' => [ $this->contents ], |
| 37 |
]; |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
public static function newFromJsonArray( array $json ): SampleContainerObject { |
| 42 |
Assert::invariant( |
| 43 |
get_class( $json['test'] ) === stdClass::class && |
| 44 |
count( get_object_vars( $json['test'] ) ) === 0, |
| 45 |
"Ensure that the 'test' key is restored correctly" |
| 46 |
); |
| 47 |
Assert::invariant( |
| 48 |
is_array( $json['array'] ) && count( $json['array'] ) === 1, |
| 49 |
"Ensure that the 'array' key is restored correctly" |
| 50 |
); |
| 51 |
return new SampleContainerObject( $json['contents'] ); |
| 52 |
} |
| 53 |
|
| 54 |
|
| 55 |
public static function jsonClassHintFor( string $keyName ): ?string { |
| 56 |
if ( $keyName === 'contents' ) { |
| 57 |
|
| 58 |
return SampleObject::class; |
| 59 |
} elseif ( $keyName === 'array' ) { |
| 60 |
|
| 61 |
|
| 62 |
return SampleObject::class . '[]'; |
| 63 |
} elseif ( $keyName === 'test' ) { |
| 64 |
|
| 65 |
|
| 66 |
return stdClass::class; |
| 67 |
} |
| 68 |
return null; |
| 69 |
} |
| 70 |
} |