Test Failed
Pull Request — master (#148)
by
unknown
08:08
created

YearMonthTimeParser   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 143
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 24
lcom 1
cbo 6
dl 0
loc 143
ccs 38
cts 38
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 2
C stringParse() 0 56 14
A parseMonth() 0 9 3
A getTimeFromYearMonth() 0 7 3
A canBeMonth() 0 3 2
1
<?php
2
3
namespace ValueParsers;
4
5
use DataValues\TimeValue;
6
7
/**
8
 * A parser that accepts various date formats with month precision. Prefers month/year order when
9
 * both numbers are valid months, e.g. "12/10" is December 2010. Should be called before
10
 * YearTimeParser when you want to accept both formats, because strings like "1 999" may either
11
 * represent a month and a year or a year with digit grouping.
12
 *
13
 * @since 0.8.4
14
 *
15
 * @license GPL-2.0+
16
 * @author Addshore
17
 * @author Thiemo Kreuz
18
 */
19
class YearMonthTimeParser extends StringValueParser {
20
21
	const FORMAT_NAME = 'year-month';
22
23
	/**
24
	 * @var int[] Array mapping localized month names to month numbers (1 to 12).
25
	 */
26
	private $monthNumbers;
27
28
	/**
29
	 * @var ValueParser
30
	 */
31
	private $isoTimestampParser;
32
33
	/**
34
	 * @var EraParser
35
	 */
36
	private $eraParser;
37
38
	/**
39
	 * @see StringValueParser::__construct
40
	 *
41 70
	 * @param MonthNameProvider $monthNameProvider
42
	 * @param ParserOptions|null $options
43
	 * @param EraParser|null $eraParser
44
	 */
45 70
	public function __construct(
46
		MonthNameProvider $monthNameProvider,
47 70
		ParserOptions $options = null,
48 70
		EraParser $eraParser = null
49 70
	) {
50 70
		parent::__construct( $options );
51
52
		$languageCode = $this->getOption( ValueParser::OPT_LANG );
53
		$this->monthNumbers = $monthNameProvider->getMonthNumbers( $languageCode );
54
		$this->isoTimestampParser = new IsoTimestampParser( null, $this->options );
55
		$this->eraParser = $eraParser ?: new EraParser();
56
	}
57
58
	/**
59
	 * @see StringValueParser::stringParse
60 63
	 *
61
	 * @param string $value
62
	 *
63 63
	 * @throws ParseException
64 63
	 * @return TimeValue
65 11
	 */
66
	protected function stringParse( $value ) {
67 52
		$trimmedValue = trim( $value );
68
		switch ( $trimmedValue[0] ) {
69 52
			case '+':
70 52
			case '-':
71
				// don't let EraParser strip it, we will handle it ourselves
72 52
				$newValue = $trimmedValue;
73 30
				$eraWasSpecified = false;
74 21
				$sign = '';
75 9
				break;
76 9
			default:
77
				list( $sign, $newValue ) = $this->eraParser->parse( $trimmedValue );
78 22
				if ( $newValue !== $trimmedValue ) {
79 3
					$eraWasSpecified = true;
80
				} else {
81 3
					$eraWasSpecified = false;
82 3
					$sign = '';
83
				}
84 19
				break;
85 18
		}
86
87 18
		// Matches year and month separated by a separator.
88 16
		// \p{L} matches letters outside the ASCII range.
89
		$regex = '/^(-?[\d\p{L}]+)\s*?[\/\-\s.,]\s*(-?[\d\p{L}]+)$/u';
90
		if ( !preg_match( $regex, $newValue, $matches ) ) {
91
			throw new ParseException( 'Failed to parse year and month', $value, self::FORMAT_NAME );
92 8
		}
93
		list( , $a, $b ) = $matches;
94
95
		// if era was specified, fail on a minus sign
96
		$intRegex = $eraWasSpecified ? '/^\d+$/' : '/^-?\d+$/';
97
		$aIsInt = preg_match( $intRegex, $a );
98
		$bIsInt = preg_match( $intRegex, $b );
99
100 21
		if ( $aIsInt && $bIsInt ) {
101 21
			if ( $this->canBeMonth( $a ) ) {
102 21
				return $this->getTimeFromYearMonth( $sign . $b, $a );
103 19
			} elseif ( $this->canBeMonth( $b ) ) {
104
				return $this->getTimeFromYearMonth( $sign . $a, $b );
105
			}
106
		} elseif ( $aIsInt ) {
107 2
			$month = $this->parseMonth( $b );
108
109
			if ( $month ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $month of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
110
				return $this->getTimeFromYearMonth( $sign . $a, $month );
111
			}
112
		} elseif ( $bIsInt ) {
113
			$month = $this->parseMonth( $a );
114
115
			if ( $month ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $month of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
116 44
				return $this->getTimeFromYearMonth( $sign . $b, $month );
117 44
			}
118 40
		}
119
120
		throw new ParseException( 'Failed to parse year and month', $value, self::FORMAT_NAME );
121 44
	}
122
123
	/**
124
	 * @param string $month
125
	 *
126
	 * @return int|null
127
	 */
128
	private function parseMonth( $month ) {
129 30
		foreach ( $this->monthNumbers as $monthName => $i ) {
130 30
			if ( strcasecmp( $monthName, $month ) === 0 ) {
131
				return $i;
132
			}
133
		}
134
135
		return null;
136
	}
137
138
	/**
139
	 * @param string $year
140
	 * @param string $month as a canonical month number
141
	 *
142
	 * @return TimeValue
143
	 */
144
	private function getTimeFromYearMonth( $year, $month ) {
145
		if ( $year[0] !== '-' && $year[0] !== '+' ) {
146
			$year = '+' . $year;
147
		}
148
149
		return $this->isoTimestampParser->parse( sprintf( '%s-%02s-00T00:00:00Z', $year, $month ) );
150
	}
151
152
	/**
153
	 * @param string $value
154
	 *
155
	 * @return bool can the given value be a month?
156
	 */
157
	private function canBeMonth( $value ) {
158
		return $value >= 0 && $value <= 12;
159
	}
160
161
}
162