TranslatableMarkup.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. <?php
  2. namespace Drupal\Core\StringTranslation;
  3. use Drupal\Component\Render\FormattableMarkup;
  4. use Drupal\Component\Utility\ToStringTrait;
  5. /**
  6. * Provides translatable markup class.
  7. *
  8. * This object, when cast to a string, will return the formatted, translated
  9. * string. Avoid casting it to a string yourself, because it is preferable to
  10. * let the rendering system do the cast as late as possible in the rendering
  11. * process, so that this object itself can be put, untranslated, into render
  12. * caches and thus the cache can be shared between different language contexts.
  13. *
  14. * @see \Drupal\Component\Render\FormattableMarkup
  15. * @see \Drupal\Core\StringTranslation\TranslationManager::translateString()
  16. * @see \Drupal\Core\Annotation\Translation
  17. */
  18. class TranslatableMarkup extends FormattableMarkup {
  19. use ToStringTrait;
  20. /**
  21. * The translated markup without placeholder replacements.
  22. *
  23. * @var string
  24. */
  25. protected $translatedMarkup;
  26. /**
  27. * The translation options.
  28. *
  29. * @var array
  30. */
  31. protected $options;
  32. /**
  33. * The string translation service.
  34. *
  35. * @var \Drupal\Core\StringTranslation\TranslationInterface
  36. */
  37. protected $stringTranslation;
  38. /**
  39. * Constructs a new class instance.
  40. *
  41. * When possible, use the
  42. * \Drupal\Core\StringTranslation\StringTranslationTrait $this->t(). Otherwise
  43. * create a new \Drupal\Core\StringTranslation\TranslatableMarkup object
  44. * directly.
  45. *
  46. * Calling the trait's t() method or instantiating a new TranslatableMarkup
  47. * object serves two purposes:
  48. * - At run-time it translates user-visible text into the appropriate
  49. * language.
  50. * - Static analyzers detect calls to t() and new TranslatableMarkup, and add
  51. * the first argument (the string to be translated) to the database of
  52. * strings that need translation. These strings are expected to be in
  53. * English, so the first argument should always be in English.
  54. * To allow the site to be localized, it is important that all human-readable
  55. * text that will be displayed on the site or sent to a user is made available
  56. * in one of the ways supported by the
  57. * @link https://www.drupal.org/node/322729 Localization API @endlink.
  58. * See the @link https://www.drupal.org/node/322729 Localization API @endlink
  59. * pages for more information, including recommendations on how to break up or
  60. * not break up strings for translation.
  61. *
  62. * @section sec_translating_vars Translating Variables
  63. * $string should always be an English literal string.
  64. *
  65. * $string should never contain a variable, such as:
  66. * @code
  67. * new TranslatableMarkup($text)
  68. * @endcode
  69. * There are several reasons for this:
  70. * - Using a variable for $string that is user input is a security risk.
  71. * - Using a variable for $string that has even guaranteed safe text (for
  72. * example, user interface text provided literally in code), will not be
  73. * picked up by the localization static text processor. (The parameter could
  74. * be a variable if the entire string in $text has been passed into t() or
  75. * new TranslatableMarkup() elsewhere as the first argument, but that
  76. * strategy is not recommended.)
  77. *
  78. * It is especially important never to call new TranslatableMarkup($user_text)
  79. * or t($user_text) where $user_text is some text that a user entered -- doing
  80. * that can lead to cross-site scripting and other security problems. However,
  81. * you can use variable substitution in your string, to put variable text such
  82. * as user names or link URLs into translated text. Variable substitution
  83. * looks like this:
  84. * @code
  85. * new TranslatableMarkup("@name's blog", array('@name' => $account->getDisplayName()));
  86. * @endcode
  87. * Basically, you can put placeholders like @name into your string, and the
  88. * method will substitute the sanitized values at translation time. (See the
  89. * Localization API pages referenced above and the documentation of
  90. * \Drupal\Component\Render\FormattableMarkup::placeholderFormat()
  91. * for details about how to safely and correctly define variables in your
  92. * string.) Translators can then rearrange the string as necessary for the
  93. * language (e.g., in Spanish, it might be "blog de @name").
  94. *
  95. * @param string $string
  96. * A string containing the English text to translate.
  97. * @param array $arguments
  98. * (optional) An associative array of replacements to make after
  99. * translation. Based on the first character of the key, the value is
  100. * escaped and/or themed. See
  101. * \Drupal\Component\Render\FormattableMarkup::placeholderFormat() for
  102. * details.
  103. * @param array $options
  104. * (optional) An associative array of additional options, with the following
  105. * elements:
  106. * - 'langcode' (defaults to the current language): A language code, to
  107. * translate to a language other than what is used to display the page.
  108. * - 'context' (defaults to the empty context): The context the source
  109. * string belongs to.
  110. * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
  111. * (optional) The string translation service.
  112. *
  113. * @throws \InvalidArgumentException
  114. * Exception thrown when $string is not a string.
  115. *
  116. * @see \Drupal\Component\Render\FormattableMarkup::placeholderFormat()
  117. * @see \Drupal\Core\StringTranslation\StringTranslationTrait::t()
  118. *
  119. * @ingroup sanitization
  120. */
  121. public function __construct($string, array $arguments = [], array $options = [], TranslationInterface $string_translation = NULL) {
  122. if (!is_string($string)) {
  123. $message = $string instanceof TranslatableMarkup ? '$string ("' . $string->getUntranslatedString() . '") must be a string.' : '$string ("' . (string) $string . '") must be a string.';
  124. throw new \InvalidArgumentException($message);
  125. }
  126. parent::__construct($string, $arguments);
  127. $this->options = $options;
  128. $this->stringTranslation = $string_translation;
  129. }
  130. /**
  131. * Gets the untranslated string value stored in this translated string.
  132. *
  133. * @return string
  134. * The string stored in this wrapper.
  135. */
  136. public function getUntranslatedString() {
  137. return $this->string;
  138. }
  139. /**
  140. * Gets a specific option from this translated string.
  141. *
  142. * @param string $name
  143. * Option name.
  144. *
  145. * @return mixed
  146. * The value of this option or empty string of option is not set.
  147. */
  148. public function getOption($name) {
  149. return isset($this->options[$name]) ? $this->options[$name] : '';
  150. }
  151. /**
  152. * Gets all options from this translated string.
  153. *
  154. * @return mixed[]
  155. * The array of options.
  156. */
  157. public function getOptions() {
  158. return $this->options;
  159. }
  160. /**
  161. * Gets all arguments from this translated string.
  162. *
  163. * @return mixed[]
  164. * The array of arguments.
  165. */
  166. public function getArguments() {
  167. return $this->arguments;
  168. }
  169. /**
  170. * Renders the object as a string.
  171. *
  172. * @return string
  173. * The translated string.
  174. */
  175. public function render() {
  176. if (!isset($this->translatedMarkup)) {
  177. $this->translatedMarkup = $this->getStringTranslation()->translateString($this);
  178. }
  179. // Handle any replacements.
  180. if ($args = $this->getArguments()) {
  181. return $this->placeholderFormat($this->translatedMarkup, $args);
  182. }
  183. return $this->translatedMarkup;
  184. }
  185. /**
  186. * Magic __sleep() method to avoid serializing the string translator.
  187. */
  188. public function __sleep() {
  189. return ['string', 'arguments', 'options'];
  190. }
  191. /**
  192. * Gets the string translation service.
  193. *
  194. * @return \Drupal\Core\StringTranslation\TranslationInterface
  195. * The string translation service.
  196. */
  197. protected function getStringTranslation() {
  198. if (!$this->stringTranslation) {
  199. $this->stringTranslation = \Drupal::service('string_translation');
  200. }
  201. return $this->stringTranslation;
  202. }
  203. /**
  204. * Returns the string length.
  205. *
  206. * @return int
  207. * The length of the string.
  208. */
  209. public function count() {
  210. return mb_strlen($this->render());
  211. }
  212. }