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

YearMonthTimeParser::parseMonth()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 2
cts 2
cp 1
rs 9.9666
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3
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
				break;
75 9
			default:
76 9
				list( $sign, $newValue ) = $this->eraParser->parse( $trimmedValue );
77
				if ( $newValue !== $trimmedValue ) {
78 22
					$eraWasSpecified = true;
79 3
				} else {
80
					$eraWasSpecified = false;
81 3
					$sign = '';
82 3
				}
83
				break;
84 19
		}
85 18
86
		// Matches year and month separated by a separator.
87 18
		// \p{L} matches letters outside the ASCII range.
88 16
		$regex = '/^(-?[\d\p{L}]+)\s*?[\/\-\s.,]\s*(-?[\d\p{L}]+)$/u';
89
		if ( !preg_match( $regex, $newValue, $matches ) ) {
90
			throw new ParseException( 'Failed to parse year and month', $value, self::FORMAT_NAME );
91
		}
92 8
		list( , $a, $b ) = $matches;
93
94
		// if era was specified, fail on a minus sign
95
		$intRegex = $eraWasSpecified ? '/^\d+$/' : '/^-?\d+$/';
96
		$aIsInt = preg_match( $intRegex, $a );
97
		$bIsInt = preg_match( $intRegex, $b );
98
99
		if ( $aIsInt && $bIsInt ) {
100 21
			if ( $this->canBeMonth( $a ) ) {
101 21
				return $this->getTimeFromYearMonth( $sign . $b, $a );
0 ignored issues
show
Bug introduced by
The variable $sign does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
102 21
			} elseif ( $this->canBeMonth( $b ) ) {
103 19
				return $this->getTimeFromYearMonth( $sign . $a, $b );
104
			}
105
		} elseif ( $aIsInt ) {
106
			$month = $this->parseMonth( $b );
107 2
108
			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...
109
				return $this->getTimeFromYearMonth( $sign . $a, $month );
110
			}
111
		} elseif ( $bIsInt ) {
112
			$month = $this->parseMonth( $a );
113
114
			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...
115
				return $this->getTimeFromYearMonth( $sign . $b, $month );
116 44
			}
117 44
		}
118 40
119
		throw new ParseException( 'Failed to parse year and month', $value, self::FORMAT_NAME );
120
	}
121 44
122
	/**
123
	 * @param string $month
124
	 *
125
	 * @return int|null
126
	 */
127
	private function parseMonth( $month ) {
128
		foreach ( $this->monthNumbers as $monthName => $i ) {
129 30
			if ( strcasecmp( $monthName, $month ) === 0 ) {
130 30
				return $i;
131
			}
132
		}
133
134
		return null;
135
	}
136
137
	/**
138
	 * @param string $year
139
	 * @param string $month as a canonical month number
140
	 *
141
	 * @return TimeValue
142
	 */
143
	private function getTimeFromYearMonth( $year, $month ) {
144
		if ( $year[0] !== '-' && $year[0] !== '+' ) {
145
			$year = '+' . $year;
146
		}
147
148
		return $this->isoTimestampParser->parse( sprintf( '%s-%02s-00T00:00:00Z', $year, $month ) );
149
	}
150
151
	/**
152
	 * @param string $value
153
	 *
154
	 * @return bool can the given value be a month?
155
	 */
156
	private function canBeMonth( $value ) {
157
		return $value >= 0 && $value <= 12;
158
	}
159
160
}
161