1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ValueParsers; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Base class to unlocalize a month name in a date string. |
7
|
|
|
* |
8
|
|
|
* @since 0.7 |
9
|
|
|
* |
10
|
|
|
* @license GPL-2.0+ |
11
|
|
|
* @author Addshore |
12
|
|
|
* @author Thiemo Kreuz |
13
|
|
|
*/ |
14
|
|
|
class MonthNameUnlocalizer { |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var string[] Array mapping localized to canonical (English) month names. |
18
|
|
|
*/ |
19
|
|
|
private $replacements = array(); |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param string[] $replacements Array mapping localized month names (possibly including full |
23
|
|
|
* month names, genitive names and abbreviations) to canonical (English) month names. |
24
|
|
|
*/ |
25
|
11 |
|
public function __construct( array $replacements ) { |
26
|
11 |
|
$this->replacements = $replacements; |
27
|
|
|
|
28
|
|
|
// Order search strings from longest to shortest |
29
|
11 |
|
uksort( $this->replacements, function( $a, $b ) { |
30
|
2 |
|
return strlen( $b ) - strlen( $a ); |
31
|
11 |
|
} ); |
32
|
11 |
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Unlocalizes the longest month name in a date string that could be found first. |
36
|
|
|
* Tries to avoid doing multiple replacements and returns the localized original if in doubt. |
37
|
|
|
* |
38
|
|
|
* @see NumberUnlocalizer::unlocalizeNumber |
39
|
|
|
* |
40
|
|
|
* @param string $date Localized date string. |
41
|
|
|
* |
42
|
|
|
* @return string Unlocalized date string. |
43
|
|
|
*/ |
44
|
11 |
|
public function unlocalize( $date ) { |
45
|
11 |
|
foreach ( $this->replacements as $search => $replace ) { |
46
|
9 |
|
if ( !is_string( $search ) ) { |
47
|
1 |
|
continue; |
48
|
|
|
} |
49
|
|
|
|
50
|
8 |
|
$unlocalized = str_replace( $search, $replace, $date, $count ); |
51
|
|
|
|
52
|
|
|
// Nothing happened, try the next. |
53
|
8 |
|
if ( $count <= 0 ) { |
54
|
1 |
|
continue; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
// Do not mess with strings that are clearly not a valid date. |
58
|
7 |
|
if ( $count > 1 ) { |
59
|
1 |
|
break; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
// Do not mess with already unlocalized month names, e.g. "July" should not become |
63
|
|
|
// "Julyy" when replacing "Jul" with "July". But shortening "Julyus" to "July" is ok. |
64
|
6 |
|
if ( strpos( $date, $replace ) !== false && strlen( $replace ) >= strlen( $search ) ) { |
65
|
1 |
|
break; |
66
|
|
|
} |
67
|
|
|
|
68
|
5 |
|
return $unlocalized; |
69
|
|
|
} |
70
|
|
|
|
71
|
6 |
|
return $date; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
} |
75
|
|
|
|