1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Wikibase\DataModel\Serializers; |
4
|
|
|
|
5
|
|
|
use Serializers\Exceptions\SerializationException; |
6
|
|
|
use Serializers\Exceptions\UnsupportedObjectException; |
7
|
|
|
use Serializers\Serializer; |
8
|
|
|
use Wikibase\DataModel\Term\TermList; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Package private |
12
|
|
|
* |
13
|
|
|
* @license GPL-2.0-or-later |
14
|
|
|
* @author Addshore |
15
|
|
|
*/ |
16
|
|
|
class TermListSerializer implements Serializer { |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var Serializer |
20
|
|
|
*/ |
21
|
|
|
private $termSerializer; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var bool |
25
|
|
|
*/ |
26
|
|
|
private $useObjectsForMaps; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param Serializer $termSerializer |
30
|
|
|
* @param bool $useObjectsForMaps |
31
|
|
|
*/ |
32
|
16 |
|
public function __construct( Serializer $termSerializer, $useObjectsForMaps ) { |
33
|
16 |
|
$this->termSerializer = $termSerializer; |
34
|
16 |
|
$this->useObjectsForMaps = $useObjectsForMaps; |
35
|
16 |
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @see Serializer::serialize |
39
|
|
|
* |
40
|
|
|
* @param TermList $object |
41
|
|
|
* |
42
|
|
|
* @return array[] |
43
|
|
|
* @throws SerializationException |
44
|
|
|
*/ |
45
|
16 |
|
public function serialize( $object ) { |
46
|
16 |
|
$this->assertIsSerializerFor( $object ); |
47
|
15 |
|
return $this->getSerialized( $object ); |
48
|
|
|
} |
49
|
|
|
|
50
|
16 |
|
private function assertIsSerializerFor( $object ) { |
51
|
16 |
|
if ( !( $object instanceof TermList ) ) { |
52
|
1 |
|
throw new UnsupportedObjectException( |
53
|
1 |
|
$object, |
54
|
1 |
|
'TermListSerializer can only serialize TermList objects' |
55
|
|
|
); |
56
|
|
|
} |
57
|
15 |
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @param TermList $termList |
61
|
|
|
* |
62
|
|
|
* @return array[] |
63
|
|
|
*/ |
64
|
15 |
|
private function getSerialized( TermList $termList ) { |
65
|
15 |
|
$serialization = []; |
66
|
|
|
|
67
|
15 |
|
foreach ( $termList->getIterator() as $term ) { |
68
|
5 |
|
$serialization[$term->getLanguageCode()] = $this->termSerializer->serialize( $term ); |
69
|
|
|
} |
70
|
|
|
|
71
|
15 |
|
if ( $this->useObjectsForMaps ) { |
72
|
2 |
|
$serialization = (object)$serialization; |
73
|
|
|
} |
74
|
|
|
|
75
|
15 |
|
return $serialization; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
} |
79
|
|
|
|