class TestTranslator

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",
  files = TRUE,
)

Hierarchy

Expanded class hierarchy of TestTranslator

File

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

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) {

    /** @var \Drupal\tmgmt\Data $data_service */
    $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'];
        }
      }

      // Translate files.
      foreach ($data_service
        ->getTranslatableFiles($job_item
        ->getData()) as $key => $source_file) {
        $source_uri = $source_file
          ->getFileUri();
        $source_content = file_get_contents($source_uri);
        if ($target_langcode != $remote_target_langcode) {
          $translation_content = $target_langcode . '(' . $remote_target_langcode . '): ' . $source_content;
        }
        else {
          $translation_content = $target_langcode . ': ' . $source_content;
        }
        $translation_file = $data_service
          ->createFileTranslation($source_file, $target_langcode, $translation_content);
        $tdata[$key]['#file'] = $translation_file
          ->id();
      }
      $job_item
        ->addTranslatedData($data_service
        ->unflatten($tdata));
    }
    $groups = \Drupal::state()
      ->get('job_item_groups') ?: [];
    $groups[] = $group;
    \Drupal::state()
      ->set('job_item_groups', $groups);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
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