You are here

public function GoogleTranslator::requestJobItemsTranslation in TMGMT Translator Google 8

Requests the translation of a JobItem.

Parameters

JobItemInterface[] $job_items: The JobItem we want to translate.

Overrides ContinuousTranslatorInterface::requestJobItemsTranslation

1 call to GoogleTranslator::requestJobItemsTranslation()
GoogleTranslator::requestTranslation in src/Plugin/tmgmt/Translator/GoogleTranslator.php
Implements TMGMTTranslatorPluginControllerInterface::requestTranslation().

File

src/Plugin/tmgmt/Translator/GoogleTranslator.php, line 322
Contains \Drupal\tmgmt_microsoft\Plugin\tmgmt\Translator\MicrosoftTranslator.

Class

GoogleTranslator
Google translator plugin.

Namespace

Drupal\tmgmt_google\Plugin\tmgmt\Translator

Code

public function requestJobItemsTranslation(array $job_items) {

  /** @var \Drupal\tmgmt\Entity\Job $job */
  $job = reset($job_items)
    ->getJob();
  foreach ($job_items as $job_item) {
    if ($job
      ->isContinuous()) {
      $job_item
        ->active();
    }

    // Pull the source data array through the job and flatten it.
    $data = \Drupal::service('tmgmt.data')
      ->filterTranslatable($job_item
      ->getData());
    $translation = array();
    $q = array();
    $keys_sequence = array();
    $i = 0;

    // Build Google q param and preserve initial array keys.
    foreach ($data as $key => $value) {
      $q[] = $value['#text'];
      $keys_sequence[] = $key;
    }
    try {

      // Split $q into chunks of self::qChunkSize.
      foreach (array_chunk($q, $this->qChunkSize) as $_q) {

        // Get translation from Google.
        $result = $this
          ->googleRequestTranslation($job, $_q);

        // Collect translated texts with use of initial keys.
        foreach ($result['data']['translations'] as $translated) {
          $translation[$keys_sequence[$i]]['#text'] = Html::decodeEntities($translated['translatedText']);
          $i++;
        }
      }

      // Save the translated data through the job.
      // NOTE that this line of code is reached only in case all translation
      // requests succeeded.
      $job_item
        ->addTranslatedData(\Drupal::service('tmgmt.data')
        ->unflatten($translation));
    } catch (TMGMTException $e) {
      $job
        ->rejected('Translation has been rejected with following error: @error', array(
        '@error' => $e
          ->getMessage(),
      ), 'error');
    }
  }
}