Debian Codegraph @

includes/libs/Message/README.md

raw symbols SCIP
1 Wikimedia Internationalization Library
2 ======================================
3
4 This library provides interfaces and value objects for internationalization (i18n)
5 of applications in PHP.
6
7 It is based on the i18n code used in MediaWiki, and is also intended to be
8 compatible with [jQuery.i18n], a JavaScript i18n library.
9
10 Concepts
11 --------
12
13 Any text string that is needed in an application is a **message**. This might
14 be something like a button label, a sentence, or a longer text. Each message is
15 assigned a **message key**, which is used as the identifier in code.
16
17 Each message is translated into various languages, each represented by a
18 **language code**. The message's text (as translated into each language) can
19 contain **placeholders**, which represents a place in the message where a
20 **parameter** is to be inserted, and **formatting commands**. It might be plain
21 text other than these placeholders and formatting commands, or it might be in a
22 **markup language** such as wikitext or Markdown.
23
24 A **formatter** is used to convert the message key and parameters
25 (that is, a **message specifier**) into a text
26 representation in a particular language and **output format**.
27
28 The library itself imposes few restrictions on all of these concepts; this
29 document contains recommendations to help various implementations operate in
30 compatible ways.
31
32 Usage
33 -----
34
35 <pre lang="php">
36 use Wikimedia\Message\MessageValue;
37 use Wikimedia\Message\MessageParam;
38 use Wikimedia\Message\ParamType;
39
40 // Constructor interface
41 $message = new MessageValue( 'message-key', [
42 'parameter',
43 new MessageValue( 'another-message' ),
44 new MessageParam( ParamType::NUM, 12345 ),
45 ] );
46
47 // Fluent interface
48 $message = MessageValue::new( 'message-key' )
49 ->params( 'parameter', new MessageValue( 'another-message' ) )
50 ->numParams( 12345 );
51
52 // Formatting
53 $messageFormatter = $serviceContainer->get( 'MessageFormatterFactory' )->getTextFormatter( 'de' );
54 $output = $messageFormatter->format( $message );
55 </pre>
56
57 Class Overview
58 --------------
59
60 ### Messages
61
62 Messages and their parameters are represented by newable value objects.
63
64 **MessageValue** represents an instance of a message, holding the key and any
65 parameters. It is mutable in that parameters can be added to the object after
66 creation.
67
68 **MessageSpecifier** is an interface implemented by MessageValue (and, outside
69 of the Wikimedia\Message namespace, also MediaWiki\Message\Message), which only
70 provides getter methods for the key and parameters, and no way to mutate
71 the object. It should be used in methods that output or inspect messages,
72 but aren't supposed to modify them.
73
74 **MessageParam** is an abstract value class representing a parameter to a message.
75 It has a type (using constants defined in the **ParamType** class) and a value. It
76 has two implementations:
77
78 - **ScalarParam** represents a single-valued parameter, such as a text string, a
79 number, or another message.
80 - **ListParam** represents a list of values, which will be joined together with
81 appropriate separators. It has a "list type" (using constants defined in the
82 **ListType** class) defining the desired separators.
83
84 #### Machine-readable messages
85
86 **DataMessageValue** represents a message with additional machine-readable
87 data. In addition to the key and message parameters, it holds a "code" and
88 structured data that would be a useful representation of the message in an API
89 response or the like.
90
91 For example, a message for an "integer out of range" error might have one of
92 three different keys depending on whether the range has a minimum, maximum, or
93 both. But all should have the same code (representing the concept of "integer
94 out of range") and should likely have structured data representing the range
95 directly as `[ 'min' => 1, 'max' => 10 ]` rather than as a flat array of
96 MessageParam objects.
97
98 ### Formatters
99
100 A formatter for a particular language is obtained from an implementation of
101 **IMessageFormatterFactory**. No implementation of this interface is provided by
102 this library. If an environment needs its formatters to vary behavior on things
103 other than the language code, for example selecting among multiple sources of
104 messages or markup language used for processing message texts, it should define
105 a MessageFormatterFactoryFactory of some sort to provide appropriate
106 IMessageFormatterFactory implementations.
107
108 There is no one base interface for all formatters; the intent is that type
109 hinting will ensure that the formatter being used will produce output in the
110 expected output format. The defined output formats are:
111
112 - **ITextFormatter** produces plain text output.
113
114 No implementation of these interfaces are provided by this library.
115
116 Formatter implementations are expected to perform the following procedure to
117 generate the output string:
118
119 1. Fetch the message's translation in the formatter's language. Details of this
120 fetching are unspecified here.
121 - If no translation is found in the formatter's language, it should attempt
122 to fall back to appropriate other languages. Details of the fallback are
123 unspecified here.
124 - If no translation can be found in any fallback language, a string should
125 be returned that indicates at minimum the message key that was unable to
126 be found.
127 2. Replace placeholders with parameter values.
128 - Note that placeholders must not be replaced recursively. That is, if a
129 parameter's value contains text that looks like a placeholder, it must not
130 be replaced as if it really were a placeholder.
131 - Certain types of parameters are not substituted directly at this stage.
132 Instead their placeholders must be replaced with an opaque representation
133 that will not be misinterpreted during later stages.
134 - Parameters of type RAW or PLAINTEXT
135 - TEXT parameters with a MessageValue as the value
136 - LIST parameters with any late-substituted value as one of their values.
137 3. Process any formatting commands.
138 4. Process the source markup language to produce a string in the desired output
139 format. This may be a no-op, and may be combined with the previous step if
140 the markup language implements compatible formatting commands.
141 5. Replace any opaque representations from step 2 with the actual values of
142 the corresponding parameters.
143
144 Guidelines for Interoperability
145 -------------------------------
146
147 Besides allowing for libraries to safely supply their own translations for
148 every app using them, and apps to easily use libraries' translations instead of
149 having to retranslate everything, following these guidelines will also help
150 open source projects use [translatewiki.net] for crowdsourced volunteer
151 translation into many languages.
152
153 ### Language codes
154
155 [BCP 47] language tags should be used for language codes. If a supplied
156 language tag is not recognized, at minimum the corresponding tag with all
157 optional subtags stripped should be tried as a fallback.
158
159 All messages must have a translation in English (code "en"). All languages
160 should fall back to English as a last resort.
161
162 The English translations should use `{{PLURAL:...}}` and `{{GENDER:...}}` even
163 when English doesn't make a grammatical distinction, to signal to translators
164 that plural/gender support is available.
165
166 Language code "qqq" is reserved for documenting messages. Documentation should
167 describe the context in which the message is used and the values of all
168 parameters used with the message. Generally this is written in English.
169 Attempting to obtain a message formatter for "qqq" should return one for "en"
170 instead.
171
172 Language code "qqx" is reserved for debugging. Rather than retrieving
173 translations from some underlying storage, every key should act as if it were
174 translated as something `(key-name: $1, $2, $3)` with the number of
175 placeholders depending on how many parameters are included in the
176 MessageValue.
177
178 ### Message keys
179
180 Message keys intended for use with external implementations should follow
181 certain guidelines for interoperability:
182
183 - Keys should be restricted to the regular expression `/^[a-z][a-z0-9-]*$/`.
184 That is, it should consist of lowercase ASCII letters, numbers, and hyphen
185 only, and should begin with a letter.
186 - Keys should be prefixed to help avoid collisions. For example, a library
187 named "ApplePicker" should prefix its message keys with "applepicker-".
188 - Common values needing translation, such as names of months and weekdays,
189 should not be prefixed by each library. Libraries needing these should use
190 keys from the [Common Locale Data Repository][CLDR] and document this
191 requirement, and environments should provide these messages.
192
193 ### Message format
194
195 Placeholders are represented by `$1`, `$2`, `$3`, and so on. Text like `$100`
196 is interpreted as a placeholder for parameter 100 if 100 or more parameters
197 were supplied, as a placeholder for parameter 10 followed by text "0" if
198 between ten and 99 parameters were supplied, and as a placeholder for parameter
199 1 followed by text "00" if between one and nine parameters were supplied.
200
201 All formatting commands look like `{{NAME:$value1|$value2|$value3|...}}`. Braces
202 are to be balanced, e.g. `{{NAME:foo|{{bar|baz}}}}` has $value1 as "foo" and
203 $value2 as "{{bar|baz}}". The name is always case-insensitive.
204
205 Anything syntactically resembling a placeholder or formatting command that does
206 not correspond to an actual parameter or known command should be left unchanged
207 for processing by the markup language processor.
208
209 Libraries providing messages for use by externally-defined formatters should
210 generally assume no markup language will be applied, and should avoid
211 constructs used by common markup languages unless they also make sense when
212 read as plain text.
213
214 ### Formatting commands
215
216 The following formatting commands should be supported.
217
218 #### PLURAL
219
220 `{{PLURAL:$count|$formA|$formB|...}}` is used to produce plurals.
221
222 $count is a number, which may have been formatted with ParamType::NUM.
223
224 The number of forms and which count corresponds to which form depend on the
225 language, for example English uses `{{PLURAL:$1|one|other}}` while Arabic uses
226 `{{PLURAL:$1|zero|one|two|few|many|other}}`. Details are defined in
227 [CLDR][CLDR plurals].
228
229 It is not possible to "skip" positions while still suppling later ones. If too
230 few values are supplied, the final form is repeated for subsequent positions.
231
232 If there is an explicit plural form to be given for a specific number, it may
233 be specified with syntax like `{{PLURAL:$1|one egg|$1 eggs|12=a dozen eggs}}`.
234
235 #### GENDER
236
237 `{{GENDER:$name|$masculine|$feminine|$unspecified}}` is used to handle
238 grammatical gender, typically when messages refer to user accounts.
239
240 This supports three grammatical genders: "male", "female", and a third option
241 for cases where the gender is unspecified, unknown, or neither male nor female.
242 It does not attempt to handle animate-inanimate or [T-V] distinctions.
243
244 $name is a user account name or other similar identifier. If the name given
245 does not correspond to any known user account, it should probably use the
246 $unspecified gender.
247
248 If $feminine and/or $unspecified is not specified, the value of $masculine
249 is normally used in its place.
250
251 #### GRAMMAR
252
253 `{{GRAMMAR:$form|$term}}` converts a term to an appropriate grammatical form.
254
255 If no mapping for $term to $form exists, $term should be returned unchanged.
256
257 See [jQuery.i18n § Grammar][jQuery.i18n grammar] for details.
258
259 #### BIDI
260
261 `{{BIDI:$text}}` applies directional isolation to the wrapped text, to attempt
262 to avoid errors where directionally-neutral characters are wrongly displayed
263 when between LTR and RTL content.
264
265 This should output U+202A (left-to-right embedding) or U+202B (right-to-left
266 embedding) before the text, depending on the directionality of the first
267 strongly-directional character in $text, and U+202C (pop directional
268 formatting) after, or do something equivalent for the target output format.
269
270 ### Supplying translations
271
272 Code intending its messages to be used by externally-defined formatters should
273 supply the translations as described by
274 [jQuery.i18n § Message File Format][jQuery.i18n file format].
275
276 In brief, the base directory of the library should contain a directory named
277 "i18n". This directory should contain JSON files named by code such as
278 "en.json", "de.json", "qqq.json", each with contents like:
279
280 ```json
281 {
282 "@metadata": {
283 "authors": [
284 "Alice",
285 "Bob",
286 "Carol",
287 "David"
288 ],
289 "last-updated": "2012-09-21"
290 },
291 "appname-title": "Example Application",
292 "appname-sub-title": "An example application",
293 "appname-header-introduction": "Introduction",
294 "appname-about": "About this application",
295 "appname-footer": "Footer text"
296 }
297 ```
298
299 Formatter implementations should be able to consume message data supplied in
300 this format, either directly via registration of i18n directories to check or
301 by providing tooling to incorporate it during a build step.
302
303 ### Machine-readable data
304
305 Libraries producing MessageValues as error messages should generally produce
306 DataMessageValues instead. Codes should be similar to message keys but need
307 not be prefixed. Data should be restricted to values that will produce valid
308 output when passed to `json_encode()`.
309
310 Libraries producing MessageValues in other contexts should consider whether the
311 same applies to those contexts.
312
313
314 ---
315 [jQuery.i18n]: https://github.com/wikimedia/jquery.i18n
316 [BCP 47]: https://tools.ietf.org/rfc/bcp/bcp47.txt
317 [CLDR]: http://cldr.unicode.org/
318 [CLDR plurals]: https://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html
319 [jQuery.i18n grammar]: https://github.com/wikimedia/jquery.i18n#grammar
320 [jQuery.i18n file format]: https://github.com/wikimedia/jquery.i18n#message-file-format
321 [translatewiki.net]: https://translatewiki.net/wiki/Translating:New_project
322 [T-V]: https://en.wikipedia.org/wiki/T%E2%80%93V_distinction