Passed
Push — master ( 935a55...baa252 )
by Daimona
01:37
created

Message::getTimeWithArticle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php declare( strict_types=1 );
2
3
namespace BotRiconferme;
4
5
/**
6
 *
7
 */
8
class Message {
9
	public const MONTHS = [
10
		'January' => 'gennaio',
11
		'February' => 'febbraio',
12
		'March' => 'marzo',
13
		'April' => 'aprile',
14
		'May' => 'maggio',
15
		'June' => 'giugno',
16
		'July' => 'luglio',
17
		'August' => 'agosto',
18
		'September' => 'settembre',
19
		'October' => 'ottobre',
20
		'November' => 'novembre',
21
		'December' => 'dicembre'
22
	];
23
	/** @var string */
24
	private $value;
25
26
	/**
27
	 * @param string $key
28
	 */
29
	public function __construct( string $key ) {
30
		$this->value = Config::getInstance()->getWikiMessage( $key );
31
	}
32
33
	/**
34
	 * @param array $args
35
	 * @return self
36
	 */
37
	public function params( array $args ) : self {
38
		$this->value = strtr( $this->value, $args );
39
		return $this;
40
	}
41
42
	/**
43
	 * @return string
44
	 */
45
	public function text() : string {
46
		$this->parsePlurals();
47
		return $this->value;
48
	}
49
50
	/**
51
	 * Replace {{$plur|<amount>|sing|plur}}
52
	 */
53
	protected function parsePlurals() {
54
		$reg = '!\{\{\$plur\|(?P<amount>\d+)\|(?P<sing>[^}|]+)\|(?P<plur>[^|}]+)}}!';
55
56
		if ( preg_match( $reg, $this->value ) === 0 ) {
57
			return;
58
		}
59
		$this->value = preg_replace_callback(
60
			$reg,
61
			function ( $matches ) {
62
				return intval( $matches['amount'] ) > 1 ? trim( $matches['plur'] ) : trim( $matches['sing'] );
63
			},
64
			$this->value
65
		);
66
	}
67
68
	/**
69
	 * Get a timestamp from a localized time string
70
	 *
71
	 * @param string $timeString Full format, e.g. "15 aprile 2019 18:27"
72
	 * @return int
73
	 */
74
	public static function getTimestampFromLocalTime( string $timeString ) : int {
75
		$englishTime = str_ireplace(
76
			array_values( self::MONTHS ),
77
			array_keys( self::MONTHS ),
78
			$timeString
79
		);
80
81
		return strtotime( $englishTime );
82
	}
83
84
	/**
85
	 * Given an array of data, returns a list of its elements using commas, and " e " before
86
	 * the last one. $emptyText can be used to specify the text in case $data is empty.
87
	 *
88
	 * @param array $data
89
	 * @param string $emptyText
90
	 * @return string
91
	 */
92
	public static function commaList( array $data, string $emptyText = 'nessuno' ) : string {
93
		if ( count( $data ) > 1 ) {
94
			$last = array_pop( $data );
95
			$ret = implode( ', ', $data ) . " e $last";
96
		} elseif ( $data ) {
97
			$ret = (string)$data[0];
98
		} else {
99
			$ret = $emptyText;
100
		}
101
102
		return $ret;
103
	}
104
105
	public function __toString() {
106
		return $this->text();
107
	}
108
}
109