3 namespace Drupal\Core\StringTranslation;
5 use Drupal\Component\Render\FormattableMarkup;
6 use Drupal\Component\Utility\ToStringTrait;
7 use Drupal\Component\Utility\Unicode;
10 * Provides translatable markup class.
12 * This object, when cast to a string, will return the formatted, translated
13 * string. Avoid casting it to a string yourself, because it is preferable to
14 * let the rendering system do the cast as late as possible in the rendering
15 * process, so that this object itself can be put, untranslated, into render
16 * caches and thus the cache can be shared between different language contexts.
18 * @see \Drupal\Component\Render\FormattableMarkup
19 * @see \Drupal\Core\StringTranslation\TranslationManager::translateString()
20 * @see \Drupal\Core\Annotation\Translation
22 class TranslatableMarkup extends FormattableMarkup {
27 * The string to be translated.
34 * The translated markup without placeholder replacements.
38 protected $translatedMarkup;
41 * The translation options.
48 * The string translation service.
50 * @var \Drupal\Core\StringTranslation\TranslationInterface
52 protected $stringTranslation;
55 * Constructs a new class instance.
57 * When possible, use the
58 * \Drupal\Core\StringTranslation\StringTranslationTrait $this->t(). Otherwise
59 * create a new \Drupal\Core\StringTranslation\TranslatableMarkup object
62 * Calling the trait's t() method or instantiating a new TranslatableMarkup
63 * object serves two purposes:
64 * - At run-time it translates user-visible text into the appropriate
66 * - Static analyzers detect calls to t() and new TranslatableMarkup, and add
67 * the first argument (the string to be translated) to the database of
68 * strings that need translation. These strings are expected to be in
69 * English, so the first argument should always be in English.
70 * To allow the site to be localized, it is important that all human-readable
71 * text that will be displayed on the site or sent to a user is made available
72 * in one of the ways supported by the
73 * @link https://www.drupal.org/node/322729 Localization API @endlink.
74 * See the @link https://www.drupal.org/node/322729 Localization API @endlink
75 * pages for more information, including recommendations on how to break up or
76 * not break up strings for translation.
78 * @section sec_translating_vars Translating Variables
79 * $string should always be an English literal string.
81 * $string should never contain a variable, such as:
83 * new TranslatableMarkup($text)
85 * There are several reasons for this:
86 * - Using a variable for $string that is user input is a security risk.
87 * - Using a variable for $string that has even guaranteed safe text (for
88 * example, user interface text provided literally in code), will not be
89 * picked up by the localization static text processor. (The parameter could
90 * be a variable if the entire string in $text has been passed into t() or
91 * new TranslatableMarkup() elsewhere as the first argument, but that
92 * strategy is not recommended.)
94 * It is especially important never to call new TranslatableMarkup($user_text)
95 * or t($user_text) where $user_text is some text that a user entered -- doing
96 * that can lead to cross-site scripting and other security problems. However,
97 * you can use variable substitution in your string, to put variable text such
98 * as user names or link URLs into translated text. Variable substitution
101 * new TranslatableMarkup("@name's blog", array('@name' => $account->getDisplayName()));
103 * Basically, you can put placeholders like @name into your string, and the
104 * method will substitute the sanitized values at translation time. (See the
105 * Localization API pages referenced above and the documentation of
106 * \Drupal\Component\Render\FormattableMarkup::placeholderFormat()
107 * for details about how to safely and correctly define variables in your
108 * string.) Translators can then rearrange the string as necessary for the
109 * language (e.g., in Spanish, it might be "blog de @name").
111 * @param string $string
112 * A string containing the English text to translate.
113 * @param array $arguments
114 * (optional) An associative array of replacements to make after
115 * translation. Based on the first character of the key, the value is
116 * escaped and/or themed. See
117 * \Drupal\Component\Render\FormattableMarkup::placeholderFormat() for
119 * @param array $options
120 * (optional) An associative array of additional options, with the following
122 * - 'langcode' (defaults to the current language): A language code, to
123 * translate to a language other than what is used to display the page.
124 * - 'context' (defaults to the empty context): The context the source
126 * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
127 * (optional) The string translation service.
129 * @throws \InvalidArgumentException
130 * Exception thrown when $string is not a string.
132 * @see \Drupal\Component\Render\FormattableMarkup::placeholderFormat()
133 * @see \Drupal\Core\StringTranslation\StringTranslationTrait::t()
135 * @ingroup sanitization
137 public function __construct($string, array $arguments = [], array $options = [], TranslationInterface $string_translation = NULL) {
138 if (!is_string($string)) {
139 $message = $string instanceof TranslatableMarkup ? '$string ("' . $string->getUntranslatedString() . '") must be a string.' : '$string ("' . (string) $string . '") must be a string.';
140 throw new \InvalidArgumentException($message);
142 $this->string = $string;
143 $this->arguments = $arguments;
144 $this->options = $options;
145 $this->stringTranslation = $string_translation;
149 * Gets the untranslated string value stored in this translated string.
152 * The string stored in this wrapper.
154 public function getUntranslatedString() {
155 return $this->string;
159 * Gets a specific option from this translated string.
161 * @param string $name
165 * The value of this option or empty string of option is not set.
167 public function getOption($name) {
168 return isset($this->options[$name]) ? $this->options[$name] : '';
172 * Gets all options from this translated string.
175 * The array of options.
177 public function getOptions() {
178 return $this->options;
182 * Gets all arguments from this translated string.
185 * The array of arguments.
187 public function getArguments() {
188 return $this->arguments;
192 * Renders the object as a string.
195 * The translated string.
197 public function render() {
198 if (!isset($this->translatedMarkup)) {
199 $this->translatedMarkup = $this->getStringTranslation()->translateString($this);
202 // Handle any replacements.
203 if ($args = $this->getArguments()) {
204 return $this->placeholderFormat($this->translatedMarkup, $args);
206 return $this->translatedMarkup;
210 * Magic __sleep() method to avoid serializing the string translator.
212 public function __sleep() {
213 return ['string', 'arguments', 'options'];
217 * Gets the string translation service.
219 * @return \Drupal\Core\StringTranslation\TranslationInterface
220 * The string translation service.
222 protected function getStringTranslation() {
223 if (!$this->stringTranslation) {
224 $this->stringTranslation = \Drupal::service('string_translation');
227 return $this->stringTranslation;
231 * Returns the string length.
234 * The length of the string.
236 public function count() {
237 return Unicode::strlen($this->render());