You are here

class TestTranslator in Translation Management Tool 8

Test source plugin implementation.

Plugin annotation


@TranslatorPlugin(
  id = "test_translator",
  label = @Translation("Test provider"),
  description = @Translation("Simple provider for testing purposes."),
  default_settings = {
    "expose_settings" = TRUE,
  },
  ui = "Drupal\tmgmt_test\TestTranslatorUi",
  logo = "icons/tmgmt_test.svg",
)

Hierarchy

Expanded class hierarchy of TestTranslator

File

tmgmt_test/src/Plugin/tmgmt/Translator/TestTranslator.php, line 29

Namespace

Drupal\tmgmt_test\Plugin\tmgmt\Translator
View source
class TestTranslator extends TranslatorPluginBase implements TranslatorRejectDataInterface, ContinuousTranslatorInterface {

  /**
   * {@inheritdoc}
   */
  protected $escapeStart = '[[[';

  /**
   * {@inheritdoc}
   */
  protected $escapeEnd = ']]]';

  /**
   * {@inheritdoc}
   */
  public function getDefaultRemoteLanguagesMappings() {
    return array(
      'en' => 'en-us',
      'de' => 'de-ch',
    );
  }

  /**
   * {@inheritdoc}
   */
  public function hasCheckoutSettings(JobInterface $job) {
    return $job
      ->getTranslator()
      ->getSetting('expose_settings');
  }

  /**
   * {@inheritdoc}
   */
  function requestTranslation(JobInterface $job) {

    // Add a debug message.
    $job
      ->addMessage('Test translator called.', array(), 'debug');

    // Do something different based on the action, if defined.
    $action = $job
      ->getSetting('action') ?: '';
    switch ($action) {
      case 'submit':
        $job
          ->submitted('Test submit.');
        break;
      case 'reject':
        $job
          ->rejected('This is not supported.');
        break;
      case 'fail':

        // Target not reachable.
        $job
          ->addMessage('Service not reachable.', array(), 'error');
        break;
      case 'translate':
      default:
        $job
          ->submitted('Test translation created.');
        $this
          ->requestJobItemsTranslation($job
          ->getItems());
        break;
    }
  }

  /**
   * {@inheritdoc}
   */
  function checkTranslatable(TranslatorInterface $translator, JobInterface $job) {
    if ($job
      ->getSetting('action') == 'not_translatable') {
      return TranslatableResult::no(t('@translator can not translate from @source to @target.', array(
        '@translator' => $job
          ->getTranslator()
          ->label(),
        '@source' => $job
          ->getSourceLanguage()
          ->getName(),
        '@target' => $job
          ->getTargetLanguage()
          ->getName(),
      )));
    }
    return parent::checkTranslatable($translator, $job);
  }

  /**
   * {@inheritdoc}
   */
  function checkAvailable(TranslatorInterface $translator) {
    if ($translator
      ->getSetting('action') == 'not_available') {
      return AvailableResult::no(t('@translator is not available. Make sure it is properly <a href=:configured>configured</a>.', [
        '@translator' => $translator
          ->label(),
        ':configured' => $translator
          ->toUrl()
          ->toString(),
      ]));
    }
    return parent::checkAvailable($translator);
  }

  /**
   * {@inheritdoc}
   */
  public function getSupportedTargetLanguages(TranslatorInterface $translator, $source_language) {
    $languages = array(
      'en',
      'de',
      'es',
      'it',
      'pt',
      'zh-hans',
      'gsw-berne',
    );
    $languages = array_combine($languages, $languages);
    unset($languages[$source_language]);
    return $languages;
  }

  /**
   * {@inheritdoc}
   */
  public function rejectDataItem(JobItemInterface $job_item, array $key, array $values = NULL) {
    $key = '[' . implode('][', $key) . ']';
    $job_item
      ->addMessage('Rejected data item @key for job item @item in job @job.', array(
      '@key' => $key,
      '@item' => $job_item
        ->id(),
      '@job' => $job_item
        ->getJobId(),
    ));
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function rejectForm(array $form, FormStateInterface $form_state) {
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function requestJobItemsTranslation(array $job_items) {
    $data_service = \Drupal::service('tmgmt.data');
    $group = [];

    /** @var JobItemInterface $job_item */
    foreach ($job_items as $job_item) {
      $job = $job_item
        ->getJob();
      $target_langcode = $job
        ->getTargetLangcode();
      $remote_target_langcode = $job
        ->getRemoteTargetLanguage();
      $group[] = [
        'item_id' => $job_item
          ->id(),
        'job_id' => $job_item
          ->getJobId(),
      ];

      // Add a debug message.
      $job_item
        ->active('Requested translation to the continuous translator.', [], 'debug');

      // The dummy translation prefixes strings with the target language.
      $data = $data_service
        ->filterTranslatable($job_item
        ->getData());
      $tdata = [];
      foreach ($data as $key => $value) {

        // Special handling for path fields that start with the language
        // prefix, keep them valid by just replacing the path prefix.
        if (strpos($value['#text'], '/' . $job
          ->getSourceLangcode()) === 0) {
          $tdata[$key]['#text'] = str_replace('/' . $job
            ->getSourceLangcode(), '/' . $job
            ->getTargetLangcode(), $value['#text']);
        }
        elseif ($target_langcode != $remote_target_langcode) {
          $tdata[$key]['#text'] = $target_langcode . '(' . $remote_target_langcode . '): ' . $value['#text'];
        }
        else {
          $tdata[$key]['#text'] = $target_langcode . ': ' . $value['#text'];
        }
      }
      $job_item
        ->addTranslatedData($data_service
        ->unflatten($tdata));
    }
    $groups = \Drupal::state()
      ->get('job_item_groups') ?: [];
    $groups[] = $group;
    \Drupal::state()
      ->set('job_item_groups', $groups, $group);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. 92
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TestTranslator::$escapeEnd protected property Characters that indicate the end of an escaped string. Overrides TranslatorPluginBase::$escapeEnd
TestTranslator::$escapeStart protected property Characters that indicate the beginning of an escaped string. Overrides TranslatorPluginBase::$escapeStart
TestTranslator::checkAvailable function Checks whether a translator is available. Overrides TranslatorPluginBase::checkAvailable
TestTranslator::checkTranslatable function Check whether this service can handle a particular translation job. Overrides TranslatorPluginBase::checkTranslatable
TestTranslator::getDefaultRemoteLanguagesMappings public function Specifies default mappings for local to remote language codes. Overrides TranslatorPluginBase::getDefaultRemoteLanguagesMappings
TestTranslator::getSupportedTargetLanguages public function Returns all available target languages that are supported by this service when given a source language. Overrides TranslatorPluginBase::getSupportedTargetLanguages
TestTranslator::hasCheckoutSettings public function Returns if the translator has any settings for the passed job. Overrides TranslatorPluginBase::hasCheckoutSettings
TestTranslator::rejectDataItem public function Reject one single data item. Overrides TranslatorRejectDataInterface::rejectDataItem
TestTranslator::rejectForm public function Reject form. Overrides TranslatorRejectDataInterface::rejectForm
TestTranslator::requestJobItemsTranslation public function Requests the translation of a JobItem. Overrides ContinuousTranslatorInterface::requestJobItemsTranslation
TestTranslator::requestTranslation function @abstract Overrides TranslatorPluginInterface::requestTranslation
TranslatorPluginBase::abortTranslation public function Aborts a translation job. Overrides TranslatorPluginInterface::abortTranslation
TranslatorPluginBase::acceptedDataItem public function Accept a single data item. Overrides TranslatorPluginInterface::acceptedDataItem
TranslatorPluginBase::defaultSettings public function Defines default settings. Overrides TranslatorPluginInterface::defaultSettings 1
TranslatorPluginBase::escapeText public function Returns the escaped #text of a data item. Overrides TranslatorPluginInterface::escapeText
TranslatorPluginBase::getEscapedString protected function Returns the escaped string.
TranslatorPluginBase::getSupportedLanguagePairs public function Default implementation that gets target languages for each remote language. This approach is ineffective and therefore it is advised that a plugin should provide own implementation. Overrides TranslatorPluginInterface::getSupportedLanguagePairs 1
TranslatorPluginBase::getSupportedRemoteLanguages public function Gets all supported languages of the translator. Overrides TranslatorPluginInterface::getSupportedRemoteLanguages
TranslatorPluginBase::unescapeText public function Removes escape patterns from an escaped text. Overrides TranslatorPluginInterface::unescapeText