1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Wikibase\DataModel\Serializers; |
4
|
|
|
|
5
|
|
|
use Serializers\DispatchableSerializer; |
6
|
|
|
use Serializers\Exceptions\SerializationException; |
7
|
|
|
use Serializers\Exceptions\UnsupportedObjectException; |
8
|
|
|
use Serializers\Serializer; |
9
|
|
|
use Wikibase\DataModel\Statement\StatementList; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Package private |
13
|
|
|
* |
14
|
|
|
* @license GPL-2.0-or-later |
15
|
|
|
* @author Bene* < [email protected] > |
16
|
|
|
*/ |
17
|
|
|
class StatementListSerializer implements DispatchableSerializer { |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var Serializer |
21
|
|
|
*/ |
22
|
|
|
private $statementSerializer; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var bool |
26
|
|
|
*/ |
27
|
|
|
private $useObjectsForMaps; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param Serializer $statementSerializer |
31
|
|
|
* @param bool $useObjectsForMaps |
32
|
|
|
*/ |
33
|
26 |
|
public function __construct( Serializer $statementSerializer, $useObjectsForMaps ) { |
34
|
26 |
|
$this->statementSerializer = $statementSerializer; |
35
|
26 |
|
$this->useObjectsForMaps = $useObjectsForMaps; |
36
|
26 |
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @see Serializer::isSerializerFor |
40
|
|
|
* |
41
|
|
|
* @param mixed $object |
42
|
|
|
* |
43
|
|
|
* @return bool |
44
|
|
|
*/ |
45
|
25 |
|
public function isSerializerFor( $object ) { |
46
|
25 |
|
return $object instanceof StatementList; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @see Serializer::serialize |
51
|
|
|
* |
52
|
|
|
* @param StatementList $object |
53
|
|
|
* |
54
|
|
|
* @throws SerializationException |
55
|
|
|
* @return array[] |
56
|
|
|
*/ |
57
|
20 |
|
public function serialize( $object ) { |
58
|
20 |
|
if ( !$this->isSerializerFor( $object ) ) { |
59
|
3 |
|
throw new UnsupportedObjectException( |
60
|
3 |
|
$object, |
61
|
3 |
|
'StatementListSerializer can only serialize StatementList objects' |
62
|
|
|
); |
63
|
|
|
} |
64
|
|
|
|
65
|
17 |
|
return $this->getSerialized( $object ); |
66
|
|
|
} |
67
|
|
|
|
68
|
17 |
|
private function getSerialized( StatementList $statementList ) { |
69
|
17 |
|
$serialization = []; |
70
|
|
|
|
71
|
17 |
|
foreach ( $statementList->toArray() as $statement ) { |
72
|
5 |
|
$idSerialization = $statement->getPropertyId()->getSerialization(); |
73
|
|
|
|
74
|
5 |
|
if ( !array_key_exists( $idSerialization, $serialization ) ) { |
75
|
5 |
|
$serialization[$idSerialization] = []; |
76
|
|
|
} |
77
|
|
|
|
78
|
5 |
|
$serialization[$idSerialization][] = $this->statementSerializer->serialize( $statement ); |
79
|
|
|
} |
80
|
|
|
|
81
|
17 |
|
if ( $this->useObjectsForMaps ) { |
82
|
1 |
|
$serialization = (object)$serialization; |
83
|
|
|
} |
84
|
|
|
|
85
|
17 |
|
return $serialization; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
} |
89
|
|
|
|