Completed
Push — master ( 7776a4...8c5813 )
by mw
35:00
created

DispatchingDataValueFormatter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 63
rs 10
c 1
b 0
f 1

3 Methods

Rating   Name   Duplication   Size   Complexity  
A addDataValueFormatter() 0 3 1
A addDefaultDataValueFormatter() 0 3 1
B getDataValueFormatterFor() 0 18 5
1
<?php
2
3
namespace SMW\DataValues\ValueFormatters;
4
5
use SMWDataValue as DataValue;
6
use RuntimeException;
7
8
/**
9
 * @private
10
 *
11
 * @license GNU GPL v2+
12
 * @since 2.4
13
 *
14
 * @author mwjames
15
 */
16
class DispatchingDataValueFormatter {
17
18
	/**
19
	 * @var DataValueFormatter[]
20
	 */
21
	private $dataValueFormatters = array();
22
23
	/**
24
	 * @var DataValueFormatter
25
	 */
26
	private $defaultDataValueFormatters = array();
27
28
	/**
29
	 * @since  2.4
30
	 *
31
	 * @param DataValueFormatter $dataValueFormatter
32
	 */
33
	public function addDataValueFormatter( DataValueFormatter $dataValueFormatter ) {
34
		$this->dataValueFormatters[] = $dataValueFormatter;
35
	}
36
37
	/**
38
	 * DataValueFormatters registered with this method are validated after
39
	 * DispatchingDataValueFormatter::getDataValueFormatterFor was not able to
40
	 * match any Formatter. This to ensure that a distinct FooStringValueFormatter
41
	 * is tried before the default StringValueFormatter.
42
	 *
43
	 * @since 2.4
44
	 *
45
	 * @param DataValueFormatter $dataValueFormatter
46
	 */
47
	public function addDefaultDataValueFormatter( DataValueFormatter $dataValueFormatter ) {
48
		$this->defaultDataValueFormatters[] = $dataValueFormatter;
49
	}
50
51
	/**
52
	 * @since 2.4
53
	 *
54
	 * @param DataValue $dataValue
55
	 *
56
	 * @return DataValueFormatter
57
	 * @throws RuntimeException
58
	 */
59
	public function getDataValueFormatterFor( DataValue $dataValue ) {
60
61
		foreach ( $this->dataValueFormatters as $dataValueFormatter ) {
62
			if ( $dataValueFormatter->isFormatterFor( $dataValue ) ) {
63
				$dataValueFormatter->setDataValue( $dataValue );
64
				return $dataValueFormatter;
65
			}
66
		}
67
68
		foreach ( $this->defaultDataValueFormatters as $dataValueFormatter ) {
0 ignored issues
show
Bug introduced by
The expression $this->defaultDataValueFormatters of type object<SMW\DataValues\Va...ers\DataValueFormatter> is not traversable.
Loading history...
69
			if ( $dataValueFormatter->isFormatterFor( $dataValue ) ) {
70
				$dataValueFormatter->setDataValue( $dataValue );
71
				return $dataValueFormatter;
72
			}
73
		}
74
75
		throw new RuntimeException( "The dispatcher could not match a DataValueFormatter for " . get_class( $dataValue ) );
76
	}
77
78
}
79