Passed
Push — master ( 853cce...2ef02f )
by Daimona
01:54
created

Message::parsePlurals()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 1
nop 0
dl 0
loc 7
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
	/** @var string */
10
	private $key;
11
	/** @var string */
12
	private $value;
13
14
	/**
15
	 * @param string $key
16
	 */
17
	public function __construct( string $key ) {
18
		$this->key = $key;
19
		$this->value = Config::getInstance()->getWikiMessage( $key );
20
	}
21
22
	/**
23
	 * @param array $args
24
	 * @return self
25
	 */
26
	public function params( array $args ) : self {
27
		$this->value = strtr( $this->value, $args );
28
		return $this;
29
	}
30
31
	/**
32
	 * @return string
33
	 */
34
	public function text() : string {
35
		$this->parsePlurals();
36
		return $this->value;
37
	}
38
39
	/**
40
	 * Replace {{$plur|<amount>|sing|plur}}
41
	 */
42
	protected function parsePlurals() {
43
		$this->value = preg_replace_callback(
44
			'!\{\{$plur|(?P<amount>\d+)|(?P<sing>[^}|]+)|(?P<plur>[^|}]+)}}!',
45
			function ( $matches ) {
46
				return intval( $matches['amount'] ) > 1 ? trim( $matches['plur'] ) : trim( $matches['sing'] );
47
			},
48
			$this->value
49
		);
50
	}
51
52
	/**
53
	 * Get a localized version of article + day + time
54
	 *
55
	 * @param int $timestamp
56
	 * @return string
57
	 */
58
	public static function getTimeWithArticle( int $timestamp ) : string {
59
		$oldLoc = setlocale( LC_TIME, 'it_IT', 'Italian_Italy', 'Italian' );
60
		$timeString = strftime( '%e %B alle %R', $timestamp );
61
		// Remove the left space if day has a single digit
62
		$timeString = ltrim( $timeString );
63
		$artic = in_array( date( 'j', $timestamp ), [ 8, 11 ] ) ? "l'" : "il ";
64
		setlocale( LC_TIME, $oldLoc );
65
66
		return $artic . $timeString;
67
	}
68
69
	/**
70
	 * Get a timestamp from a localized time string
71
	 *
72
	 * @param string $timeString
73
	 * @return int
74
	 * @todo Is there a better way?
75
	 */
76
	public static function getTimestampFromLocalTime( string $timeString ) : int {
77
		$oldLoc = setlocale( LC_TIME, 'it_IT', 'Italian_Italy', 'Italian' );
78
		$bits = strptime( $timeString, '%e %m %Y alle %H:%M' );
79
		$timestamp = mktime(
80
			$bits['tm_hour'],
81
			$bits['tm_min'],
82
			0,
83
			$bits['tm_mon'] + 1,
84
			$bits['tm_mday'],
85
			$bits['tm_year'] + 1900
86
		);
87
		setlocale( LC_TIME, $oldLoc );
88
89
		return $timestamp;
90
	}
91
}
92