3 namespace Drupal\Core\Annotation;
5 use Drupal\Component\Annotation\AnnotationBase;
6 use Drupal\Core\StringTranslation\TranslatableMarkup;
9 * @defgroup plugin_translatable Annotation for translatable text
11 * Describes how to put translatable UI text into annotations.
13 * When providing plugin annotation, properties whose values are displayed in
14 * the user interface should be made translatable. Much the same as how user
15 * interface text elsewhere is wrapped in t() to make it translatable, in plugin
16 * annotation, wrap translatable strings in the @ Translation() annotation.
19 * title = @ Translation("Title of the plugin"),
21 * Remove spaces after @ in your actual plugin - these are put into this sample
22 * code so that it is not recognized as annotation.
24 * To provide replacement values for placeholders, use the "arguments" array:
26 * title = @ Translation("Bundle !title", arguments = {"!title" = "Foo"}),
29 * It is also possible to provide a context with the text, similar to t():
31 * title = @ Translation("Bundle", context = "Validation"),
33 * Other t() arguments like language code are not valid to pass in. Only
34 * context is supported.
42 * Defines a translatable annotation object.
44 * Some metadata within an annotation needs to be translatable. This class
45 * supports that need by allowing both the translatable string and, if
46 * specified, a context for that string. The string (with optional context)
49 * @ingroup plugin_translatable
53 class Translation extends AnnotationBase {
56 * The string translation object.
58 * @var \Drupal\Core\StringTranslation\TranslatableMarkup
60 protected $translation;
63 * Constructs a new class instance.
65 * Parses values passed into this class through the t() function in Drupal and
66 * handles an optional context for the string.
68 * @param array $values
69 * Possible array keys:
70 * - value (required): the string that is to be translated.
71 * - arguments (optional): an array with placeholder replacements, keyed by
73 * - context (optional): a string that describes the context of "value";
75 public function __construct(array $values) {
76 $string = $values['value'];
77 $arguments = isset($values['arguments']) ? $values['arguments'] : [];
79 if (!empty($values['context'])) {
81 'context' => $values['context'],
84 $this->translation = new TranslatableMarkup($string, $arguments, $options);
90 public function get() {
91 return $this->translation;