summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/Serializers/ExpDataSerializer.php
blob: 1f3a031d5e9158e4c84a5722dab895fe3d84b1e3 (plain)
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
55
56
57
58
59
60
61
62
63
64
65
<?php

namespace SMW\Serializers;

use OutOfBoundsException;
use Serializers\Serializer;
use SMW\Exporter\Element\ExpElement;
use SMWExpData as ExpData;

/**
 * @license GNU GPL v2+
 * @since 2.2
 *
 * @author mwjames
 */
class ExpDataSerializer implements Serializer {

	/**
	 * @see Serializer::serialize
	 *
	 * @since 2.2
	 */
	public function serialize( $expData ) {

		if ( !$expData instanceof ExpData ) {
			throw new OutOfBoundsException( 'Object is not supported' );
		}

		return $this->doSerialize( $expData ) + [ 'serializer' => __CLASS__, 'version' => 0.1 ];
	}

	private function doSerialize( $expData ) {

		$serialization = [
			'subject' => $expData->getSubject()->getSerialization()
		];

		$properties = [];

		foreach ( $expData->getProperties() as $property ) {
			$properties[$property->getUri()] = [
				'property' => $property->getSerialization(),
				'children' => $this->doSerializeChildren( $expData->getValues( $property ) )
			];
		}

		return $serialization + [ 'data' => $properties ];
	}

	private function doSerializeChildren( array $elements ) {

		$children = [];

		if ( $elements === [] ) {
			return $children;
		}

		foreach ( $elements as $element ) {
			$children[] = $element instanceof ExpElement ? $element->getSerialization() : $this->doSerialize( $element );
		}

		return $children;
	}

}