Localisation updates from https://translatewiki.net.
[mediawiki.git] / tests / phpunit / mocks / json / SampleContainerObject.php
blobdc39b2371fffd60293495744ff8aa0dc94b30639
1 <?php
2 namespace MediaWiki\Tests\Json;
4 use stdClass;
5 use Wikimedia\Assert\Assert;
6 use Wikimedia\JsonCodec\JsonCodecable;
7 use Wikimedia\JsonCodec\JsonCodecableTrait;
9 /**
10 * Sample container object which uses JsonCodecableTrait to directly implement
11 * serialization/deserialization and uses class hints.
13 class SampleContainerObject implements JsonCodecable {
14 use JsonCodecableTrait;
16 /** @var mixed */
17 public $contents;
19 /**
20 * Create a new SampleContainerObject which stores $contents
21 * @param mixed $contents
23 public function __construct( $contents ) {
24 $this->contents = $contents;
27 // Implement JsonCodecable using the JsonCodecableTrait
29 /** @inheritDoc */
30 public function toJsonArray(): array {
31 return [
32 'contents' => $this->contents,
33 // Note that json array keys need not correspond to property names
34 'test' => (object)[],
35 // Test "array of" hints as well as regular hints
36 'array' => [ $this->contents ],
40 /** @inheritDoc */
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"
47 Assert::invariant(
48 is_array( $json['array'] ) && count( $json['array'] ) === 1,
49 "Ensure that the 'array' key is restored correctly"
51 return new SampleContainerObject( $json['contents'] );
54 /** @inheritDoc */
55 public static function jsonClassHintFor( string $keyName ): ?string {
56 if ( $keyName === 'contents' ) {
57 // Hint that the contained value is a SampleObject. It might be!
58 return SampleObject::class;
59 } elseif ( $keyName === 'array' ) {
60 // Hint that the contained value is a *array of* SampleObject.
61 // It might be!
62 return SampleObject::class . '[]';
63 } elseif ( $keyName === 'test' ) {
64 // This hint will always be correct; note that this is a key
65 // name not a property of SampleContainerObject
66 return stdClass::class;
68 return null;