|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace WikidataQueryApi\Query\Serializers; |
|
4
|
|
|
|
|
5
|
|
|
use Serializers\DispatchableSerializer; |
|
6
|
|
|
use Serializers\Exceptions\UnsupportedObjectException; |
|
7
|
|
|
use Serializers\Serializer; |
|
8
|
|
|
use WikidataQueryApi\Query\AbstractQuery; |
|
9
|
|
|
use WikidataQueryApi\Query\CollectionQuery; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* @licence GPLv2+ |
|
13
|
|
|
* @author Thomas Pellissier Tanon |
|
14
|
|
|
*/ |
|
15
|
|
|
class QuerySerializer implements DispatchableSerializer { |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var Serializer |
|
19
|
|
|
*/ |
|
20
|
|
|
private $commandsSerializer; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @param Serializer $commandsSerializer |
|
24
|
|
|
*/ |
|
25
|
9 |
|
public function __construct( Serializer $commandsSerializer ) { |
|
26
|
9 |
|
$this->commandsSerializer = $commandsSerializer; |
|
27
|
9 |
|
} |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* @see DispatchableSerializer::isSerializerFor |
|
31
|
|
|
*/ |
|
32
|
8 |
|
public function isSerializerFor( $object ) { |
|
33
|
8 |
|
return is_object( $object ) && $object instanceof AbstractQuery; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* @see Serializer::serialize |
|
38
|
|
|
*/ |
|
39
|
4 |
|
public function serialize( $object ) { |
|
40
|
4 |
|
if ( !$this->isSerializerFor( $object ) ) { |
|
41
|
2 |
|
throw new UnsupportedObjectException( |
|
42
|
2 |
|
$object, |
|
43
|
|
|
'QuerySerializer can only serialize AbstractQuery objects' |
|
44
|
2 |
|
); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
2 |
|
return $this->getSerialized( $object ); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
2 |
|
private function getSerialized( AbstractQuery $query ) { |
|
51
|
2 |
|
if ( $query instanceof CollectionQuery ) { |
|
52
|
1 |
|
return '(' . implode( ' ' . $query->getType() . ' ', $this->serializeQueries( $query->getSubQueries() ) ) . ')'; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
2 |
|
return $this->commandsSerializer->serialize( $query ); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
1 |
|
private function serializeQueries( array $queries ) { |
|
59
|
1 |
|
$serialized = []; |
|
60
|
|
|
|
|
61
|
1 |
|
foreach( $queries as $query ) { |
|
62
|
1 |
|
$serialized[] = $this->getSerialized( $query ); |
|
63
|
1 |
|
} |
|
64
|
|
|
|
|
65
|
1 |
|
return $serialized; |
|
66
|
|
|
} |
|
67
|
|
|
} |