Debian Codegraph @

tests/phpunit/mocks/json/ManagedObjectFactory.php

raw symbols SCIP
1 <?php
2 namespace MediaWiki\Tests\Json;
3
4 use Wikimedia\JsonCodec\JsonClassCodec;
5
6 /**
7 * Managed object factory which also handles serialization/deserialization
8 * of the objects it manages.
9 *
10 * @implements JsonClassCodec<ManagedObject>
11 */
12 class ManagedObjectFactory implements JsonClassCodec {
13 /** @var array<string,ManagedObject> Fake database */
14 private $storage = [];
15
16 /**
17 * Create and store an object with $name and $value in the database.
18 * @param string $name
19 * @param int $value
20 * @return ManagedObject
21 */
22 public function create( string $name, int $value ) {
23 if ( isset( $this->storage[$name] ) ) {
24 throw new \Error( "duplicate name" );
25 }
26 $this->storage[$name] = $o = new ManagedObject( $name, $value );
27 return $o;
28 }
29
30 /**
31 * Lookup $name in the database.
32 * @param string $name
33 * @return ManagedObject
34 */
35 public function lookup( string $name ): ManagedObject {
36 if ( !isset( $this->storage[$name] ) ) {
37 throw new \Error( "not found" );
38 }
39 return $this->storage[$name];
40 }
41
42 /** @inheritDoc */
43 public function toJsonArray( $obj ): array {
44 '@phan-var ManagedObject $obj';
45 // Not necessary to serialize all the properties, since they
46 // will be reloaded from the "database" during deserialization
47 return [ 'name' => $obj->name ];
48 }
49
50 /** @inheritDoc */
51 public function newFromJsonArray( string $className, array $json ): ManagedObject {
52 // @phan-suppress-next-line PhanTypeMismatchReturn template limitations
53 return $this->lookup( $json['name'] );
54 }
55
56 /** @inheritDoc */
57 public function jsonClassHintFor( string $className, string $key ): ?string {
58 // no hints
59 return null;
60 }
61 }