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-or-later |
14
|
|
|
* @author Daniel Kinzler |
15
|
|
|
*/ |
16
|
|
|
class DecimalFormatter implements ValueFormatter { |
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
|
|
|
public const OPT_FORCE_SIGN = 'forceSign'; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var FormatterOptions |
27
|
|
|
*/ |
28
|
|
|
private $options; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @var NumberLocalizer |
32
|
|
|
*/ |
33
|
|
|
private $localizer; |
34
|
7 |
|
|
35
|
7 |
|
/** |
36
|
|
|
* @param FormatterOptions|null $options |
37
|
7 |
|
* @param NumberLocalizer|null $localizer |
38
|
|
|
*/ |
39
|
7 |
|
public function __construct( FormatterOptions $options = null, NumberLocalizer $localizer = null ) { |
40
|
7 |
|
$this->options = $options ?: new FormatterOptions(); |
41
|
|
|
|
42
|
|
|
$this->options->defaultOption( ValueFormatter::OPT_LANG, 'en' ); |
43
|
|
|
$this->options->defaultOption( self::OPT_FORCE_SIGN, false ); |
44
|
|
|
|
45
|
|
|
$this->localizer = $localizer ?: new BasicNumberLocalizer(); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @see ValueFormatter::format |
50
|
7 |
|
* |
51
|
7 |
|
* @param DecimalValue $dataValue |
52
|
|
|
* |
53
|
|
|
* @throws InvalidArgumentException |
54
|
|
|
* @return string Text |
55
|
|
|
*/ |
56
|
7 |
|
public function format( $dataValue ) { |
57
|
|
|
if ( !( $dataValue instanceof DecimalValue ) ) { |
58
|
7 |
|
throw new InvalidArgumentException( 'Data value type mismatch. Expected a DecimalValue.' ); |
59
|
|
|
} |
60
|
6 |
|
|
61
|
|
|
// TODO: Implement optional rounding/padding |
62
|
|
|
$decimal = $dataValue->getValue(); |
63
|
|
|
|
64
|
7 |
|
if ( !$this->options->getOption( self::OPT_FORCE_SIGN ) ) { |
65
|
|
|
// strip leading + |
66
|
7 |
|
$decimal = ltrim( $decimal, '+' ); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
// apply number localization |
70
|
|
|
$decimal = $this->localizer->localizeNumber( $decimal ); |
71
|
|
|
|
72
|
|
|
return $decimal; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
} |
76
|
|
|
|