aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/xyz/driver/core/messages.scala
blob: 94d9889e07be3ea9e3ee581a6e86bf2131ff98cc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package xyz.driver.core

import java.util.Locale

import com.typesafe.config.Config
import xyz.driver.core.logging.Logger

import scala.collection.JavaConverters._

/**
  * Scala internationalization (i18n) support
  */
object messages {

  object Messages {
    def messages(config: Config, log: Logger, locale: Locale = Locale.US): Messages = {
      val map = config.getConfig(locale.getLanguage).root().unwrapped().asScala.mapValues(_.toString).toMap
      Messages(map, locale, log)
    }
  }

  final case class Messages(map: Map[String, String], locale: Locale, log: Logger) {

    /**
      * Returns message for the key
      *
      * @param key key
      * @return message
      */
    def apply(key: String): String = {
      map.get(key) match {
        case Some(message) => message
        case None =>
          log.error(s"Message with key '$key' not found for locale '${locale.getLanguage}'")
          key
      }
    }

    /**
      * Returns message for the key and formats that with parameters
      *
      * @example "Hello {0}!" with "Joe" will be "Hello Joe!"
      *
      * @param key key
      * @param params params to be embedded
      * @return formatted message
      */
    def apply(key: String, params: Any*): String = {

      def format(formatString: String, params: Seq[Any]) =
        params.zipWithIndex.foldLeft(formatString) {
          case (res, (value, index)) => res.replace(s"{$index}", value.toString)
        }

      val template = apply(key)
      format(template, params)
    }
  }
}