aboutsummaryrefslogtreecommitdiffstats
path: root/tests/phpunit/mocks/json/SampleObject.php
blob: 9b1faaea7c2f23927a86357c259c3530fb1017a8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
namespace MediaWiki\Tests\Json;

use Wikimedia\Assert\Assert;
use Wikimedia\JsonCodec\JsonCodecable;
use Wikimedia\JsonCodec\JsonCodecableTrait;

/**
 * Sample object which uses JsonCodecableTrait to directly implement
 * serialization/deserialization.
 */
class SampleObject implements JsonCodecable {
	use JsonCodecableTrait;

	/** @var string */
	public string $property;

	/**
	 * Create a new SampleObject which stores $property.
	 * @param string $property
	 */
	public function __construct( string $property ) {
		$this->property = $property;
	}

	// Implement JsonCodecable using the JsonCodecableTrait

	/** @inheritDoc */
	public function toJsonArray(): array {
		if ( $this->property !== 'use _type_' ) {
			// Allow testing both with and without the '_type_' special case
			return [ 'property' => $this->property ];
		}
		return [
			'property' => $this->property,
			// Implementers shouldn't have to know which properties the
			// codec is using for its own purposes; this will still work
			// fine:
			'_type_' => 'check123',
		];
	}

	/** @inheritDoc */
	public static function newFromJsonArray( array $json ): SampleObject {
		if ( $json['property'] === 'use _type_' ) {
			Assert::invariant( $json['_type_'] === 'check123', 'protected field' );
		}
		return new SampleObject( $json['property'] );
	}
}

// This class_alias exists for testing alias support in JsonCodec and
// should not be removed.
class_alias( SampleObject::class, 'MediaWiki\\Tests\\Json\\SampleObjectAlias' );