TimeFormatter::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace ValueFormatters;
4
5
use DataValues\TimeValue;
6
use InvalidArgumentException;
7
8
/**
9
 * Basic plain text formatter for TimeValue objects that either delegates formatting to an other
10
 * formatter given via OPT_TIME_ISO_FORMATTER or outputs the timestamp as it is.
11
 *
12
 * @since 0.1
13
 *
14
 * @license GPL-2.0-or-later
15
 * @author H. Snater < [email protected] >
16
 */
17
class TimeFormatter implements ValueFormatter {
18
19
	/**
20
	 * @deprecated since 0.7.1, use TimeValue::CALENDAR_GREGORIAN instead
21
	 */
22
	public const CALENDAR_GREGORIAN = TimeValue::CALENDAR_GREGORIAN;
23
24
	/**
25
	 * @deprecated since 0.7.1, use TimeValue::CALENDAR_JULIAN instead
26
	 */
27
	public const CALENDAR_JULIAN = TimeValue::CALENDAR_JULIAN;
28
29
	/**
30
	 * Option to localize calendar models. Must contain an array mapping known calendar model URIs
31
	 * to localized calendar model names.
32
	 */
33
	public const OPT_CALENDARNAMES = 'calendars';
34
35
	/**
36
	 * Option for a custom timestamp formatter. Must contain an instance of a ValueFormatter
37
	 * subclass, capable of formatting TimeValue objects. The output of the custom formatter is
38
	 * threaded as plain text and passed through.
39
	 */
40
	public const OPT_TIME_ISO_FORMATTER = 'time iso formatter';
41
42
	/**
43
	 * @var FormatterOptions
44
	 */
45
	private $options;
46
47 8
	/**
48 8
	 *
49
	 * @param FormatterOptions|null $options
50 8
	 */
51 8
	public function __construct( FormatterOptions $options = null ) {
52 8
		$this->options = $options ?: new FormatterOptions();
53
54
		$this->options->defaultOption( self::OPT_CALENDARNAMES, array() );
55
		$this->options->defaultOption( self::OPT_TIME_ISO_FORMATTER, null );
56
	}
57
58
	/**
59
	 * @see ValueFormatter::format
60
	 *
61
	 * @param TimeValue $value
62 8
	 *
63 8
	 * @throws InvalidArgumentException
64
	 * @return string Plain text
65
	 */
66
	public function format( $value ) {
67 8
		if ( !( $value instanceof TimeValue ) ) {
68
			throw new InvalidArgumentException( 'Data value type mismatch. Expected a TimeValue.' );
69 8
		}
70 8
71
		$formatted = $value->getTime();
72
73
		$isoFormatter = $this->options->getOption( self::OPT_TIME_ISO_FORMATTER );
74 8
		if ( $isoFormatter instanceof ValueFormatter ) {
75
			$formatted = $isoFormatter->format( $value );
76
		}
77
78
		return $formatted;
79
	}
80
81
}
82