StringTranslationTrait.php 2.35 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
<?php

/**
 * @file
 * Contains \Drupal\Core\StringTranslation\StringTranslationTrait.
 */

namespace Drupal\Core\StringTranslation;

/**
 * Wrapper methods for \Drupal\Core\StringTranslation\TranslationInterface.
 *
13 14
 * Using this trait will add t() and formatPlural() methods to the class. These
 * must be used for every translatable string, similar to how procedural code
15 16
 * must use the global functions t() and \Drupal::translation()->formatPlural().
 * This allows string extractor tools to find translatable strings.
17
 *
18 19 20 21 22 23
 * If the class is capable of injecting services from the container, it should
 * inject the 'string_translation' service and assign it to
 * $this->stringTranslation.
 *
 * @see \Drupal\Core\StringTranslation\TranslationInterface
 * @see container
24 25
 *
 * @ingroup i18n
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
 */
trait StringTranslationTrait {

  /**
   * The string translation service.
   *
   * @var \Drupal\Core\StringTranslation\TranslationInterface
   */
  protected $stringTranslation;

  /**
   * Translates a string to the current language or to a given language.
   *
   * See the t() documentation for details.
   */
  protected function t($string, array $args = array(), array $options = array()) {
    return $this->getStringTranslation()->translate($string, $args, $options);
  }

  /**
   * Formats a string containing a count of items.
   *
   * See the \Drupal\Core\StringTranslation\TranslationInterface::formatPlural()
   * documentation for details.
   */
  protected function formatPlural($count, $singular, $plural, array $args = array(), array $options = array()) {
    return $this->getStringTranslation()->formatPlural($count, $singular, $plural, $args, $options);
  }

  /**
   * Gets the string translation service.
   *
   * @return \Drupal\Core\StringTranslation\TranslationInterface
   *   The string translation service.
   */
  protected function getStringTranslation() {
    if (!$this->stringTranslation) {
      $this->stringTranslation = \Drupal::service('string_translation');
    }

    return $this->stringTranslation;
  }

  /**
   * Sets the string translation service to use.
   *
   * @param \Drupal\Core\StringTranslation\TranslationInterface $translation
   *   The string translation service.
   *
   * @return $this
   */
  public function setStringTranslation(TranslationInterface $translation) {
    $this->stringTranslation = $translation;

    return $this;
  }

}