summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/DataValues/ValueFormatters/DispatchingDataValueFormatter.php
blob: c8056a987863d62b5b1400c0e7c686bdf4e351a0 (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
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php

namespace SMW\DataValues\ValueFormatters;

use RuntimeException;
use SMWDataValue as DataValue;

/**
 * @private
 *
 * @license GNU GPL v2+
 * @since 2.4
 *
 * @author mwjames
 */
class DispatchingDataValueFormatter {

	/**
	 * @var DataValueFormatter[]
	 */
	private $dataValueFormatters = [];

	/**
	 * @var DataValueFormatter[]
	 */
	private $defaultDataValueFormatters = [];

	/**
	 * @since  2.4
	 *
	 * @param DataValueFormatter $dataValueFormatter
	 */
	public function addDataValueFormatter( DataValueFormatter $dataValueFormatter ) {
		$this->dataValueFormatters[] = $dataValueFormatter;
	}

	/**
	 * DataValueFormatters registered with this method are validated after
	 * DispatchingDataValueFormatter::getDataValueFormatterFor was not able to
	 * match any Formatter. This to ensure that a distinct FooStringValueFormatter
	 * is tried before the default StringValueFormatter.
	 *
	 * @since 2.4
	 *
	 * @param DataValueFormatter $dataValueFormatter
	 */
	public function addDefaultDataValueFormatter( DataValueFormatter $dataValueFormatter ) {
		$this->defaultDataValueFormatters[] = $dataValueFormatter;
	}

	/**
	 * @since 2.4
	 *
	 * @param DataValue $dataValue
	 *
	 * @return DataValueFormatter
	 * @throws RuntimeException
	 */
	public function getDataValueFormatterFor( DataValue $dataValue ) {

		foreach ( $this->dataValueFormatters as $dataValueFormatter ) {
			if ( $dataValueFormatter->isFormatterFor( $dataValue ) ) {
				$dataValueFormatter->setDataValue( $dataValue );
				return $dataValueFormatter;
			}
		}

		foreach ( $this->defaultDataValueFormatters as $dataValueFormatter ) {
			if ( $dataValueFormatter->isFormatterFor( $dataValue ) ) {
				$dataValueFormatter->setDataValue( $dataValue );
				return $dataValueFormatter;
			}
		}

		throw new RuntimeException( "The dispatcher could not match a DataValueFormatter for " . get_class( $dataValue ) );
	}

}