Completed
Push — master ( 89b6ee...61842f )
by Morris
34:27 queued 17:16
created

L10N::getLocaleCode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
/**
4
 * @copyright Copyright (c) 2016, ownCloud, Inc.
5
 *
6
 * @author Georg Ehrke <[email protected]>
7
 * @author Joas Schilling <[email protected]>
8
 * @author Thomas Citharel <[email protected]>
9
 * @author Roeland Jago Douma <[email protected]>
10
 *
11
 * @license AGPL-3.0
12
 *
13
 * This code is free software: you can redistribute it and/or modify
14
 * it under the terms of the GNU Affero General Public License, version 3,
15
 * as published by the Free Software Foundation.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20
 * GNU Affero General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License, version 3,
23
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
24
 *
25
 */
26
27
namespace OC\L10N;
28
29
use OCP\IL10N;
30
use OCP\L10N\IFactory;
31
use Punic\Calendar;
32
use Symfony\Component\Translation\PluralizationRules;
33
34
class L10N implements IL10N {
35
36
	/** @var IFactory */
37
	protected $factory;
38
39
	/** @var string App of this object */
40
	protected $app;
41
42
	/** @var string Language of this object */
43
	protected $lang;
44
45
	/** @var string Locale of this object */
46
	protected $locale;
47
48
	/** @var string Plural forms (string) */
49
	private $pluralFormString = 'nplurals=2; plural=(n != 1);';
50
51
	/** @var string Plural forms (function) */
52
	private $pluralFormFunction = null;
53
54
	/** @var string[] */
55
	private $translations = [];
56
57
	/**
58
	 * @param IFactory $factory
59
	 * @param string $app
60
	 * @param string $lang
61
	 * @param string $locale
62
	 * @param array $files
63
	 */
64
	public function __construct(IFactory $factory, $app, $lang, $locale, array $files) {
65
		$this->factory = $factory;
66
		$this->app = $app;
67
		$this->lang = $lang;
68
		$this->locale = $locale;
69
70
		foreach ($files as $languageFile) {
71
			$this->load($languageFile);
72
		}
73
	}
74
75
	/**
76
	 * The code (en, de, ...) of the language that is used for this instance
77
	 *
78
	 * @return string language
79
	 */
80
	public function getLanguageCode(): string {
81
		return $this->lang;
82
	}
83
84
	/**
85
	 * The code (en_US, fr_CA, ...) of the locale that is used for this instance
86
	 *
87
	 * @return string locale
88
	 */
89
	public function getLocaleCode(): string {
90
		return $this->locale;
91
	}
92
93
	/**
94
	 * Translating
95
	 * @param string $text The text we need a translation for
96
	 * @param array|string $parameters default:array() Parameters for sprintf
97
	 * @return string Translation or the same text
98
	 *
99
	 * Returns the translation. If no translation is found, $text will be
100
	 * returned.
101
	 */
102
	public function t(string $text, $parameters = []): string {
103
		if (!\is_array($parameters)) {
104
			$parameters = [$parameters];
105
		}
106
107
		return (string) new L10NString($this, $text, $parameters);
108
	}
109
110
	/**
111
	 * Translating
112
	 * @param string $text_singular the string to translate for exactly one object
113
	 * @param string $text_plural the string to translate for n objects
114
	 * @param integer $count Number of objects
115
	 * @param array $parameters default:array() Parameters for sprintf
116
	 * @return string Translation or the same text
117
	 *
118
	 * Returns the translation. If no translation is found, $text will be
119
	 * returned. %n will be replaced with the number of objects.
120
	 *
121
	 * The correct plural is determined by the plural_forms-function
122
	 * provided by the po file.
123
	 *
124
	 */
125
	public function n(string $text_singular, string $text_plural, int $count, array $parameters = []): string {
126
		$identifier = "_${text_singular}_::_${text_plural}_";
127
		if (isset($this->translations[$identifier])) {
128
			return (string) new L10NString($this, $identifier, $parameters, $count);
129
		}
130
131
		if ($count === 1) {
132
			return (string) new L10NString($this, $text_singular, $parameters, $count);
133
		}
134
135
		return (string) new L10NString($this, $text_plural, $parameters, $count);
136
	}
137
138
	/**
139
	 * Localization
140
	 * @param string $type Type of localization
141
	 * @param \DateTime|int|string $data parameters for this localization
142
	 * @param array $options
143
	 * @return string|int|false
144
	 *
145
	 * Returns the localized data.
146
	 *
147
	 * Implemented types:
148
	 *  - date
149
	 *    - Creates a date
150
	 *    - params: timestamp (int/string)
151
	 *  - datetime
152
	 *    - Creates date and time
153
	 *    - params: timestamp (int/string)
154
	 *  - time
155
	 *    - Creates a time
156
	 *    - params: timestamp (int/string)
157
	 *  - firstday: Returns the first day of the week (0 sunday - 6 saturday)
158
	 *  - jsdate: Returns the short JS date format
159
	 */
160
	public function l(string $type, $data = null, array $options = []) {
161
		if (null === $this->locale) {
162
			// Use the language of the instance
163
			$this->locale = $this->getLanguageCode();
164
		}
165
		if ($this->locale === 'sr@latin') {
166
			$this->locale = 'sr_latn';
167
		}
168
169
		if ($type === 'firstday') {
170
			return (int) Calendar::getFirstWeekday($this->locale);
171
		}
172
		if ($type === 'jsdate') {
173
			return (string) Calendar::getDateFormat('short', $this->locale);
174
		}
175
176
		$value = new \DateTime();
177
		if ($data instanceof \DateTime) {
178
			$value = $data;
179
		} else if (\is_string($data) && !is_numeric($data)) {
180
			$data = strtotime($data);
181
			$value->setTimestamp($data);
182
		} else if ($data !== null) {
183
			$data = (int)$data;
184
			$value->setTimestamp($data);
185
		}
186
187
		$options = array_merge(['width' => 'long'], $options);
188
		$width = $options['width'];
189
		switch ($type) {
190
			case 'date':
191
				return (string) Calendar::formatDate($value, $width, $this->locale);
192
			case 'datetime':
193
				return (string) Calendar::formatDatetime($value, $width, $this->locale);
194
			case 'time':
195
				return (string) Calendar::formatTime($value, $width, $this->locale);
196
			case 'weekdayName':
197
				return (string) Calendar::getWeekdayName($value, $width, $this->locale);
198
			default:
199
				return false;
200
		}
201
	}
202
203
	/**
204
	 * Returns an associative array with all translations
205
	 *
206
	 * Called by \OC_L10N_String
207
	 * @return array
208
	 */
209
	public function getTranslations(): array {
210
		return $this->translations;
211
	}
212
213
	/**
214
	 * Returnsed function accepts the argument $n
215
	 *
216
	 * Called by \OC_L10N_String
217
	 * @return \Closure the plural form function
218
	 */
219
	public function getPluralFormFunction(): \Closure {
220
		if (\is_null($this->pluralFormFunction)) {
221
			$lang = $this->getLanguageCode();
222
			$this->pluralFormFunction = function($n) use ($lang) {
0 ignored issues
show
Documentation Bug introduced by
It seems like function ($n) use($lang)...ules::get($n, $lang); } of type object<Closure> is incompatible with the declared type string of property $pluralFormFunction.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
223
				return PluralizationRules::get($n, $lang);
224
			};
225
		}
226
227
		return $this->pluralFormFunction;
228
	}
229
230
	/**
231
	 * @param string $translationFile
232
	 * @return bool
233
	 */
234
	protected function load(string $translationFile): bool {
235
		$json = json_decode(file_get_contents($translationFile), true);
236 View Code Duplication
		if (!\is_array($json)) {
237
			$jsonError = json_last_error();
238
			\OC::$server->getLogger()->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']);
239
			return false;
240
		}
241
242
		if (!empty($json['pluralForm'])) {
243
			$this->pluralFormString = $json['pluralForm'];
244
		}
245
		$this->translations = array_merge($this->translations, $json['translations']);
246
		return true;
247
	}
248
}
249