1 /**
2 * Copyright © DiamondMVC 2019
3 * License: MIT (https://github.com/DiamondMVC/Diamond/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 */
6 module diamond.data.i18n.messages;
7 
8 import diamond.core.apptype;
9 
10 static if (isWeb)
11 {
12   import diamond.http;
13 
14   /// Alias for an associative array.
15   private alias Language = string[string];
16 
17   /// A collection of localization messages.
18   private __gshared Language[string] _messages;
19 
20   /// The default language.
21   package(diamond) __gshared string _defaultLanguage;
22 
23   /**
24   * Sets the default language of the application.
25   * Params:
26   *   language = The language.
27   */
28   void setDefaultLanguage(string language)
29   {
30     _defaultLanguage = language;
31   }
32 
33   /**
34   * Gets a message.
35   * Params:
36   *   clent = The client to use the language of.
37   *   key =   The key of the message to retrieve.
38   * Returns:
39   *   The message if found for the client's language, otherwise it will attempt to get the default language's message and if that fails too then it returns an empty string.
40   */
41   string getMessage(HttpClient client, string key)
42   {
43     return getMessage(client.language, key);
44   }
45 
46   /**
47   * Gets a message.
48   * Params:
49   *   languageName = The language to retrieve a message from.
50   *   key =          The key of the message to retrieve.
51   * Returns:
52   *   The message if found for the specified language, otherwise it will attempt to get the default language's message and if that fails too then it returns an empty string.
53   */
54   string getMessage(string languageName, string key)
55   {
56     auto language = _messages.get(languageName, null);
57 
58     if (!language)
59     {
60       language = _messages.get(_defaultLanguage, null);
61     }
62 
63     if (!language)
64     {
65       return "";
66     }
67 
68     return language.get(key, "");
69   }
70 
71   /**
72   * Adds a message to a specific language.
73   * Params:
74   *   language = The language to add the message to.
75   *   key =      The key of the message.
76   *   message =  The message to add.
77   */
78   void addMessage(string language, string key, string message)
79   {
80     _messages[language][key] = message;
81   }
82 }