Completed
Push — master ( 946fba...596b16 )
by Marius
11:53 queued 04:58
created

DecimalFormatter   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 92.31%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 4
dl 0
loc 54
ccs 12
cts 13
cp 0.9231
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
A format() 0 18 3
1
<?php
2
3
namespace ValueFormatters;
4
5
use DataValues\DecimalValue;
6
use InvalidArgumentException;
7
8
/**
9
 * Formatter for decimal values
10
 *
11
 * @since 0.1
12
 *
13
 * @license GPL-2.0+
14
 * @author Daniel Kinzler
15
 */
16
class DecimalFormatter extends ValueFormatterBase {
17
18
	/**
19
	 * Option key for forcing the sign to be included in the
20
	 * formatter's output even if it's "+". The value must
21
	 * be a boolean.
22
	 */
23
	const OPT_FORCE_SIGN = 'forceSign';
24
25
	/**
26
	 * @var NumberLocalizer
27
	 */
28
	private $localizer;
29
30
	/**
31
	 * @param FormatterOptions|null $options
32
	 * @param NumberLocalizer|null $localizer
33
	 */
34 7
	public function __construct( FormatterOptions $options = null, NumberLocalizer $localizer = null ) {
35 7
		parent::__construct( $options );
36
37 7
		$this->defaultOption( self::OPT_FORCE_SIGN, false );
38
39 7
		$this->localizer = $localizer ?: new BasicNumberLocalizer();
40 7
	}
41
42
	/**
43
	 * @see ValueFormatter::format
44
	 *
45
	 * @param DecimalValue $dataValue
46
	 *
47
	 * @throws InvalidArgumentException
48
	 * @return string Text
49
	 */
50 7
	public function format( $dataValue ) {
51 7
		if ( !( $dataValue instanceof DecimalValue ) ) {
52
			throw new InvalidArgumentException( 'Data value type mismatch. Expected a DecimalValue.' );
53
		}
54
55
		// TODO: Implement optional rounding/padding
56 7
		$decimal = $dataValue->getValue();
57
58 7
		if ( !$this->getOption( self::OPT_FORCE_SIGN ) ) {
59
			// strip leading +
60 6
			$decimal = ltrim( $decimal, '+' );
61
		}
62
63
		// apply number localization
64 7
		$decimal = $this->localizer->localizeNumber( $decimal );
65
66 7
		return $decimal;
67
	}
68
69
}
70